Go¶
Scope: services, command-line tools and game servers written in Go, on the two releases the Go team supports: Go 1.27 (August 2026) and Go 1.26 (February 2026). Go 1.25 stopped receiving fixes when Go 1.27 came out. For configuration, health checks, telemetry and resilience, follow general/operations-reliability.md; for secrets, authorization and the supply chain, general/security.md; for test strategy and CI, the TEST rules in general/testing-delivery.md; for container images, Docker; for databases, PostgreSQL; and for hosting, scaling and securing game servers, Game servers and online services. The rules here cover what is specific to Go.
Entries are sorted by score from 1 to 10 (criteria): 9–10 start here or strongly recommended, 6–8 recommended, 1–5 further reading or conditional.
Adopted references¶
- 8 Go Style (Google): the baseline for code style: the canonical Style Guide, the normative Style Decisions, and Best Practices for naming, package size, errors, interfaces, concurrency, contexts, global state and tests. A few points refer to Google's internal libraries, such as its own
logpackage. - 8 Go Code Review Comments (Go wiki): the comments most often made in Go code reviews, such as contexts, goroutine lifetimes, error handling, interfaces and package names, each with a short name to cite in a review. Go Test Comments adds those for tests.
- 8 Organizing a Go module (Go): the official layouts for a package, a command, a module with several commands, and a server project, with
internal/andcmd/directories. - 8 Go Modules Reference (Go):
go.modandgo.sum, minimal version selection, module proxies, the checksum database and private modules. - 7 Security Best Practices for Go Developers (Go): scanning for known vulnerabilities with govulncheck, keeping Go and dependencies up to date, fuzzing, the race detector and
go vet. - 7 Effective Go (Go): idiomatic use of the core language, including interfaces, concurrency, errors,
panicandrecover. It was written for Go's release in 2009 and isn't actively updated, so it doesn't cover generics, modules or newer libraries. - 7 Release History (Go): the release policy, under which each major release is supported until there are two newer major releases, and what each minor release fixed.
- 7 Accessing relational databases (Go): the
database/sqlguides to opening a handle, querying, transactions, cancellation, the connection pool and avoiding SQL injection. - 7 A Guide to the Go Garbage Collector (Go): how
GOGCand the memory limit (GOMEMLIMIT) trade memory for CPU time. It advises a memory limit, with 5–10% headroom, for a service in a container with a fixed memory limit, and none for a command-line tool whose memory use depends on its input. - 6 Go Runtime (Heroic Labs, Nakama): writing Nakama server modules in Go. The plugin must be built for the same platform, with the same Go version and the same versions of shared dependencies as the Nakama binary; Dependency Pinning explains how.
Key rules¶
Code structure¶
- 6
GO-1Lay out a service as "Organizing a Go module" describes for a server project: each command incmd/<name>/, the packages that implement them underinternal/, and each package named for what it provides, notutil,commonorhelper. Other modules can't import packages underinternal/, so you can refactor them freely; move code into a module of its own only when other projects need it. (Go, Organizing a Go module: Server project, Go Code Review Comments, Package names, Go Style, Util packages, Go blog, Package names) - 6
GO-2Define interfaces in the package that uses them, keep them small, and return concrete types; don't add an interface before a consumer needs it, and don't export one from the implementing package only so that it can be mocked. Likewise, use type parameters only when you would otherwise write the same code for several types, and an interface when you only call methods. (Go Code Review Comments, Interfaces, Go Style, Interfaces, Go blog, When To Use Generics, Go Style, Generics)
Errors¶
- 7
GO-3Check every error, then either handle it or return it with added context, not both: don't discard errors with_, and don't log an error that you return. Wrap with%wonly when callers may need to inspect the cause, because the wrapped error becomes part of your API, and inspect errors witherrors.Isanderrors.As(orerrors.AsTypefrom Go 1.26), which also match wrapped errors, rather than with==, type assertions or string matching. (Go Code Review Comments, Handle errors, Go Style, Logging errors, Go blog, Whether to wrap, Go, errors package, Go Style, Error structure) - 7
GO-4Return anerrorfor every failure a caller can expect, such as invalid input, failed I/O or bad configuration, and panic only for bugs that tests and reviews should catch, such as API misuse or a broken invariant. In a server, recover at the top of each goroutine that serves one connection, job or match. A panic that reaches the top of any goroutine ends the whole process, with every other request or match in it;net/httprecovers panics inServeHTTP, but not in goroutines that a handler starts. (Go Code Review Comments, Don't panic, Go Style, When to panic, Effective Go, Recover, Go spec, Handling panics, net/http, Handler)
Context and concurrency¶
- 8
GO-5Pass the request'scontext.Contextalong the whole call chain, from the incoming request to every outgoing call, as the first parameter, namedctx; never store it in a struct, and use the context-aware APIs, such asQueryContextandhttp.NewRequestWithContext. Deadlines and cancellation then reach the database and the services you call: set the timeouts thatOPS-3asks for withcontext.WithTimeout, and always call thecancelfunction it returns. Never pass a nil context. (Go, context package, Go Code Review Comments, Contexts, Go blog, Contexts and structs, Go, Canceling in-progress operations) - 8
GO-7Never share a variable between goroutines without synchronization: hand data over on channels, or guard shared state, such as a cache, with async.Mutex, and run the tests with the race detector (go test -race) in CI. The race detector finds only races in code that runs, so it needs tests that exercise the concurrent paths, and it typically makes programs 2 to 20 times slower. (Effective Go, Share by communicating, Go wiki, Use a sync.Mutex or a channel?, Go Security Best Practices, Race detector, Go, Data Race Detector) - 7
GO-6Give each goroutine you start a context to stop on, and wait for it with async.WaitGroupor anerrgroup.Groupfromgolang.org/x/syncbefore the code that started it returns or shuts down. Prefer synchronous functions and let callers add concurrency.errgroup.WithContextcancels the group's context when one goroutine fails, and Go 1.27'sgoroutineleakprofile reports many goroutines that are blocked forever and never freed. This is how Go appliesPRIN-16. (Go Code Review Comments, Goroutine lifetimes, Synchronous functions, Go Style, Goroutine lifetimes, errgroup package, Go 1.27, Goroutine leak profile)
HTTP servers¶
- 7
GO-8Create everyhttp.Serveryourself and set its timeouts: alwaysReadHeaderTimeoutandIdleTimeout, andReadTimeoutandWriteTimeouttoo unless handlers set their own deadlines. Don't serve withhttp.ListenAndServeorhttp.Serve, which can't set timeouts. A zero timeout means no timeout, so a slow client can hold a connection and its goroutine as long as it likes. Handlers that need longer, such as uploads or streams, can extend their deadlines withhttp.ResponseController; limit request bodies withhttp.MaxBytesReader. This appliesAPI-11. (net/http, Server, net/http, ResponseController, net/http, MaxBytesReader, gosec, G112 and G114) - 7
GO-9Shut down onSIGTERM: derive the root context fromsignal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM), and when it's done, callServer.Shutdownwith a deadline shorter than the platform's grace period. By default aSIGTERMmakes a Go program exit.Shutdownstops listening and waits for active connections to go idle, but not for hijacked connections such as WebSockets: tell those to close from a function registered withRegisterOnShutdown. This appliesOPS-15andK8S-3. (os/signal, Default behavior of signals, os/signal, NotifyContext, net/http, Server.Shutdown, net/http, Server.RegisterOnShutdown)
Logging¶
- 6
GO-10Log withlog/slog: in a service, set a JSON handler on stdout as the default logger, withslog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil))), call the...Contextlogging methods so that handlers can add trace context, and give types that hold secrets aLogValuemethod that redacts them. AfterSetDefault, the standardlogpackage writes through the same handler. This appliesOPS-16andSEC-4. (Go blog, Structured Logging with slog, log/slog, Contexts, log/slog, SetDefault, log/slog, Customizing a type's logging behavior)
Dependencies and toolchain¶
- 8
GO-12Build with a supported Go release, one of the two newest major versions, at its latest minor version, and rungovulncheckon every change in CI and regularly on the code or binaries you have deployed. The Go team fixes critical problems, including security problems, in the supported releases by issuing minor releases. Set thetoolchainline ingo.modto the release you build with, so that thegocommand, with its defaultGOTOOLCHAIN=auto, switches to it when a local toolchain is older. This appliesSEC-17. (Go, Release policy, Go Security Best Practices, Keep your Go version and dependencies up to date, Scan source code and binaries, Go Toolchains, govulncheck) - 7
GO-11Commitgo.modandgo.sum, change dependencies only withgo getorgo mod tidyin a reviewed change, and fail CI whengo mod tidy -diffreports a difference. Keep the public module proxy and checksum database for public modules, and list private modules inGOPRIVATE, which keeps them away from both, instead of settingGOSUMDB=off, which stops checking any module against the checksum database. This appliesSEC-15. (Go blog, How Go Mitigates Supply Chain Attacks, Go wiki, Should I commit my go.sum file?, Go Modules Reference, go mod tidy, Private modules, Authenticating modules)
Data and output¶
- 9
GO-13Never build SQL statements or HTML by formatting or concatenating strings with values: pass values to SQL as arguments for placeholders (?or$1), and render HTML withhtml/template, nottext/template. Convert a value totemplate.HTMLor another of its trusted types only if it comes from a trusted source or a sound HTML sanitizer, because it is inserted without escaping. This appliesSEC-18andWEB-8. (Go, Avoiding SQL injection risk, html/template, html/template, HTML) - 7
GO-14Open onesql.DBfor each database when the program starts and share it, because it is a connection pool that is safe for concurrent use, and close everysql.Rowswithdefer rows.Close()and checkrows.Err(). By default the pool opens a new connection whenever all are busy, with no limit: if all your instances together could open more connections than the database accepts, cap them withSetMaxOpenConns, so that callers wait for a free connection, or add a pooler (PG-9). (Go, database/sql Open, Go, Managing connections, Go, Querying for data: multiple rows)
Testing and code quality¶
- 7
GO-15In CI, fail the build on unformatted code (gofmt -l), on anygo vet ./...finding and on linter findings, for example from Staticcheck or golangci-lint.go testruns only a high-confidence subset of the vet checks, which leaves out checks such aslostcancelandcopylocks, so rungo veton its own. (Go Code Review Comments, Gofmt, Go Style Guide, Formatting, go command, Test packages, Go, cmd/vet, Staticcheck) - 6
GO-16Fuzz the code that parses untrusted input, such as request decoders and network protocol handlers, withgo test -fuzz, and test code with timers, timeouts or background goroutines insidesynctest.Testinstead of waiting in real time. Commit the failing inputs that fuzzing saves undertestdata/fuzz, whichgo testthen runs as regression tests.synctest.Testruns the test on a fake clock, waits for its goroutines to exit, and fails if they deadlock. (Go Security Best Practices, Fuzzing, Go Fuzzing, testing/synctest)
How to enforce¶
Tools that check the key rules above automatically, in CI, the IDE or a commit hook. "Partly" means the tool covers only some of what the rule asks.
- 7 go vet:
go vet ./...exits with a non-zero status when it reports a problem. Itslostcancelcheck reportscancelfunctions that aren't called on every path,copylocksreports locks copied by value,errorsasreports wrong arguments toerrors.As, and from Go 1.27printfreports%woperands that are pointers to an error type. ChecksGO-15, and partlyGO-3andGO-5. - 7 Data Race Detector:
go test -racereports the data races that happen while the tests run, with the stacks of the conflicting accesses, and exits with a non-zero status (66 by default). Partly checksGO-7. - 7 go mod tidy -diff: prints the changes that
go.modandgo.sumneed without making them, and exits with a non-zero status if there are any;go mod verifyfails when a downloaded module in the cache has changed. Partly checksGO-11. - 6 gofmt:
gofmt -l .lists the files whose formatting differs from gofmt's; fail CI when it lists any. Partly checksGO-15. - 6 govulncheck exit codes:
govulncheck ./...exits with a non-zero status when it finds known vulnerabilities, in the standard library or in dependencies, that affect the code, unless you ask for JSON, SARIF or OpenVEX output. It analyzes source code with the Go version on thePATH, and a binary with the version that built it, so it covers that release's standard library too. Partly checksGO-12. - 6 golangci-lint: runs many linters in one pass, with errcheck, govet, ineffassign, staticcheck and unused on by default; errcheck reports unchecked errors. Also enable errorlint with its
comparisonandassertschecks, for errors compared with==or type assertions, containedctx for contexts stored in structs, noctx for HTTP, network and database calls made without a context, and sloglint withcontext: allforslogcalls without a context. ChecksGO-15, and partlyGO-3,GO-5andGO-10. - 6 gosec: G112 reports an
http.ServerwithoutReadHeaderTimeout, G114 thenet/httpserve functions that can't set timeouts, G201 and G202 SQL built with format strings or concatenation, G203 unescaped data in HTML templates, G701 SQL injection found by taint analysis, and G118 unusedcancelfunctions, goroutines that usecontext.Background()where a request context exists, and I/O loops that never checkctx.Done(). It exits with status 1 on findings, and also runs inside golangci-lint. Partly checksGO-5,GO-6,GO-8andGO-13. - 6 Staticcheck checks: more than 150 checks for bugs, performance problems and style, such as SA1012 for a nil
context.Context. Runstaticcheck ./...in CI, or through golangci-lint, which enables it by default. ChecksGO-15, and partlyGO-5.
Tutorials and further reading¶
- 7 How to Write Go Code (Go): code organization in modules and packages, your first program, importing packages from your module and from remote modules, and testing, with the
gocommand. - 6 A Tour of Go (Go): the official interactive introduction to the syntax and data structures, methods and interfaces, and concurrency primitives.
- 6 Tutorial: Accessing a relational database (Go): querying, adding data and handling errors with
database/sql, step by step. - 6 Tutorial: Getting started with fuzzing and Tutorial: Find and fix vulnerable dependencies with govulncheck (Go): writing and running a fuzz test, and scanning, assessing and fixing a vulnerable dependency.
- 6 Routing Enhancements for Go 1.22 (Go blog): method matching and wildcards in
net/http'sServeMux, which cover the routing needs of many services without a third-party router. - 6 TableDrivenTests (Go wiki): table-driven tests with named subtests, and running them in parallel with
t.Parallel(). - 6 Learn Go with Tests (Chris James, free online): the language, the standard library and building an HTTP server, through test-driven development.
- 5 Go Concurrency Patterns: Context and Pipelines and cancellation (Go blog, 2014): how a server passes deadlines and cancellation to all the goroutines that handle a request, and how to build pipelines of goroutines that exit cleanly when a stage fails.
- 5 The Go Programming Language (Alan Donovan and Brian Kernighan, 2015): a thorough book on the language, concurrency, packages and testing. It predates modules and generics.