Go Knowledge Patch
Use this skill before changing Go source, modules, build pipelines, tests,
cryptographic code, HTTP stacks, runtime integrations, or platform-specific
builds. Read the relevant topic reference before relying on older defaults,
removed commands, compatibility switches, or byte-for-byte encoded output.
Reference index
| Reference |
Topics |
| language-and-core.md |
Language syntax, iterators, templates, errors, reflection, source positions, time, regular expressions, and Unicode |
| tooling-modules-and-testing.md |
Modules, workspaces, go commands, vet, caches, source modernization, testing, and profiling tools |
| runtime-and-observability.md |
Garbage collection, scheduling, traces, crash recovery, cleanup, heap layout, and runtime metrics |
| filesystem-data-and-encoding.md |
Rooted filesystems, links, tar, JSON, compression, JPEG, UUIDs, Windows handles, and fstest |
| networking-and-http.md |
DNS, HTTP protocols, redirects, reverse proxies, CSRF, URL parsing, MPTCP, and connection reuse |
| crypto-tls-and-x509.md |
FIPS, randomness, signing, KEM and HPKE, RSA, X.509, SHA-3, TLS defaults, and certificate roots |
| build-linking-and-platforms.md |
Cgo, linker behavior, build IDs, sanitizers, WASI, architecture profiles, ports, SIMD, and bootstrap floors |
Breaking changes and deprecations
Replace removed and unsafe APIs
- Replace
go tool doc and cmd/doc with go doc. It also accepts
package@version; use -ex to list executable examples.
- Replace
httputil.ReverseProxy.Director with Rewrite. A client-selected
hop-by-hop declaration can remove headers added by Director.
- Stop calling undocumented CTR, GCM, or CBC methods on the concrete block
returned by
aes.NewCipher; use crypto/cipher constructors.
- Replace deprecated OFB and CFB helpers with authenticated
AEAD modes, or
NewCTR only when unauthenticated streaming is unavoidable.
- Migrate away from PKCS #1 v1.5 encryption and direct use of ECDSA key
big.Int fields.
- Replace deprecated AST package-merging APIs and
parser.ParseDir in source
tools.
Account for stricter behavior
- Check a call's error before dereferencing its result. Required nil checks
happen at the dereference rather than being delayed.
- Expect
url.Parse to reject malformed hosts with ambiguous colons; bracket
IPv6 literals.
- Expect
time.Parse and time.ParseInLocation to reject out-of-range zone
offsets.
- Expect RSA operations to reject keys smaller than 1024 bits and X.509
verification to reject SHA-1 signatures.
- Do not assume caller-supplied randomness controls DSA, ECDH, RSA, ECDSA,
rand.Prime, or every Ed25519 key-generation path. Use
testing/cryptotest.SetGlobalRandom for deterministic tests.
- Update golden files and cache keys that require byte-identical JPEG or
DEFLATE-family output.
- Treat
runtime.AddCleanup callbacks as concurrent and potentially parallel.
- Expect
testing.AllocsPerRun to panic while parallel tests are active.
- Treat unknown fields such as
OutputType in go test -json records as
forward-compatible structured data.
Audit changed defaults
- Green Tea is the default garbage collector. Use
GOEXPERIMENT=nogreenteagc only as a temporary diagnostic escape hatch
where the selected toolchain still supports it.
- Linux
GOMAXPROCS observes cgroup CPU bandwidth, and the runtime periodically
refreshes its default on every OS.
net.ListenConfig enables Multipath TCP by default where supported.
- Post-quantum hybrid TLS exchanges are enabled by default unless
CurvePreferences or the applicable GODEBUG switch disables them.
ServeMux trailing-slash redirects use status 307.
ServeContent, ServeFile, and ServeFileFS strip caching and encoding
headers from error responses.
- Closing an HTTP/1 response body may drain unread data to preserve connection
reuse; disable keep-alives when reuse is intentionally unwanted.
go mod init deliberately selects an older language version than the stable
toolchain executing it.
go build -asan performs leak detection at process exit by default.
- DWARF 5 and native ELF or Mach-O build identifiers are emitted by default.
- The JSON v2 implementation backs
encoding/json; it rejects invalid UTF-8
and duplicate object names through the v2 APIs.
Language quick reference
Range over iterator functions
Use one of these push-iterator shapes:
func(func() bool)
func(func(V) bool)
func(func(K, V) bool)
Stop producing values when yield returns false. Prefer the named
iter.Seq[V] and iter.Seq2[K, V] forms; there is no Seq0.
func (s *Set[E]) All() iter.Seq[E] {
return func(yield func(E) bool) {
for value := range s.m {
if !yield(value) {
return
}
}
}
}
For pull-style consumption, call iter.Pull and always arrange for stop
when iteration can end early:
next, stop := iter.Pull(seq)
defer stop()
for value, ok := next(); ok; value, ok = next() {
use(value)
}
Select language version 1.23 or newer before using range-over-function syntax.
See language-and-core.md for iterator helpers,
templates, reflection iterators, initialized new, self-referential
constraints, and generic-method limitations.
Newer generic forms
Methods on non-parameterized receiver types may declare type parameters, but a
parameterized receiver cannot add them and generic methods cannot implement
interface methods. Generic function values also participate in type inference
when assigned or converted to a matching function type.
Use errors.AsType[E] for type-safe extraction from a wrapped error chain.
Testing and deterministic concurrency
Use stable synctest.Test and synctest.Wait from testing/synctest for
fake-time concurrency tests. Inside a synctest bubble, time advances only when
every goroutine is durably blocked. Channel operations, timers,
sync.Cond.Wait, and sync.WaitGroup.Wait can be durable; mutex contention
and external I/O are not.
Use in-memory I/O such as net.Pipe, ensure every background goroutine exits,
and do not use a channel created inside a bubble outside it.
Use these test facilities where appropriate:
T.Context and B.Context for cancellation before cleanup runs.
T.Attr, B.Attr, and F.Attr for structured attributes.
Output for an indented log writer without source prefixes.
ArtifactDir with go test -artifacts for persistent diagnostic output.
Filesystem confinement
Use os.OpenRoot when resolving untrusted relative paths beneath a trusted
directory:
root, err := os.OpenRoot(base)
if err != nil {
return err
}
defer root.Close()
file, err := root.Open(untrustedName)
Use os.OpenInRoot for a one-shot open. Do not replace it with
filepath.Join plus a pre-check: lexical checks do not prevent symlink
check/use races. Read
filesystem-data-and-encoding.md
for available methods and platform limitations, especially mount traversal
and GOOS=js behavior.
Modules, commands, and build output
- Use the
tool meta-pattern to upgrade or install every executable dependency
declared with a tool directive.
- Use
go get -tool package@version to add both the tool directive and module
dependency.
- Use a
go.mod ignore directive to exclude directories from package-pattern
matching; it does not remove files from module zips.
- Use the
work pattern for all packages in the work module or workspace.
- Consume
go build -json, go install -json, and go test -json as
extensible structured records.
- Expect
go fix to apply analysis-based modernizers, including migrations
driven by //go:fix inline.
- For modules declaring language version 1.27 or later, expect
go mod tidy to
canonicalize duplicate require blocks.
Runtime and diagnostics
- Call
runtime.SetDefaultGOMAXPROCS to return to the runtime-selected value
after an explicit override.
- Use
runtime/trace.FlightRecorder to retain a recent in-memory trace window
and write it after a significant event.
- Use the stable
goroutineleak profile while understanding that reachable
synchronization primitives can hide leaks.
- Read
/sched/goroutines, /sched/threads:threads, and
/sched/goroutines-created:goroutines for scheduler population and lifetime
creation counts.
- Treat assumptions about predictable 64-bit heap addresses as invalid.
- Treat goroutine labels in tracebacks as potentially sensitive and use
GODEBUG=tracebacklabels=0 when they must be suppressed.
Cryptography, TLS, and HTTP
- Use
crypto.MessageSigner and crypto.SignMessage when a key signs whole
messages.
- Use
crypto.Encapsulator, crypto.Decapsulator, and ecdh.KeyExchanger for
abstract or hardware-backed key exchange.
- Use
crypto/hpke for RFC 9180 HPKE and crypto/mldsa for FIPS 204 ML-DSA.
- Choose the cryptographic module at build time with
GOFIPS140; enable runtime
FIPS mode through GODEBUG=fips140=....
- Configure HTTP/1, HTTP/2, and h2c explicitly with
Server.Protocols or
Transport.Protocols when defaults are insufficient.
- Use
CrossOriginProtection for Fetch Metadata-based rejection of unsafe
cross-origin browser requests.
- Use
ReverseProxy.Rewrite, which exposes both the unmodified inbound request
and the outbound request.
Experimental and platform-sensitive features
Do not present experimental packages as portable or compatibility-guaranteed:
GOEXPERIMENT=simd exposes portable simd and architecture-specific
simd/archsimd APIs whose details remain toolchain-sensitive.
GOEXPERIMENT=runtimesecret exposes runtime/secret; platform support and
inheritance behavior must be checked against the selected toolchain.
Before shipping cross-platform binaries, consult
build-linking-and-platforms.md for
bootstrap requirements, linker layout, WASI requirements, architecture feature
profiles, ABI transitions, removed ports, and WebAssembly instruction floors.
1---2name: go-knowledge-patch3description: Go4license: MIT5---678# Go Knowledge Patch910Use this skill before changing Go source, modules, build pipelines, tests,11cryptographic code, HTTP stacks, runtime integrations, or platform-specific12builds. Read the relevant topic reference before relying on older defaults,13removed commands, compatibility switches, or byte-for-byte encoded output.1415## Reference index1617| Reference | Topics |18| --- | --- |19| [language-and-core.md](references/language-and-core.md) | Language syntax, iterators, templates, errors, reflection, source positions, time, regular expressions, and Unicode |20| [tooling-modules-and-testing.md](references/tooling-modules-and-testing.md) | Modules, workspaces, `go` commands, vet, caches, source modernization, testing, and profiling tools |21| [runtime-and-observability.md](references/runtime-and-observability.md) | Garbage collection, scheduling, traces, crash recovery, cleanup, heap layout, and runtime metrics |22| [filesystem-data-and-encoding.md](references/filesystem-data-and-encoding.md) | Rooted filesystems, links, tar, JSON, compression, JPEG, UUIDs, Windows handles, and `fstest` |23| [networking-and-http.md](references/networking-and-http.md) | DNS, HTTP protocols, redirects, reverse proxies, CSRF, URL parsing, MPTCP, and connection reuse |24| [crypto-tls-and-x509.md](references/crypto-tls-and-x509.md) | FIPS, randomness, signing, KEM and HPKE, RSA, X.509, SHA-3, TLS defaults, and certificate roots |25| [build-linking-and-platforms.md](references/build-linking-and-platforms.md) | Cgo, linker behavior, build IDs, sanitizers, WASI, architecture profiles, ports, SIMD, and bootstrap floors |2627## Breaking changes and deprecations2829### Replace removed and unsafe APIs3031- Replace `go tool doc` and `cmd/doc` with `go doc`. It also accepts32 `package@version`; use `-ex` to list executable examples.33- Replace `httputil.ReverseProxy.Director` with `Rewrite`. A client-selected34 hop-by-hop declaration can remove headers added by `Director`.35- Stop calling undocumented CTR, GCM, or CBC methods on the concrete block36 returned by `aes.NewCipher`; use `crypto/cipher` constructors.37- Replace deprecated OFB and CFB helpers with authenticated `AEAD` modes, or38 `NewCTR` only when unauthenticated streaming is unavoidable.39- Migrate away from PKCS #1 v1.5 encryption and direct use of ECDSA key40 `big.Int` fields.41- Replace deprecated AST package-merging APIs and `parser.ParseDir` in source42 tools.4344### Account for stricter behavior4546- Check a call's error before dereferencing its result. Required nil checks47 happen at the dereference rather than being delayed.48- Expect `url.Parse` to reject malformed hosts with ambiguous colons; bracket49 IPv6 literals.50- Expect `time.Parse` and `time.ParseInLocation` to reject out-of-range zone51 offsets.52- Expect RSA operations to reject keys smaller than 1024 bits and X.50953 verification to reject SHA-1 signatures.54- Do not assume caller-supplied randomness controls DSA, ECDH, RSA, ECDSA,55 `rand.Prime`, or every Ed25519 key-generation path. Use56 `testing/cryptotest.SetGlobalRandom` for deterministic tests.57- Update golden files and cache keys that require byte-identical JPEG or58 DEFLATE-family output.59- Treat `runtime.AddCleanup` callbacks as concurrent and potentially parallel.60- Expect `testing.AllocsPerRun` to panic while parallel tests are active.61- Treat unknown fields such as `OutputType` in `go test -json` records as62 forward-compatible structured data.6364### Audit changed defaults6566- Green Tea is the default garbage collector. Use67 `GOEXPERIMENT=nogreenteagc` only as a temporary diagnostic escape hatch68 where the selected toolchain still supports it.69- Linux `GOMAXPROCS` observes cgroup CPU bandwidth, and the runtime periodically70 refreshes its default on every OS.71- `net.ListenConfig` enables Multipath TCP by default where supported.72- Post-quantum hybrid TLS exchanges are enabled by default unless73 `CurvePreferences` or the applicable `GODEBUG` switch disables them.74- `ServeMux` trailing-slash redirects use status 307.75- `ServeContent`, `ServeFile`, and `ServeFileFS` strip caching and encoding76 headers from error responses.77- Closing an HTTP/1 response body may drain unread data to preserve connection78 reuse; disable keep-alives when reuse is intentionally unwanted.79- `go mod init` deliberately selects an older language version than the stable80 toolchain executing it.81- `go build -asan` performs leak detection at process exit by default.82- DWARF 5 and native ELF or Mach-O build identifiers are emitted by default.83- The JSON v2 implementation backs `encoding/json`; it rejects invalid UTF-884 and duplicate object names through the v2 APIs.8586## Language quick reference8788### Range over iterator functions8990Use one of these push-iterator shapes:9192```go93func(func() bool)94func(func(V) bool)95func(func(K, V) bool)96```9798Stop producing values when `yield` returns false. Prefer the named99`iter.Seq[V]` and `iter.Seq2[K, V]` forms; there is no `Seq0`.100101```go102func (s *Set[E]) All() iter.Seq[E] {103 return func(yield func(E) bool) {104 for value := range s.m {105 if !yield(value) {106 return107 }108 }109 }110}111```112113For pull-style consumption, call `iter.Pull` and always arrange for `stop`114when iteration can end early:115116```go117next, stop := iter.Pull(seq)118defer stop()119for value, ok := next(); ok; value, ok = next() {120 use(value)121}122```123124Select language version 1.23 or newer before using range-over-function syntax.125See [language-and-core.md](references/language-and-core.md) for iterator helpers,126templates, reflection iterators, initialized `new`, self-referential127constraints, and generic-method limitations.128129### Newer generic forms130131Methods on non-parameterized receiver types may declare type parameters, but a132parameterized receiver cannot add them and generic methods cannot implement133interface methods. Generic function values also participate in type inference134when assigned or converted to a matching function type.135136Use `errors.AsType[E]` for type-safe extraction from a wrapped error chain.137138## Testing and deterministic concurrency139140Use stable `synctest.Test` and `synctest.Wait` from `testing/synctest` for141fake-time concurrency tests. Inside a synctest bubble, time advances only when142every goroutine is durably blocked. Channel operations, timers,143`sync.Cond.Wait`, and `sync.WaitGroup.Wait` can be durable; mutex contention144and external I/O are not.145146Use in-memory I/O such as `net.Pipe`, ensure every background goroutine exits,147and do not use a channel created inside a bubble outside it.148149Use these test facilities where appropriate:150151- `T.Context` and `B.Context` for cancellation before cleanup runs.152- `T.Attr`, `B.Attr`, and `F.Attr` for structured attributes.153- `Output` for an indented log writer without source prefixes.154- `ArtifactDir` with `go test -artifacts` for persistent diagnostic output.155156## Filesystem confinement157158Use `os.OpenRoot` when resolving untrusted relative paths beneath a trusted159directory:160161```go162root, err := os.OpenRoot(base)163if err != nil {164 return err165}166defer root.Close()167168file, err := root.Open(untrustedName)169```170171Use `os.OpenInRoot` for a one-shot open. Do not replace it with172`filepath.Join` plus a pre-check: lexical checks do not prevent symlink173check/use races. Read174[filesystem-data-and-encoding.md](references/filesystem-data-and-encoding.md)175for available methods and platform limitations, especially mount traversal176and `GOOS=js` behavior.177178## Modules, commands, and build output179180- Use the `tool` meta-pattern to upgrade or install every executable dependency181 declared with a `tool` directive.182- Use `go get -tool package@version` to add both the tool directive and module183 dependency.184- Use a `go.mod` `ignore` directive to exclude directories from package-pattern185 matching; it does not remove files from module zips.186- Use the `work` pattern for all packages in the work module or workspace.187- Consume `go build -json`, `go install -json`, and `go test -json` as188 extensible structured records.189- Expect `go fix` to apply analysis-based modernizers, including migrations190 driven by `//go:fix inline`.191- For modules declaring language version 1.27 or later, expect `go mod tidy` to192 canonicalize duplicate `require` blocks.193194## Runtime and diagnostics195196- Call `runtime.SetDefaultGOMAXPROCS` to return to the runtime-selected value197 after an explicit override.198- Use `runtime/trace.FlightRecorder` to retain a recent in-memory trace window199 and write it after a significant event.200- Use the stable `goroutineleak` profile while understanding that reachable201 synchronization primitives can hide leaks.202- Read `/sched/goroutines`, `/sched/threads:threads`, and203 `/sched/goroutines-created:goroutines` for scheduler population and lifetime204 creation counts.205- Treat assumptions about predictable 64-bit heap addresses as invalid.206- Treat goroutine labels in tracebacks as potentially sensitive and use207 `GODEBUG=tracebacklabels=0` when they must be suppressed.208209## Cryptography, TLS, and HTTP210211- Use `crypto.MessageSigner` and `crypto.SignMessage` when a key signs whole212 messages.213- Use `crypto.Encapsulator`, `crypto.Decapsulator`, and `ecdh.KeyExchanger` for214 abstract or hardware-backed key exchange.215- Use `crypto/hpke` for RFC 9180 HPKE and `crypto/mldsa` for FIPS 204 ML-DSA.216- Choose the cryptographic module at build time with `GOFIPS140`; enable runtime217 FIPS mode through `GODEBUG=fips140=...`.218- Configure HTTP/1, HTTP/2, and h2c explicitly with `Server.Protocols` or219 `Transport.Protocols` when defaults are insufficient.220- Use `CrossOriginProtection` for Fetch Metadata-based rejection of unsafe221 cross-origin browser requests.222- Use `ReverseProxy.Rewrite`, which exposes both the unmodified inbound request223 and the outbound request.224225## Experimental and platform-sensitive features226227Do not present experimental packages as portable or compatibility-guaranteed:228229- `GOEXPERIMENT=simd` exposes portable `simd` and architecture-specific230 `simd/archsimd` APIs whose details remain toolchain-sensitive.231- `GOEXPERIMENT=runtimesecret` exposes `runtime/secret`; platform support and232 inheritance behavior must be checked against the selected toolchain.233234Before shipping cross-platform binaries, consult235[build-linking-and-platforms.md](references/build-linking-and-platforms.md) for236bootstrap requirements, linker layout, WASI requirements, architecture feature237profiles, ABI transitions, removed ports, and WebAssembly instruction floors.