Go Knowledge Patch
Use this skill before changing Go language code, modules, build pipelines, tests,
runtime diagnostics, cryptographic code, HTTP stacks, data formats, or platform
integrations. Check the project go directive and relevant topic reference before
depending on defaults, experiments, or compatibility switches.
Reference index
| Reference |
Topics |
| language-and-core.md |
Iterators, generics, templates, errors, reflection, time, Unicode, and core APIs |
| tooling-modules-and-testing.md |
Modules, commands, vet, caches, source tools, synctest, artifacts, and support policy |
| runtime-and-observability.md |
Garbage collection, scheduling, traces, crash recovery, cleanup, heap layout, and profiles |
| filesystem-data-and-encoding.md |
Rooted filesystems, links, tar, JSON, JPEG, compression, Windows handles, and fstest |
| networking-and-http.md |
DNS, HTTP protocols, redirects, reverse proxies, CSRF, URL parsing, and MPTCP |
| crypto-tls-and-x509.md |
FIPS, randomness, signatures, KEM and HPKE, RSA, X.509, SHA-3, and TLS defaults |
| build-linking-and-platforms.md |
Cgo, linking, build IDs, WASI, architecture profiles, SIMD, ports, and bootstrap floors |
Breaking changes and migrations
Remove obsolete API dependencies
- Replace
cmd/doc and go tool doc with the flag-compatible go doc.
- Replace
httputil.ReverseProxy.Director with Rewrite; Director can add a
header that a client-selected hop-by-hop declaration later removes.
- Pass the block returned by
aes.NewCipher to crypto/cipher constructors;
its undocumented CTR, GCM, and CBC methods are no longer exposed.
- Replace deprecated OFB and CFB helpers with authenticated
AEAD modes, or
NewCTR only when an unauthenticated stream is unavoidable.
- Migrate 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
tooling.
Account for stricter behavior
- Check an error before dereferencing its possibly nil result; required nil
checks are no longer delayed.
- Bracket IPv6 literals and expect
url.Parse to reject malformed host colons.
- Expect time parsing to reject out-of-range zone offsets.
- Reject RSA keys smaller than 1024 bits and certificates signed with SHA-1.
- Do not inject cryptographic randomness through operation arguments. Use
testing/cryptotest.SetGlobalRandom when tests need deterministic randomness.
- Update golden files or cache keys that assume byte-identical JPEG or
DEFLATE-family output.
- Make
runtime.AddCleanup callbacks concurrency-safe.
- Never call
testing.AllocsPerRun while parallel tests are active.
- Treat invalid UTF-8 and duplicate JSON object names as errors when using the
v2 JSON API.
Audit changed defaults
- Green Tea is the garbage collector; remove obsolete experiment assumptions.
- Linux
GOMAXPROCS observes cgroup CPU bandwidth, and the runtime periodically
refreshes its selected default on every OS.
net.ListenConfig enables Multipath TCP by default where supported.
- Several post-quantum hybrid TLS exchanges are enabled by default.
ServeMux trailing-slash redirects use 307, not 301.
- File-serving helpers remove caching and encoding headers from error responses.
- Closing an HTTP/1 response body may drain unread data to permit reuse.
- HTTP/2 servers honor extensible priority signals by default.
go mod init deliberately chooses an older language version than a stable
toolchain.
- AddressSanitizer performs leak detection at exit by default.
- DWARF 5 and native ELF or Mach-O build identifiers are emitted by default.
- The standard
encoding/json API uses the v2 backend while retaining its API
behavior apart from possible error-text changes.
Language quick reference
Range over iterator functions
Iterator functions use one of these push shapes:
func(func() bool)
func(func(V) bool)
func(func(K, V) bool)
Stop producing values as soon as 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, arrange for stop even when iteration exits 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,
generic methods, initialized new, templates, reflection, and errors.
Testing and deterministic concurrency
Use stable synctest.Test and synctest.Wait from testing/synctest. Inside a
bubble, time advances only when every goroutine is durably blocked. Same-bubble
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, make every background goroutine exit, and
do not use a channel created inside a bubble from outside it.
Prefer newer test lifecycle and diagnostic facilities where suitable:
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.
Read tooling-modules-and-testing.md
before updating JSON event consumers, vet policy, cache integration, or source
analysis.
Filesystem confinement
Use os.OpenRoot to resolve 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 substitute filepath.Join plus
a pre-check; lexical checks do not prevent symlink check/use races. Consult
filesystem-data-and-encoding.md for
available operations and platform limitations, including mount traversal and
GOOS=js behavior.
Modules, commands, and builds
- Use the
tool pattern to upgrade or install executable dependencies declared
by tool directives; add one with go get -tool package@version.
- 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 packages in the current work module or workspace.
- Consume
go build -json, go install -json, and go test -json as evolving
structured records, tolerating new actions and fields.
- Expect
go fix to use analysis-based modernizers, including migrations
driven by //go:fix inline.
- For modules selecting Go 1.27 or later, expect
go mod tidy to canonicalize
direct and indirect require blocks.
Read tooling-modules-and-testing.md
and build-linking-and-platforms.md
before changing CI parsers, cgo contracts, link flags, or cross-platform builds.
Runtime and diagnostics
- Call
runtime.SetDefaultGOMAXPROCS to restore runtime selection after an
explicit override.
- Use
runtime/trace.FlightRecorder to retain a recent trace window and write
it after a significant event.
- Use the stable
goroutineleak profile, while remembering that reachable
synchronization primitives can hide leaks.
- Treat goroutine labels in tracebacks as potentially sensitive.
- Read scheduler population and lifetime totals from the new
/sched metrics.
- Do not assume predictable 64-bit heap addresses.
See runtime-and-observability.md for
GC selection, crash-trace recovery, cleanup diagnostics, mapping labels, and
trace listener exposure.
Cryptography and TLS
- Use
crypto.MessageSigner and crypto.SignMessage for whole-message signing.
- 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.
- Select the cryptographic module at build time with
GOFIPS140; select runtime
enforcement with GODEBUG=fips140=....
- Set TLS
CurvePreferences when interoperability requires excluding default
hybrid exchanges.
- Use
Certificate.Policies for certificate creation and
VerifyOptions.CertificatePolicies for policy-graph validation.
- Audit removed TLS, X.509, timer-channel, alias, and other
GODEBUG escape
hatches instead of depending on them.
Read crypto-tls-and-x509.md before changing
randomness, signing, RSA validation, FIPS enforcement, ECH, certificate roots,
TLS curves, or SHA-3 state handling.
HTTP and networking
- Select HTTP/1, HTTP/2, and unencrypted HTTP/2 explicitly through
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.
- Expect cookies to scope to
Request.Host when it is explicitly set.
- Inspect wrapped DNS cancellation and timeout causes with
errors.Is.
- Disable keep-alives when a client deliberately must not reuse HTTP/1
connections.
Read networking-and-http.md for h2c limits,
informational responses, redirects, priority scheduling, and compatibility flags.
Experimental and platform-sensitive features
Do not present experiments as portable or compatibility-guaranteed:
GOEXPERIMENT=simd exposes portable simd and architecture-specific
simd/archsimd, whose APIs and availability differ.
GOEXPERIMENT=runtimesecret provides secret-mode execution and inheritance
only on supported systems.
Before shipping cross-platform binaries, consult
build-linking-and-platforms.md for
bootstrap requirements, linker layout, WASI instructions, architecture profiles,
removed or broken ports, and the PowerPC64 ELFv2 transition.
1---2name: go-knowledge-patch-23description: Go4license: MIT5---678# Go Knowledge Patch910Use this skill before changing Go language code, modules, build pipelines, tests,11runtime diagnostics, cryptographic code, HTTP stacks, data formats, or platform12integrations. Check the project `go` directive and relevant topic reference before13depending on defaults, experiments, or compatibility switches.1415## Reference index1617| Reference | Topics |18| --- | --- |19| [language-and-core.md](references/language-and-core.md) | Iterators, generics, templates, errors, reflection, time, Unicode, and core APIs |20| [tooling-modules-and-testing.md](references/tooling-modules-and-testing.md) | Modules, commands, vet, caches, source tools, synctest, artifacts, and support policy |21| [runtime-and-observability.md](references/runtime-and-observability.md) | Garbage collection, scheduling, traces, crash recovery, cleanup, heap layout, and profiles |22| [filesystem-data-and-encoding.md](references/filesystem-data-and-encoding.md) | Rooted filesystems, links, tar, JSON, JPEG, compression, Windows handles, and `fstest` |23| [networking-and-http.md](references/networking-and-http.md) | DNS, HTTP protocols, redirects, reverse proxies, CSRF, URL parsing, and MPTCP |24| [crypto-tls-and-x509.md](references/crypto-tls-and-x509.md) | FIPS, randomness, signatures, KEM and HPKE, RSA, X.509, SHA-3, and TLS defaults |25| [build-linking-and-platforms.md](references/build-linking-and-platforms.md) | Cgo, linking, build IDs, WASI, architecture profiles, SIMD, ports, and bootstrap floors |2627## Breaking changes and migrations2829### Remove obsolete API dependencies3031- Replace `cmd/doc` and `go tool doc` with the flag-compatible `go doc`.32- Replace `httputil.ReverseProxy.Director` with `Rewrite`; `Director` can add a33 header that a client-selected hop-by-hop declaration later removes.34- Pass the block returned by `aes.NewCipher` to `crypto/cipher` constructors;35 its undocumented CTR, GCM, and CBC methods are no longer exposed.36- Replace deprecated OFB and CFB helpers with authenticated `AEAD` modes, or37 `NewCTR` only when an unauthenticated stream is unavoidable.38- Migrate from PKCS #1 v1.5 encryption and direct use of ECDSA key `big.Int`39 fields.40- Replace deprecated AST package-merging APIs and `parser.ParseDir` in source41 tooling.4243### Account for stricter behavior4445- Check an error before dereferencing its possibly nil result; required nil46 checks are no longer delayed.47- Bracket IPv6 literals and expect `url.Parse` to reject malformed host colons.48- Expect time parsing to reject out-of-range zone offsets.49- Reject RSA keys smaller than 1024 bits and certificates signed with SHA-1.50- Do not inject cryptographic randomness through operation arguments. Use51 `testing/cryptotest.SetGlobalRandom` when tests need deterministic randomness.52- Update golden files or cache keys that assume byte-identical JPEG or53 DEFLATE-family output.54- Make `runtime.AddCleanup` callbacks concurrency-safe.55- Never call `testing.AllocsPerRun` while parallel tests are active.56- Treat invalid UTF-8 and duplicate JSON object names as errors when using the57 v2 JSON API.5859### Audit changed defaults6061- Green Tea is the garbage collector; remove obsolete experiment assumptions.62- Linux `GOMAXPROCS` observes cgroup CPU bandwidth, and the runtime periodically63 refreshes its selected default on every OS.64- `net.ListenConfig` enables Multipath TCP by default where supported.65- Several post-quantum hybrid TLS exchanges are enabled by default.66- `ServeMux` trailing-slash redirects use 307, not 301.67- File-serving helpers remove caching and encoding headers from error responses.68- Closing an HTTP/1 response body may drain unread data to permit reuse.69- HTTP/2 servers honor extensible priority signals by default.70- `go mod init` deliberately chooses an older language version than a stable71 toolchain.72- AddressSanitizer performs leak detection at exit by default.73- DWARF 5 and native ELF or Mach-O build identifiers are emitted by default.74- The standard `encoding/json` API uses the v2 backend while retaining its API75 behavior apart from possible error-text changes.7677## Language quick reference7879### Range over iterator functions8081Iterator functions use one of these push shapes:8283```go84func(func() bool)85func(func(V) bool)86func(func(K, V) bool)87```8889Stop producing values as soon as `yield` returns false. Prefer the named90`iter.Seq[V]` and `iter.Seq2[K, V]` forms; there is no `Seq0`.9192```go93func (s *Set[E]) All() iter.Seq[E] {94 return func(yield func(E) bool) {95 for value := range s.m {96 if !yield(value) {97 return98 }99 }100 }101}102```103104For pull-style consumption, arrange for `stop` even when iteration exits early:105106```go107next, stop := iter.Pull(seq)108defer stop()109for value, ok := next(); ok; value, ok = next() {110 use(value)111}112```113114Select language version 1.23 or newer before using range-over-function syntax.115See [language-and-core.md](references/language-and-core.md) for iterator helpers,116generic methods, initialized `new`, templates, reflection, and errors.117118## Testing and deterministic concurrency119120Use stable `synctest.Test` and `synctest.Wait` from `testing/synctest`. Inside a121bubble, time advances only when every goroutine is durably blocked. Same-bubble122channel operations, timers, `sync.Cond.Wait`, and `sync.WaitGroup.Wait` can be123durable; mutex contention and external I/O are not.124125Use in-memory I/O such as `net.Pipe`, make every background goroutine exit, and126do not use a channel created inside a bubble from outside it.127128Prefer newer test lifecycle and diagnostic facilities where suitable:129130- `T.Context` and `B.Context` for cancellation before cleanup runs.131- `T.Attr`, `B.Attr`, and `F.Attr` for structured attributes.132- `Output` for an indented log writer without source prefixes.133- `ArtifactDir` with `go test -artifacts` for persistent diagnostic output.134135Read [tooling-modules-and-testing.md](references/tooling-modules-and-testing.md)136before updating JSON event consumers, vet policy, cache integration, or source137analysis.138139## Filesystem confinement140141Use `os.OpenRoot` to resolve untrusted relative paths beneath a trusted directory:142143```go144root, err := os.OpenRoot(base)145if err != nil {146 return err147}148defer root.Close()149150file, err := root.Open(untrustedName)151```152153Use `os.OpenInRoot` for a one-shot open. Do not substitute `filepath.Join` plus154a pre-check; lexical checks do not prevent symlink check/use races. Consult155[filesystem-data-and-encoding.md](references/filesystem-data-and-encoding.md) for156available operations and platform limitations, including mount traversal and157`GOOS=js` behavior.158159## Modules, commands, and builds160161- Use the `tool` pattern to upgrade or install executable dependencies declared162 by `tool` directives; add one with `go get -tool package@version`.163- Use a `go.mod` `ignore` directive to exclude directories from package-pattern164 matching; it does not remove files from module zips.165- Use the `work` pattern for packages in the current work module or workspace.166- Consume `go build -json`, `go install -json`, and `go test -json` as evolving167 structured records, tolerating new actions and fields.168- Expect `go fix` to use analysis-based modernizers, including migrations169 driven by `//go:fix inline`.170- For modules selecting Go 1.27 or later, expect `go mod tidy` to canonicalize171 direct and indirect `require` blocks.172173Read [tooling-modules-and-testing.md](references/tooling-modules-and-testing.md)174and [build-linking-and-platforms.md](references/build-linking-and-platforms.md)175before changing CI parsers, cgo contracts, link flags, or cross-platform builds.176177## Runtime and diagnostics178179- Call `runtime.SetDefaultGOMAXPROCS` to restore runtime selection after an180 explicit override.181- Use `runtime/trace.FlightRecorder` to retain a recent trace window and write182 it after a significant event.183- Use the stable `goroutineleak` profile, while remembering that reachable184 synchronization primitives can hide leaks.185- Treat goroutine labels in tracebacks as potentially sensitive.186- Read scheduler population and lifetime totals from the new `/sched` metrics.187- Do not assume predictable 64-bit heap addresses.188189See [runtime-and-observability.md](references/runtime-and-observability.md) for190GC selection, crash-trace recovery, cleanup diagnostics, mapping labels, and191trace listener exposure.192193## Cryptography and TLS194195- Use `crypto.MessageSigner` and `crypto.SignMessage` for whole-message signing.196- Use `crypto.Encapsulator`, `crypto.Decapsulator`, and `ecdh.KeyExchanger` for197 abstract or hardware-backed key exchange.198- Use `crypto/hpke` for RFC 9180 HPKE and `crypto/mldsa` for FIPS 204 ML-DSA.199- Select the cryptographic module at build time with `GOFIPS140`; select runtime200 enforcement with `GODEBUG=fips140=...`.201- Set TLS `CurvePreferences` when interoperability requires excluding default202 hybrid exchanges.203- Use `Certificate.Policies` for certificate creation and204 `VerifyOptions.CertificatePolicies` for policy-graph validation.205- Audit removed TLS, X.509, timer-channel, alias, and other `GODEBUG` escape206 hatches instead of depending on them.207208Read [crypto-tls-and-x509.md](references/crypto-tls-and-x509.md) before changing209randomness, signing, RSA validation, FIPS enforcement, ECH, certificate roots,210TLS curves, or SHA-3 state handling.211212## HTTP and networking213214- Select HTTP/1, HTTP/2, and unencrypted HTTP/2 explicitly through215 `Server.Protocols` or `Transport.Protocols` when defaults are insufficient.216- Use `CrossOriginProtection` for Fetch Metadata-based rejection of unsafe217 cross-origin browser requests.218- Use `ReverseProxy.Rewrite`, which exposes both the unmodified inbound request219 and the outbound request.220- Expect cookies to scope to `Request.Host` when it is explicitly set.221- Inspect wrapped DNS cancellation and timeout causes with `errors.Is`.222- Disable keep-alives when a client deliberately must not reuse HTTP/1223 connections.224225Read [networking-and-http.md](references/networking-and-http.md) for h2c limits,226informational responses, redirects, priority scheduling, and compatibility flags.227228## Experimental and platform-sensitive features229230Do not present experiments as portable or compatibility-guaranteed:231232- `GOEXPERIMENT=simd` exposes portable `simd` and architecture-specific233 `simd/archsimd`, whose APIs and availability differ.234- `GOEXPERIMENT=runtimesecret` provides secret-mode execution and inheritance235 only on supported systems.236237Before shipping cross-platform binaries, consult238[build-linking-and-platforms.md](references/build-linking-and-platforms.md) for239bootstrap requirements, linker layout, WASI instructions, architecture profiles,240removed or broken ports, and the PowerPC64 ELFv2 transition.