Access secret versions with the cloud.google.com/go/secretmanager client, verify checksums, load secrets once at startup, decide between latest and pinned versions, grant secretAccessor, and compare with secrets declared in Go.

Google Secret Manager holds the API keys and database passwords for services on GCP, and the Go client library reads them over gRPC. The call itself is short, while resource names, checksum verification, gRPC error codes and the secretAccessor grant decide whether a deploy starts cleanly.
This guide uses cloud.google.com/go/secretmanager v1.20 on Go 1.24.
secretmanager.NewClient uses Application Default Credentials, which on Cloud Run and GKE means the runtime service account. The program below reads two secrets at startup, verifies each checksum and turns the common gRPC errors into messages that say what to fix:
package main
import (
"context"
"fmt"
"hash/crc32"
"log"
"os"
secretmanager "cloud.google.com/go/secretmanager/apiv1"
"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
var crc32c = crc32.MakeTable(crc32.Castagnoli)
// accessSecret reads one version and verifies the payload checksum.
func accessSecret(ctx context.Context, c *secretmanager.Client, project, name, version string) (string, error) {
res, err := c.AccessSecretVersion(ctx, &secretmanagerpb.AccessSecretVersionRequest{
Name: fmt.Sprintf("projects/%s/secrets/%s/versions/%s", project, name, version),
})
if err != nil {
switch status.Code(err) {
case codes.NotFound:
return "", fmt.Errorf("secret %s/%s does not exist: %w", name, version, err)
case codes.PermissionDenied:
return "", fmt.Errorf("runtime account lacks secretAccessor on %s: %w", name, err)
}
return "", err
}
data := res.GetPayload().GetData()
if want := res.GetPayload().GetDataCrc32C(); want != 0 && int64(crc32.Checksum(data, crc32c)) != want {
return "", fmt.Errorf("secret %s: checksum mismatch", name)
}
return string(data), nil
}
type Config struct {
StripeKey string
DBPassword string
}
// loadConfig reads every secret once at startup, so a missing grant fails the
// deploy's health check instead of the first request that needs the value.
func loadConfig(ctx context.Context, project string) (*Config, error) {
c, err := secretmanager.NewClient(ctx) // Application Default Credentials
if err != nil {
return nil, err
}
defer c.Close()
var cfg Config
for name, dst := range map[string]*string{
"stripe-key": &cfg.StripeKey,
"db-password": &cfg.DBPassword,
} {
v, err := accessSecret(ctx, c, project, name, "latest")
if err != nil {
return nil, err
}
*dst = v
}
return &cfg, nil
}
func main() {
cfg, err := loadConfig(context.Background(), os.Getenv("GOOGLE_CLOUD_PROJECT"))
if err != nil {
log.Fatal(err)
}
log.Printf("loaded %d-character Stripe key", len(cfg.StripeKey))
}
Secret Manager returns a CRC32C checksum of the payload, computed with the Castagnoli polynomial, and hash/crc32 covers it without another dependency. The client is a gRPC connection, so create it once and close it when done, and avoid creating one per request.
Reading every secret before the server listens turns a missing secret or a missing grant into a failed startup, and Cloud Run keeps the previous revision serving when a new one never becomes healthy. The cost is that a rotated value only arrives with a restart, which is fine for API keys and acceptable for database passwords if your rotation keeps the previous password valid until the next deploy.
For values that must change without a restart, read latest per use with a short in-memory cache, and on an authentication failure clear the cache and read once more before giving up.
latest resolves to the newest enabled version at read time. A pinned version such as versions/7 only changes when you change it, which makes rollouts explicit, and Google's Secret Manager best practices recommend pinning in production. On Cloud Run, the same choice appears when you expose secrets with --set-secrets: environment variables are resolved once at instance start, so pin them, while a mounted volume reads the current value whenever the file is read.
Grant roles/secretmanager.secretAccessor on each secret to the service account the code runs as. Cloud Run services without an explicit service account run as the Compute Engine default account, which often has the broad Editor role in older projects, so a service that works may be relying on a grant you did not intend. Create a dedicated account per service and grant it only its own secrets.
There is no official emulator. Keep accessSecret behind the config struct, so tests construct a Config directly, and for local runs either read a development project with your own gcloud auth application-default login credentials or fall back to environment variables when a DEV flag is set.
Encore brings infrastructure from code, and secrets in Go are fields on a package-level struct that Encore fills in for each environment. On GCP the values are stored in Secret Manager in your project and injected into the service's containers, so the client, the checksum and the startup loader above are not code you keep.

Run in your terminal to get started locally.
// billing/billing.go
package billing
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"encore.dev/beta/errs"
)
// Encore reads this struct and supplies each field's value per environment.
var secrets struct {
StripeKey string
}
type RefundParams struct {
PaymentIntent string `json:"payment_intent"`
}
type RefundResponse struct {
RefundID string `json:"refund_id"`
}
//encore:api public method=POST path=/refunds
func Refund(ctx context.Context, p *RefundParams) (*RefundResponse, error) {
form := url.Values{"payment_intent": {p.PaymentIntent}}
req, err := http.NewRequestWithContext(ctx, http.MethodPost,
"https://api.stripe.com/v1/refunds", strings.NewReader(form.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+secrets.StripeKey)
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, &errs.Error{Code: errs.Unavailable, Message: fmt.Sprintf("stripe returned %d", resp.StatusCode)}
}
var body struct {
ID string `json:"id"`
}
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
return nil, err
}
return &RefundResponse{RefundID: body.ID}, nil
}
Values are set per environment type, and encore run uses the local value:
A deploy fails when a secret has no value for the target environment, which gives the same early failure as the startup loader. On deploy to your own GCP project, Encore stores the values in Secret Manager and injects them as environment variables, as the GCP infrastructure docs describe, and Encore provisions an IAM role for the service, a service account on GCP. The API endpoint is the normal Encore annotation, and errs.Unavailable maps to an HTTP 503.
Secret values never enter the repository, so a coding agent can add a ShippoKey field to the struct in the same change as the code that calls Shippo and run it locally, without ever seeing or committing the production value.
Best fit: Services on GCP that want each secret declared next to the code using it, with values per environment kept in their own project.
Create a client with secretmanager.NewClient(ctx) from cloud.google.com/go/secretmanager/apiv1 and call AccessSecretVersion with a secretmanagerpb.AccessSecretVersionRequest whose Name is projects/PROJECT/secrets/NAME/versions/latest. The value is res.Payload.Data as a byte slice.
Compute crc32.Checksum(data, crc32.MakeTable(crc32.Castagnoli)) and compare it with res.Payload.GetDataCrc32C(). Secret Manager returns the CRC32C of the payload so clients can detect corruption, and a mismatch should be treated as a failed read.
The identity running the code lacks secretmanager.versions.access on that secret. Grant roles/secretmanager.secretAccessor on the secret to the runtime service account, and check which account that is, since Cloud Run uses the Compute Engine default service account unless you set one.
Read them at startup for values that rarely change, so a missing grant or secret fails the deploy instead of a request. Read per request with a cache only when rotation must apply without a restart. Encore apps read secrets from a package-level struct whose values Encore supplies at startup.
Deploy to your cloud on AWS and Google Cloud
without managing infrastructure
Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.