Secure Go code starts with strict input validation, parameterized SQL, explicit error handling, crypto/rand for secrets, TLS and timeouts on every network call, and regular scanning with govulncheck and go test -race. Go's memory safety removes whole bug classes, but injection, path traversal, weak crypto and concurrency bugs are still your job.
This guide lists the practices that matter most for services written in current Go, each with a short example.
Check every error, wrap it with context, and never leak internal details to clients. Return a generic message in the response and keep the detail in your logs.
Use errors.Is and errors.As for decisions, and %w when wrapping. Reserve panic for impossible states and add recovery middleware at the top of an HTTP server so one bad request cannot crash the process. Do not use log.Fatal in library code, because it skips deferred cleanup.
Treat all external data as hostile: request bodies, query strings, headers, file names and environment values.
../. Since Go 1.24, os.Root confines file access to a directory:html/template, which escapes by context, and never text/template for web output.exec.Command("tool", arg) with separate arguments and never pass user input through sh -c.Use the standard library and vetted packages, and do not invent your own schemes.
| Task | Use | Avoid |
|---|---|---|
| Random tokens | crypto/rand | math/rand |
| Password storage | argon2 or bcrypt from golang.org/x/crypto | MD5, SHA-1, plain SHA-256 |
| Encryption | AES-GCM or ChaCha20-Poly1305 through crypto/cipher | ECB mode, home-made ciphers |
| Comparing secrets | crypto/subtle.ConstantTimeCompare | == |
Never hard-code keys or passwords. Load secrets from the environment or a secret manager, and keep them out of logs and error messages.
The zero-value http.Server and http.Client have no timeouts, which makes them easy to exhaust. Set them explicitly:
Never set InsecureSkipVerify: true outside a throwaway test. Pass context.Context down to every call so cancellation and deadlines apply. Add security headers, authenticate and authorize every route, and store sessions in HttpOnly, Secure, SameSite cookies. Add rate limiting in front of expensive endpoints.
Go is memory safe, but data races on shared state still cause corruption and security flaws. Protect shared data with sync.Mutex, sync/atomic or ownership through channels, and make sure goroutines can always stop.
Run go test -race ./... in CI. Avoid the unsafe and reflect packages and cgo unless you need them, since they bypass the compiler's safety guarantees.
govulncheck ./... regularly. It reports only vulnerabilities your code can actually reach.go.sum, use go mod verify, and review new dependencies before adding them.go vet, staticcheck and gosec to catch risky patterns.log/slog structured fields, and never log passwords, tokens or full card numbers.Safe Go code is protected by bounds checks, which panic instead of corrupting memory. The unsafe package and cgo can reintroduce those bugs.
math/rand for tokens?No. Use crypto/rand for anything an attacker must not guess, such as session IDs, reset tokens and keys.
Pass user values as query parameters through database/sql placeholders, and never build SQL strings by concatenating input.
On every pull request and on a schedule, because new vulnerabilities are published against code you did not change.
html/template, and confine file access with os.Root.crypto/rand, modern password hashing and authenticated encryption.context everywhere.-race, and scan dependencies with govulncheck.