Nov 17, 20267 min read

How to Add Secrets to a Go net/http App

Keep a webhook HMAC key and a carrier API token out of a standard library net/http repository, with Encore secrets set per environment or with .env files and AWS Secrets Manager on ECS.

Illustration for How to Add Secrets to a Go net/http App

The Go standard library can verify a webhook and call a carrier API from an http.ServeMux handler, and the code for HMAC comparison and an Authorization header is short.

The keys those calls need should never sit in the repository or in a container image: they have to be set per environment, rotated without a code change, and kept out of logs, which means a secrets manager in production and a way to load local values that does not get committed.

This guide adds a webhook signing secret and a carrier API token to a net/http shipping API. It starts with Encore, which declares the secrets in Go next to the ServeMux and stores the values outside the repo, then shows the same handlers with a .env file locally and AWS Secrets Manager on ECS.

Secrets options for a net/http app at a glance

Encore.env + AWS Secrets Manager
Secrets declared inA var secrets struct in GoEnvironment variable names in code
Values stored inEncrypted with GCP KMS outside the repository; on deploy, replicated to a secrets manager in your account (AWS Secrets Manager on AWS, or a secrets manager in your GCP project).env locally (gitignored), Secrets Manager in production
Local valuesencore secret set --type local or .secrets.local.cueA .env file loaded at startup
Production injectionInjected into the container as secret environment variables from the secrets manager in your accountTask definition or a client call at startup
Readable from the repoProduction values are not in the repository; a local .secrets.local.cue file is readable if presentOnly if someone commits .env
CloudAWS or GCP, in your accountAWS

How do you manage secrets in net/http with Encore?

Encore

Encore works alongside a plain net/http app: the ServeMux and its handlers stay standard library code, and the secrets they use are an unexported struct next to them. A raw endpoint is an ordinary http.HandlerFunc, so the mux is mounted in one fallback route. The secrets API lets you set a value per environment type with encore secret set. Production values are not stored in the repository, so an AI coding agent working in the repo cannot read those from git. A local override in .secrets.local.cue is a file on disk and is readable.

A coding agent can add the secrets struct and the webhook handler in the same change, then you set the local values yourself with encore secret set --type local before running encore run.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

~
$ encore app create shipping-api --example=hello-world$ cd shipping-api$ encore secret set --type local,dev,preview WebhookSecret$ encore secret set --type local,dev,preview CarrierToken

The service rejects a missing or short webhook secret at startup, verifies inbound webhooks with HMAC-SHA256, and uses the carrier token only on the outbound call:

// shipping/shipping.go package shipping import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "encoding/json" "bytes" "errors" "io" "net/http" "strings" "time" ) // Values are set per environment with `encore secret set` and never live in the repo. var secrets struct { WebhookSecret string // HMAC key for inbound carrier webhooks CarrierToken string // bearer token for the outbound carrier API } var carrierHTTP = &http.Client{Timeout: 10 * time.Second} //encore:service type Service struct { mux *http.ServeMux } func initService() (*Service, error) { if len(secrets.WebhookSecret) < 32 { return nil, errors.New("WebhookSecret must be at least 32 bytes") } if secrets.CarrierToken == "" { return nil, errors.New("CarrierToken is required") } mux := http.NewServeMux() mux.HandleFunc("POST /webhooks/carrier", handleWebhook) mux.HandleFunc("POST /shipments", createShipment) return &Service{mux: mux}, nil } //encore:api public raw path=/!fallback func (s *Service) Fallback(w http.ResponseWriter, req *http.Request) { s.mux.ServeHTTP(w, req) } func handleWebhook(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) if err != nil { http.Error(w, "could not read body", http.StatusBadRequest) return } sig := r.Header.Get("X-Signature-256") mac := hmac.New(sha256.New, []byte(secrets.WebhookSecret)) mac.Write(body) expected := hex.EncodeToString(mac.Sum(nil)) if sig == "" || !hmac.Equal([]byte(sig), []byte(expected)) { http.Error(w, "bad signature", http.StatusUnauthorized) return } var ev struct { TrackingID string `json:"tracking_id"` Status string `json:"status"` } if err := json.Unmarshal(body, &ev); err != nil || ev.TrackingID == "" { http.Error(w, "invalid payload", http.StatusBadRequest) return } // Persist ev.TrackingID and ev.Status here. w.WriteHeader(http.StatusNoContent) } func createShipment(w http.ResponseWriter, r *http.Request) { var in struct { OrderID string `json:"order_id"` Address string `json:"address"` } if err := json.NewDecoder(r.Body).Decode(&in); err != nil || strings.TrimSpace(in.OrderID) == "" { http.Error(w, "order_id is required", http.StatusBadRequest) return } payload, err := json.Marshal(in) if err != nil { http.Error(w, "could not encode request", http.StatusInternalServerError) return } req, err := http.NewRequestWithContext(r.Context(), http.MethodPost, "https://carrier.example.com/v1/shipments", bytes.NewReader(payload)) if err != nil { http.Error(w, "could not build request", http.StatusInternalServerError) return } req.Header.Set("Authorization", "Bearer "+secrets.CarrierToken) req.Header.Set("Content-Type", "application/json") resp, err := carrierHTTP.Do(req) if err != nil { http.Error(w, "carrier API unavailable", http.StatusBadGateway) return } defer resp.Body.Close() w.WriteHeader(resp.StatusCode) _, _ = io.Copy(w, resp.Body) }

Set production values with encore secret set --type prod WebhookSecret before the first deploy to your own AWS or GCP account. When a secret is missing in a cloud environment, the deploy fails until the value is set. On deploy, Encore replicates the values into a secrets manager in your account. Encore provisions an IAM role for the service, or a service account on GCP. Local values can also be overridden in .secrets.local.cue next to encore.app, which should stay out of git.

Best fit: a net/http API that wants secrets declared in code, with injection handled in your own AWS or GCP account.

.env locally and AWS Secrets Manager on ECS

The same handlers can read os.Getenv("WEBHOOK_SECRET") and os.Getenv("CARRIER_TOKEN"). Locally, load a gitignored .env file at startup. In production, store the values in AWS Secrets Manager and inject them into the ECS task definition with valueFrom, so the process still sees environment variables and the values never land in the image or the repo.

// cmd/api/main.go package main import ( "crypto/hmac" "crypto/sha256" "encoding/hex" "errors" "io" "log" "net/http" "os" "time" ) type api struct { webhookSecret string carrierToken string } func main() { a, err := newAPI() if err != nil { log.Fatal(err) } mux := http.NewServeMux() mux.HandleFunc("POST /webhooks/carrier", a.handleWebhook) srv := &http.Server{Addr: ":8080", Handler: mux, ReadHeaderTimeout: 5 * time.Second} log.Fatal(srv.ListenAndServe()) } func newAPI() (*api, error) { secret := os.Getenv("WEBHOOK_SECRET") token := os.Getenv("CARRIER_TOKEN") if len(secret) < 32 || token == "" { return nil, errors.New("WEBHOOK_SECRET and CARRIER_TOKEN must be set") } return &api{webhookSecret: secret, carrierToken: token}, nil } func (a *api) handleWebhook(w http.ResponseWriter, r *http.Request) { body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) if err != nil { http.Error(w, "could not read body", http.StatusBadRequest) return } mac := hmac.New(sha256.New, []byte(a.webhookSecret)) mac.Write(body) if !hmac.Equal([]byte(r.Header.Get("X-Signature-256")), []byte(hex.EncodeToString(mac.Sum(nil)))) { http.Error(w, "bad signature", http.StatusUnauthorized) return } w.WriteHeader(http.StatusNoContent) }

Grant the task role secretsmanager:GetSecretValue on those secret ARNs only. Rotate the webhook secret by writing a new version, deploying a window where both signatures are accepted, then retiring the old value.

Best fit: teams that already inject Secrets Manager values into ECS and want the net/http process to stay a plain binary.

Environment variables only

Reading os.Getenv with no manager behind it works on a laptop and falls over in production the first time a value is pasted into a shell history, a CI log or a compose file that gets committed. Use it for throwaway local runs, then move the values into a manager before the API leaves your machine.

Best fit: short-lived local experiments.

How to choose

Pick Encore when you want secrets declared next to the ServeMux, values kept out of the repository, and injection handled in your own AWS or GCP account. Pick .env plus Secrets Manager when the task definition already injects those values and you want to keep the API a plain net/http binary. Environment variables with no manager are not enough once a webhook secret can be used to forge events.

The verification pattern itself does not depend on the choice: read the raw body, compute HMAC-SHA256, and compare with hmac.Equal before parsing JSON, as in the webhook signature construction.

Frequently asked questions

How do I store secrets in a Go net/http app?

Read them from the environment at startup, keep any local .env file out of git, and in production inject the values from a secrets manager, such as AWS Secrets Manager referenced in the ECS task definition. Validate required secrets at startup so a missing or too-short key stops the service instead of failing on the first request.

How do I manage secrets in a net/http app with Encore?

Declare a package-level var secrets struct with one string field per secret, set the values with encore secret set or in the Secrets Manager, and read them as ordinary fields in your handlers. Production secret values are not stored in the repository, so an AI coding agent working in the repo cannot read those from git. A local override in .secrets.local.cue is a file on disk and is readable. Mount the ServeMux in a raw endpoint with path=/!fallback.

How do I verify a webhook signature in net/http?

Read the raw body, compute HMAC-SHA256 with the webhook secret, and compare it to the signature header with hmac.Equal so the comparison takes constant time. Reject the request if the header is missing or the signatures do not match, and only then parse the JSON.

Where should production secrets live on AWS?

Store them in AWS Secrets Manager or SSM Parameter Store, grant the task role permission to read those secrets, and inject them as environment variables or retrieve them at startup. Do not commit the values, and do not bake them into the container image.

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.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders