[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7BQD2QBPPM42EG3A4C2VSJ5":3,"skill-same:01M7BQD2QBPPM42EG3A4C2VSJ5":59},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":30,"install":31,"resources":44},"01M7BQD2QBPPM42EG3A4C2VSJ5","go-http",null,"Use when writing or reviewing Go HTTP code — handlers, routing with net\u002Fhttp ServeMux, middleware, request decoding and response encoding, server timeouts and graceful shutdown, or HTTP clients. Also use when building a REST or JSON API endpoint or calling an external HTTP service, even if the user names a framework instead of net\u002Fhttp. Does not cover the test server helpers (see go-testing) or request-scoped logging (see go-logging).","h0rn3t\u002Fgolang-skills","h0rn3t","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1213719?v=4","01M7BQBDJ8D4P5W7EQHBD464BX","Eugene Shershen","01M7BQBDJXMTCKNCEDKVEYDRGA",7,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-http\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: go-http\ndescription: Use when writing or reviewing Go HTTP code — handlers, routing with net\u002Fhttp ServeMux, middleware, request decoding and response encoding, server timeouts and graceful shutdown, or HTTP clients. Also use when building a REST or JSON API endpoint or calling an external HTTP service, even if the user names a framework instead of net\u002Fhttp. Does not cover the test server helpers (see go-testing) or request-scoped logging (see go-logging).\n---\n\n# Go HTTP Servers and Clients\n\n> Compatibility: Baseline Go 1.27 (see [COMPATIBILITY.md](..\u002Fgo-style-core\u002Freferences\u002FCOMPATIBILITY.md)). `ServeMux` method and\n> wildcard patterns require Go 1.22+; `http.NewCrossOriginProtection` Go 1.25+;\n> `http.Server.MaxHeaderValueCount` and `encoding\u002Fjson\u002Fv2` Go 1.27+.\n\n## Resource Routing\n\n- `references\u002FWEB-SERVER.md` - Read when assembling a complete server: routing, handler, and graceful shutdown in one `main`.\n- `references\u002FJSON-V2.md` - Read when choosing JSON v2 I\u002FO APIs, decoding a bounded document, migrating wire formats, or testing exact JSON bytes (Go 1.27+).\n- `references\u002FGRPC.md` - Read when writing a gRPC server or client: status codes, generated-server embedding, `grpc.NewClient`, bounded `GracefulStop`, and bufconn tests.\n\n## Routing (Go 1.22+)\n\nA package already on a framework keeps it, and the rules below still apply;\n[go-packages](..\u002Fgo-packages\u002FSKILL.md) owns adding a router module.\n\n```go\nmux := http.NewServeMux()\nmux.HandleFunc(\"GET \u002Fusers\u002F{id}\", s.handleGetUser) \u002F\u002F serves GET and HEAD\nmux.HandleFunc(\"GET \u002Fusers\", s.handleListUsers)\nmux.HandleFunc(\"POST \u002Fusers\", s.handleCreateUser)\nmux.HandleFunc(\"GET \u002F{$}\", s.handleIndex) \u002F\u002F exact \"\u002F\", not a subtree\n\nid := r.PathValue(\"id\")\n```\n\n- **A `GET` pattern also serves `HEAD`.** A method pattern answers every other\n  method on its path with 405 and an `Allow` header that lists `HEAD`; `HEAD`\n  is the one it lets through, with the `GET` handler's status. Under a\n  contract that makes every method but `GET` a 405, every `GET` path gets a\n  `HEAD` pattern and a pattern without a method, both answered with the\n  methods that path serves — the health check and the index as much as the\n  resource routes, so the file registers as many `HEAD` patterns as `GET`\n  patterns — or a `GET`-only path registers its handler without a method and\n  opens it with an `r.Method != http.MethodGet` check that answers 405 with\n  `Allow: GET`; the test file sends\n  `HEAD` and `POST` to each `GET` path and reads `Allow`. A pattern without a\n  method matches every method.\n- Conflicting patterns panic at registration; overlapping patterns are valid\n  when one is more specific, which is why `HEAD \u002Fusers\u002F{id}` registers beside\n  `GET \u002Fusers\u002F{id}`.\n- Trailing `\u002F` is a subtree; `{$}` pins the exact path.\n\nOnly when the contract makes `HEAD` a 405, one package function builds the\nanswer, registered twice per `GET` path — as `HEAD` and without a method, so\n`POST` and `DELETE` get the same `Allow` — the index included:\n\n```go\n\u002F\u002F methodNotAllowed answers every method its path does not serve, HEAD among\n\u002F\u002F them; allow lists the methods the path does serve.\nfunc methodNotAllowed(allow string) http.HandlerFunc {\n    return func(w http.ResponseWriter, _ *http.Request) {\n        w.Header().Set(\"Allow\", allow)\n        http.Error(w, \"method not allowed\", http.StatusMethodNotAllowed)\n    }\n}\n\nmux.HandleFunc(\"HEAD \u002Fusers\u002F{id}\", methodNotAllowed(\"GET\"))\nmux.HandleFunc(\"\u002Fusers\u002F{id}\", methodNotAllowed(\"GET\"))\nmux.HandleFunc(\"HEAD \u002Fusers\", methodNotAllowed(\"GET, POST\"))\nmux.HandleFunc(\"\u002Fusers\", methodNotAllowed(\"GET, POST\"))\nmux.HandleFunc(\"HEAD \u002F{$}\", methodNotAllowed(\"GET\"))\nmux.HandleFunc(\"\u002F{$}\", methodNotAllowed(\"GET\"))\n```\n\n## Handler Shape\n\nPreserve the existing handler structure. No package-level state.\n\nBound and decode → validate → call the domain with `r.Context()` → map the\nerror → write once. `Server` below stands for the type the repository already\nhas; in new code without one, the handler is a function literal in the\nconstructor that builds the mux, capturing the store\n([go-code](..\u002Fgo-code\u002FSKILL.md#declaration-budget)). With\n`import json \"encoding\u002Fjson\u002Fv2\"` (Go 1.27):\n\n```go\nfunc (s *Server) handleCreateUser(w http.ResponseWriter, r *http.Request) {\n    r.Body = http.MaxBytesReader(w, r.Body, 1\u003C\u003C20)\n    var req struct {\n        Name string `json:\"name\"`\n    }\n    \u002F\u002F One decode: an unknown member, a second value, junk, or an oversized body fails.\n    if err := json.UnmarshalRead(r.Body, &req, json.RejectUnknownMembers(true)); err != nil {\n        http.Error(w, \"invalid JSON body\", http.StatusBadRequest)\n        return\n    }\n    if req.Name == \"\" {\n        http.Error(w, \"name is required\", http.StatusBadRequest)\n        return\n    }\n    user, err := s.store.Create(r.Context(), req.Name)\n    switch {\n    case errors.Is(err, ErrConflict):\n        http.Error(w, \"name already taken\", http.StatusConflict)\n        return\n    case err != nil && errors.Is(r.Context().Err(), context.Canceled):\n        slog.DebugContext(r.Context(), \"create user: client gone\", \"err\", err)\n        return \u002F\u002F nobody is left to read a status\n    case err != nil:\n        slog.ErrorContext(r.Context(), \"create user\", \"err\", err)\n        http.Error(w, \"internal error\", http.StatusInternalServerError)\n        return\n    }\n    body, err := json.Marshal(struct { \u002F\u002F the response names its fields; a stored one added later stays out\n        ID   string `json:\"id\"`\n        Name string `json:\"name\"`\n    }{user.ID, user.Name})\n    if err != nil { \u002F\u002F before any header, so an encode error is still a 500\n        slog.ErrorContext(r.Context(), \"encode user\", \"err\", err)\n        http.Error(w, \"internal error\", http.StatusInternalServerError)\n        return\n    }\n    w.Header().Set(\"Content-Type\", \"application\u002Fjson\")\n    w.WriteHeader(http.StatusCreated)\n    _, _ = w.Write(body) \u002F\u002F headers are sent; a failed write is the client's disconnect\n}\n```\n\n- Bound every decoded body with `http.MaxBytesReader`. `{}` and `null` still\n  decode, leaving `req` zero, so required fields are validated before the\n  store call. The request type is declared in the handler that reads it; a second\n  handler decoding the same document is what moves it to package level\n  ([go-code](..\u002Fgo-code\u002FSKILL.md#declaration-budget)).\n- A package already decoding with `encoding\u002Fjson` v1 keeps v1 and its two\n  decodes: `dec.DisallowUnknownFields()`, `dec.Decode(&req)`, then\n  `dec.Decode(new(any))` must return `io.EOF` — `DisallowUnknownFields`\n  alone accepts trailing data, and the second decode allows trailing\n  whitespace while the cap still holds.\n- v2 encodes a nil slice as `[]` and a nil map as `{}`, so a filtered list\n  with no matches is written as it is, with no `make([]T, 0, n)`; that line\n  belongs to a package on v1, or under `FormatNilSliceAsNull(true)`\n  ([JSON-V2.md](references\u002FJSON-V2.md#defaults-that-can-change-the-contract)).\n- A response body is marshalled with `json.Marshal` before the first header,\n  as above. v2 fails at encode time on a `time.Duration` field (no default\n  representation), invalid UTF-8 in stored text, or a `MarshalJSON` error;\n  `json.MarshalWrite(w, v)` after `WriteHeader` sends the status with a\n  truncated body and nowhere to report the error.\n- A write whose error has nowhere to go is discarded in the open with its\n  reason on the line, as the example's last line is, never bare. `errcheck`\n  reads a bare `w.Write`, `io.WriteString(w, …)`, `json.MarshalWrite(w, v)`,\n  or `json.NewEncoder(w).Encode(v)` as a finding, and `\u002F\u002Fnolint:errcheck` is\n  not a way out: `gosec` G104 reports the same line.\n\n### Mapping errors to status codes\n\nCentralize shared error-to-status rules in `writeError`, using\n`errors.Is`\u002F`errors.AsType`; keep a single-handler mapping local. Apply each\nrow where that failure can occur:\n\n| Error | Status | Body |\n|---|---|---|\n| Validation, malformed input | 400 | The validation message |\n| `ErrNotFound` sentinel | 404 | Generic |\n| `ErrConflict`, version mismatch | 409 | Generic |\n| Incoming `r.Context().Err()` is `context.Canceled` | 499-style: log at Debug, write nothing | — |\n| Downstream `context.Canceled` while the incoming request is alive | 500 unless the endpoint specifies otherwise | Generic |\n| `context.DeadlineExceeded` from downstream | 504 | Generic |\n| Anything else | 500 | Generic — **never** `err.Error()` |\n\nThe request ID reaches the 500 record only through the request-scoped\nlogger [go-logging](..\u002Fgo-logging\u002FSKILL.md#request-scoped-logging) sets up;\nwhere the repository has one, the example's `slog` calls go through it. This is\nthe handle-once exception owned by\n[go-error-handling](..\u002Fgo-error-handling\u002FSKILL.md).\n\n## Middleware\n\n`func(next http.Handler) http.Handler`. Outside in: recover → request ID +\nlogging → auth → mux. Wrap `http.ResponseWriter` only to capture status and\nkeep it transparent; use `http.NewResponseController(w)` for deadlines and\nflushing instead of asserting optional interfaces.\n\n## Server Construction\n\nConstruct an `http.Server`; bare `http.ListenAndServe` sets no timeouts.\n\n| Field | Why |\n|---|---|\n| `ReadHeaderTimeout` | Slowloris defense; must never be zero |\n| `ReadTimeout`, `WriteTimeout` | Bound slow clients; `WriteTimeout` exceeds the slowest handler |\n| `IdleTimeout` | Reclaim keep-alive connections |\n| `MaxHeaderBytes`, `MaxHeaderValueCount` (Go 1.27+) | Only to change the defaults, 1 MiB and 500 values: `MaxHeaderBytes: 1 \u003C\u003C 20` restates zero |\n| `Handler: http.NewCrossOriginProtection().Handler(mux)` | CSRF for state-changing requests (Go 1.25+). One per server: with CORS it is the instance go-security's `withCORS` builds with the trusted origins; a second, empty one around it answers every cross-origin POST with 403 |\n| `BaseContext` | Never the `signal.NotifyContext` context when in-flight requests should drain: it cancels every request at the signal, before `Shutdown` waits for them. Handlers that must see shutdown get a separate context, cancelled once `Shutdown`'s timeout expires |\n\nOne slow route does not raise `WriteTimeout` for all: that route extends its\nown deadline with `http.NewResponseController(w).SetWriteDeadline(t)`, as a\nstreaming route does. `http.TimeoutHandler(h, d, msg)` only shortens: it\ncancels `r.Context()` at `d` and answers 503, and with `d` above\n`WriteTimeout` the connection is cut first, with no response at all. It\nbuffers the response and has no `Flusher`.\n\nFor graceful shutdown, `signal.NotifyContext` owns the lifetime;\n`ListenAndServe` runs in one goroutine feeding a buffered error channel;\n`srv.Shutdown(ctx)` gets its own timeout.\n\n## Clients\n\n- Never `http.Get`, `http.Post`, or `http.DefaultClient` — no timeout. One\n  tuned `*http.Transport` and one `*http.Client{Timeout: d, Transport: t}` per\n  dependency, built once and reused. The Transport owns the connection pool: a\n  `Client` with a nil `Transport` shares `http.DefaultTransport`, which keeps\n  two idle connections per host (`http.DefaultMaxIdleConnsPerHost`). Tune a\n  clone of it; a `&http.Transport{...}` literal drops `ProxyFromEnvironment`\n  and the dial, TLS-handshake, and idle-connection timeouts (the SSRF dialer in\n  [go-security](..\u002Fgo-security\u002FSKILL.md) drops the proxy on purpose), and with\n  `DialContext` or `TLSClientConfig` set it speaks HTTP\u002F1.1 only unless\n  `ForceAttemptHTTP2` is true — an `HTTP2` config on it is ignored. A client\n  that keeps HTTP\u002F2 connections open — watch streams, many multiplexed\n  requests to one host — sets `SendPingTimeout` (Go 1.24+): at zero no health\n  check runs, and every stream on a connection a NAT dropped silently hangs\n  until its own deadline:\n\n  ```go\n  t := http.DefaultTransport.(*http.Transport).Clone()\n  t.MaxIdleConnsPerHost = 32\n  t.HTTP2 = &http.HTTP2Config{SendPingTimeout: 30 * time.Second}\n  client := &http.Client{Timeout: 10 * time.Second, Transport: t}\n  ```\n- `http.NewRequestWithContext(ctx, ...)` — the ctx-less form is unbounded;\n  `noctx` in the lint gate flags it.\n- The Transport reads the request body on its own goroutine, and that read\n  can outlive `Do`: a 4xx\u002F5xx answered from the headers, a timeout, or a\n  cancel returns mid-upload, and on HTTP\u002F2 the Transport's own `Close` of the\n  body can overlap a `Read`. Each request, retry included, gets its own\n  `bytes.NewReader` over bytes nobody writes again — never the previous\n  attempt's reader rewound, never a shared or pooled buffer refilled; `-race`\n  reports that write against the Transport's body writer.\n- `defer resp.Body.Close()` right after the `err != nil` return, on every\n  status (`bodyclose` flags a miss); on error `Do` returns no body to close.\n  Bound untrusted bodies and close them on every path. Go 1.27\n  drains an unread HTTP\u002F1 body on `Close` — up to 256 KiB and 50 ms — to keep\n  the connection reusable, so closing is the whole obligation; a manual read to\n  EOF only buys reuse for responses past those bounds.\n- Check `resp.StatusCode` before decoding; a 5xx body is not your struct.\n- For retry eligibility, `Retry-After`, replay safety, and coordinated budgets,\n  use [go-resilience](..\u002Fgo-resilience\u002FSKILL.md). HTTP status alone does not\n  establish whether repeating an operation is safe.\n\n\n### Bounded Response Bodies\n\nFor a strict response-size limit, read at most the limit plus one byte,\nreject an oversized result, then decode the complete buffer into `dst`.\nA decoder can finish its first object before `io.LimitReader` reaches its\nlimit; that alone does not enforce the size of the whole response.\n\n```go\nconst maxBody = 64 \u003C\u003C 10\nbody, err := io.ReadAll(io.LimitReader(resp.Body, maxBody+1))\nif err != nil {\n    return fmt.Errorf(\"read response: %w\", err)\n}\nif len(body) > maxBody {\n    return fmt.Errorf(\"response exceeds %d bytes\", maxBody)\n}\nreturn json.Unmarshal(body, dst)\n```\n\n## Partial Updates\n\nA PATCH body names only the members it changes, and a Go struct cannot tell a\nmissing member from a zero one: decoding into a fresh struct and saving it\nzeroes every field the client left out. Load the record, copy its\nclient-writable fields into the request value, and unmarshal the body onto\nthat value. v2 leaves an absent member as loaded and sets one sent as `null`\nto its zero value (v1 leaves it unchanged). `RejectUnknownMembers(true)`\nrefuses `password_hash` and any member the request type does not hold, and a\ntop-level `null` leaves the pointer nil. v2 decodes into what the request\nvalue already holds — it writes a non-nil slice's array, merges into a\nnon-nil map, decodes through a non-nil pointer — so a slice, map, or pointer\nfield is copied with `slices.Clone`, `maps.Clone`, or a new value; copied as\nis, the record changes before the body is rejected:\n\n```go\nr.Body = http.MaxBytesReader(w, r.Body, 1\u003C\u003C20)\nreq := &struct {\n    Email string   `json:\"email\"`\n    Phone string   `json:\"phone\"` \u002F\u002F \"phone\": null clears it\n    Tags  []string `json:\"tags\"`\n}{acct.Email, acct.Phone, slices.Clone(acct.Tags)} \u002F\u002F never acct.Tags: v2 writes into its array\nif err := json.UnmarshalRead(r.Body, &req, json.RejectUnknownMembers(true)); err != nil || req == nil {\n    http.Error(w, \"invalid JSON body\", http.StatusBadRequest)\n    return\n}\nif req.Email == \"\" { \u002F\u002F \"email\": null arrives as \"\"\n    http.Error(w, \"email is required\", http.StatusBadRequest)\n    return\n}\nacct.Email, acct.Phone, acct.Tags = req.Email, req.Phone, req.Tags \u002F\u002F a rejected body never touched acct\n```\n\n## Related Skills\n\n- [go-context](..\u002Fgo-context\u002FSKILL.md): derived deadlines and request lifetime.\n- [go-database](..\u002Fgo-database\u002FSKILL.md): handler queries and transactions.\n- [go-testing](..\u002Fgo-testing\u002FSKILL.md): `httptest` and `synctest`.\n- [go-concurrency](..\u002Fgo-concurrency\u002FSKILL.md): server goroutine and shared state.\n- [go-security](..\u002Fgo-security\u002FSKILL.md): input naming files, URLs or commands;\n  cookies, SSRF, and error disclosure.\n- [go-data-structures](..\u002Fgo-data-structures\u002FSKILL.md): nil versus empty slices\n  and maps before they reach the encoder.\n","# Go HTTP Servers and Clients\n\n> Compatibility: Baseline Go 1.27 (see [COMPATIBILITY.md](..\u002Fgo-style-core\u002Freferences\u002FCOMPATIBILITY.md)). `ServeMux` method and\n> wildcard patterns require Go 1.22+; `http.NewCrossOriginProtection` Go 1.25+;\n> `http.Server.MaxHeaderValueCount` and `encoding\u002Fjson\u002Fv2` Go 1.27+.\n\n## Resource Routing\n\n- `references\u002FWEB-SERVER.md` - Read when assembling a complete server: routing, handler, and graceful shutdown in one `main`.\n- `references\u002FJSON-V2.md` - Read when choosing JSON v2 I\u002FO APIs, decoding a bounded document, migrating wire formats, or testing exact JSON bytes (Go 1.27+).\n- `references\u002FGRPC.md` - Read when writing a gRPC server or client: status codes, generated-server embedding, `grpc.NewClient`, bounded `GracefulStop`, and bufconn tests.\n\n## Routing (Go 1.22+)\n\nA package already on a framework keeps it, and the rules below still apply;\n[go-packages](..\u002Fgo-packages\u002FSKILL.md) owns adding a router module.\n\n```go\nmux := http.NewServeMux()\nmux.HandleFunc(\"GET \u002Fusers\u002F{id}\", s.handleGetUser) \u002F\u002F serves GET and HEAD\nmux.HandleFunc(\"GET \u002Fusers\", s.handleListUsers)\nmux.HandleFunc(\"POST \u002Fusers\", s.handleCreateUser)\nmux.HandleFunc(\"GET \u002F{$}\", s.handleIndex) \u002F\u002F exact \"\u002F\", not a subtree\n\nid := r.PathValue(\"id\")\n```\n\n- **A `GET` pattern also serves `HEAD`.** A method pattern answers every other\n  method on its path with 405 and an `Allow` header that lists `HEAD`; `HEAD`\n  is the one it lets through, with the `GET` handler's status. Under a\n  contract that makes every method but `GET` a 405, every `GET` path gets a\n  `HEAD` pattern and a pattern without a method, both answered with the\n  methods that path serves — the health check and the index as much as the\n  resource routes, so the file registers as many `HEAD` patterns as `GET`\n  patterns — or a `GET`-only path registers its handler without a method and\n  opens it with an `r.Method != http.MethodGet` check that answers 405 with\n  `Allow: GET`; the test file sends\n  `HEAD` and `POST` to each `GET` path and reads `Allow`. A pattern without a\n  method matches every method.\n- Conflicting patterns panic at registration; overlapping patterns are valid\n  when one is more specific, which is why `HEAD \u002Fusers\u002F{id}` registers beside\n  `GET \u002Fusers\u002F{id}`.\n- Trailing `\u002F` is a subtree; `{$}` pins the exact path.\n\nOnly when the contract makes `HEAD` a 405, one package function builds the\nanswer, registered twice per `GET` path — as `HEAD` and without a method, so\n`POST` and `DELETE` get the same `Allow` — the index included:\n\n```go\n\u002F\u002F methodNotAllowed answers every method its path does not serve, HEAD among\n\u002F\u002F them; allow lists the methods the path does serve.\nfunc methodNotAllowed(allow string) http.HandlerFunc {\n    return func(w http.ResponseWriter, _ *http.Request) {\n        w.Header().Set(\"Allow\", allow)\n        http.Error(w, \"method not allowed\", http.StatusMethodNotAllowed)\n    }\n}\n\nmux.HandleFunc(\"HEAD \u002Fusers\u002F{id}\", methodNotAllowed(\"GET\"))\nmux.HandleFunc(\"\u002Fusers\u002F{id}\", methodNotAllowed(\"GET\"))\nmux.HandleFunc(\"HEAD \u002Fusers\", methodNotAllowed(\"GET, POST\"))\nmux.HandleFunc(\"\u002Fusers\", methodNotAllowed(\"GET, POST\"))\nmux.HandleFunc(\"HEAD \u002F{$}\", methodNotAllowed(\"GET\"))\nmux.HandleFunc(\"\u002F{$}\", methodNotAllowed(\"GET\"))\n```\n\n## Handler Shape\n\nPreserve the existing handler structure. No package-level state.\n\nBound and decode → validate → call the domain with `r.Context()` → map the\nerror → write once. `Server` below stands for the type the repository already\nhas; in new code without one, the handler is a function literal in the\nconstructor that builds the mux, capturing the store\n([go-code](..\u002Fgo-code\u002FSKILL.md#declaration-budget)). With\n`import json \"encoding\u002Fjson\u002Fv2\"` (Go 1.27):\n\n```go\nfunc (s *Server) handleCreateUser(w http.ResponseWriter, r *http.Request) {\n    r.Body = http.MaxBytesReader(w, r.Body, 1\u003C\u003C20)\n    var req struct {\n        Name string `json:\"name\"`\n    }\n    \u002F\u002F One decode: an unknown member, a second value, junk, or an oversized body fails.\n    if err := json.UnmarshalRead(r.Body, &req, json.RejectUnknownMembers(true)); err != nil {\n        http.Error(w, \"invalid JSON body\", http.StatusBadRequest)\n        return\n    }\n    if req.Name == \"\" {\n        http.Error(w, \"name is required\", http.StatusBadRequest)\n        return\n    }\n    user, err := s.store.Create(r.Context(), req.Name)\n    switch {\n    case errors.Is(err, ErrConflict):\n        http.Error(w, \"name already taken\", http.StatusConflict)\n        return\n    case err != nil && errors.Is(r.Context().Err(), context.Canceled):\n        slog.DebugContext(r.Context(), \"create user: client gone\", \"err\", err)\n        return \u002F\u002F nobody is left to read a status\n    case err != nil:\n        slog.ErrorContext(r.Context(), \"create user\", \"err\", err)\n        http.Error(w, \"internal error\", http.StatusInternalServerError)\n        return\n    }\n    body, err := json.Marshal(struct { \u002F\u002F the response names its fields; a stored one added later stays out\n        ID   string `json:\"id\"`\n        Name string `json:\"name\"`\n    }{user.ID, user.Name})\n    if err != nil { \u002F\u002F before any header, so an encode error is still a 500\n        slog.ErrorContext(r.Context(), \"encode user\", \"err\", err)\n        http.Error(w, \"internal error\", http.StatusInternalServerError)\n        return\n    }\n    w.Header().Set(\"Content-Type\", \"application\u002Fjson\")\n    w.WriteHeader(http.StatusCreated)\n    _, _ = w.Write(body) \u002F\u002F headers are sent; a failed write is the client's disconnect\n}\n```\n\n- Bound every decoded body with `http.MaxBytesReader`. `{}` and `null` still\n  decode, leaving `req` zero, so required fields are validated before the\n  store call. The request type is declared in the handler that reads it; a second\n  handler decoding the same document is what moves it to package level\n  ([go-code](..\u002Fgo-code\u002FSKILL.md#declaration-budget)).\n- A package already decoding with `encoding\u002Fjson` v1 keeps v1 and its two\n  decodes: `dec.DisallowUnknownFields()`, `dec.Decode(&req)`, then\n  `dec.Decode(new(any))` must return `io.EOF` — `DisallowUnknownFields`\n  alone accepts trailing data, and the second decode allows trailing\n  whitespace while the cap still holds.\n- v2 encodes a nil slice as `[]` and a nil map as `{}`, so a filtered list\n  with no matches is written as it is, with no `make([]T, 0, n)`; that line\n  belongs to a package on v1, or under `FormatNilSliceAsNull(true)`\n  ([JSON-V2.md](references\u002FJSON-V2.md#defaults-that-can-change-the-contract)).\n- A response body is marshalled with `json.Marshal` before the first header,\n  as above. v2 fails at encode time on a `time.Duration` field (no default\n  representation), invalid UTF-8 in stored text, or a `MarshalJSON` error;\n  `json.MarshalWrite(w, v)` after `WriteHeader` sends the status with a\n  truncated body and nowhere to report the error.\n- A write whose error has nowhere to go is discarded in the open with its\n  reason on the line, as the example's last line is, never bare. `errcheck`\n  reads a bare `w.Write`, `io.WriteString(w, …)`, `json.MarshalWrite(w, v)`,\n  or `json.NewEncoder(w).Encode(v)` as a finding, and `\u002F\u002Fnolint:errcheck` is\n  not a way out: `gosec` G104 reports the same line.\n\n### Mapping errors to status codes\n\nCentralize shared error-to-status rules in `writeError`, using\n`errors.Is`\u002F`errors.AsType`; keep a single-handler mapping local. Apply each\nrow where that failure can occur:\n\n| Error | Status | Body |\n|---|---|---|\n| Validation, malformed input | 400 | The validation message |\n| `ErrNotFound` sentinel | 404 | Generic |\n| `ErrConflict`, version mismatch | 409 | Generic |\n| Incoming `r.Context().Err()` is `context.Canceled` | 499-style: log at Debug, write nothing | — |\n| Downstream `context.Canceled` while the incoming request is alive | 500 unless the endpoint specifies otherwise | Generic |\n| `context.DeadlineExceeded` from downstream | 504 | Generic |\n| Anything else | 500 | Generic — **never** `err.Error()` |\n\nThe request ID reaches the 500 record only through the request-scoped\nlogger [go-logging](..\u002Fgo-logging\u002FSKILL.md#request-scoped-logging) sets up;\nwhere the repository has one, the example's `slog` calls go through it. This is\nthe handle-once exception owned by\n[go-error-handling](..\u002Fgo-error-handling\u002FSKILL.md).\n\n## Middleware\n\n`func(next http.Handler) http.Handler`. Outside in: recover → request ID +\nlogging → auth → mux. Wrap `http.ResponseWriter` only to capture status and\nkeep it transparent; use `http.NewResponseController(w)` for deadlines and\nflushing instead of asserting optional interfaces.\n\n## Server Construction\n\nConstruct an `http.Server`; bare `http.ListenAndServe` sets no timeouts.\n\n| Field | Why |\n|---|---|\n| `ReadHeaderTimeout` | Slowloris defense; must never be zero |\n| `ReadTimeout`, `WriteTimeout` | Bound slow clients; `WriteTimeout` exceeds the slowest handler |\n| `IdleTimeout` | Reclaim keep-alive connections |\n| `MaxHeaderBytes`, `MaxHeaderValueCount` (Go 1.27+) | Only to change the defaults, 1 MiB and 500 values: `MaxHeaderBytes: 1 \u003C\u003C 20` restates zero |\n| `Handler: http.NewCrossOriginProtection().Handler(mux)` | CSRF for state-changing requests (Go 1.25+). One per server: with CORS it is the instance go-security's `withCORS` builds with the trusted origins; a second, empty one around it answers every cross-origin POST with 403 |\n| `BaseContext` | Never the `signal.NotifyContext` context when in-flight requests should drain: it cancels every request at the signal, before `Shutdown` waits for them. Handlers that must see shutdown get a separate context, cancelled once `Shutdown`'s timeout expires |\n\nOne slow route does not raise `WriteTimeout` for all: that route extends its\nown deadline with `http.NewResponseController(w).SetWriteDeadline(t)`, as a\nstreaming route does. `http.TimeoutHandler(h, d, msg)` only shortens: it\ncancels `r.Context()` at `d` and answers 503, and with `d` above\n`WriteTimeout` the connection is cut first, with no response at all. It\nbuffers the response and has no `Flusher`.\n\nFor graceful shutdown, `signal.NotifyContext` owns the lifetime;\n`ListenAndServe` runs in one goroutine feeding a buffered error channel;\n`srv.Shutdown(ctx)` gets its own timeout.\n\n## Clients\n\n- Never `http.Get`, `http.Post`, or `http.DefaultClient` — no timeout. One\n  tuned `*http.Transport` and one `*http.Client{Timeout: d, Transport: t}` per\n  dependency, built once and reused. The Transport owns the connection pool: a\n  `Client` with a nil `Transport` shares `http.DefaultTransport`, which keeps\n  two idle connections per host (`http.DefaultMaxIdleConnsPerHost`). Tune a\n  clone of it; a `&http.Transport{...}` literal drops `ProxyFromEnvironment`\n  and the dial, TLS-handshake, and idle-connection timeouts (the SSRF dialer in\n  [go-security](..\u002Fgo-security\u002FSKILL.md) drops the proxy on purpose), and with\n  `DialContext` or `TLSClientConfig` set it speaks HTTP\u002F1.1 only unless\n  `ForceAttemptHTTP2` is true — an `HTTP2` config on it is ignored. A client\n  that keeps HTTP\u002F2 connections open — watch streams, many multiplexed\n  requests to one host — sets `SendPingTimeout` (Go 1.24+): at zero no health\n  check runs, and every stream on a connection a NAT dropped silently hangs\n  until its own deadline:\n\n  ```go\n  t := http.DefaultTransport.(*http.Transport).Clone()\n  t.MaxIdleConnsPerHost = 32\n  t.HTTP2 = &http.HTTP2Config{SendPingTimeout: 30 * time.Second}\n  client := &http.Client{Timeout: 10 * time.Second, Transport: t}\n  ```\n- `http.NewRequestWithContext(ctx, ...)` — the ctx-less form is unbounded;\n  `noctx` in the lint gate flags it.\n- The Transport reads the request body on its own goroutine, and that read\n  can outlive `Do`: a 4xx\u002F5xx answered from the headers, a timeout, or a\n  cancel returns mid-upload, and on HTTP\u002F2 the Transport's own `Close` of the\n  body can overlap a `Read`. Each request, retry included, gets its own\n  `bytes.NewReader` over bytes nobody writes again — never the previous\n  attempt's reader rewound, never a shared or pooled buffer refilled; `-race`\n  reports that write against the Transport's body writer.\n- `defer resp.Body.Close()` right after the `err != nil` return, on every\n  status (`bodyclose` flags a miss); on error `Do` returns no body to close.\n  Bound untrusted bodies and close them on every path. Go 1.27\n  drains an unread HTTP\u002F1 body on `Close` — up to 256 KiB and 50 ms — to keep\n  the connection reusable, so closing is the whole obligation; a manual read to\n  EOF only buys reuse for responses past those bounds.\n- Check `resp.StatusCode` before decoding; a 5xx body is not your struct.\n- For retry eligibility, `Retry-After`, replay safety, and coordinated budgets,\n  use [go-resilience](..\u002Fgo-resilience\u002FSKILL.md). HTTP status alone does not\n  establish whether repeating an operation is safe.\n\n\n### Bounded Response Bodies\n\nFor a strict response-size limit, read at most the limit plus one byte,\nreject an oversized result, then decode the complete buffer into `dst`.\nA decoder can finish its first object before `io.LimitReader` reaches its\nlimit; that alone does not enforce the size of the whole response.\n\n```go\nconst maxBody = 64 \u003C\u003C 10\nbody, err := io.ReadAll(io.LimitReader(resp.Body, maxBody+1))\nif err != nil {\n    return fmt.Errorf(\"read response: %w\", err)\n}\nif len(body) > maxBody {\n    return fmt.Errorf(\"response exceeds %d bytes\", maxBody)\n}\nreturn json.Unmarshal(body, dst)\n```\n\n## Partial Updates\n\nA PATCH body names only the members it changes, and a Go struct cannot tell a\nmissing member from a zero one: decoding into a fresh struct and saving it\nzeroes every field the client left out. Load the record, copy its\nclient-writable fields into the request value, and unmarshal the body onto\nthat value. v2 leaves an absent member as loaded and sets one sent as `null`\nto its zero value (v1 leaves it unchanged). `RejectUnknownMembers(true)`\nrefuses `password_hash` and any member the request type does not hold, and a\ntop-level `null` leaves the pointer nil. v2 decodes into what the request\nvalue already holds — it writes a non-nil slice's array, merges into a\nnon-nil map, decodes through a non-nil pointer — so a slice, map, or pointer\nfield is copied with `slices.Clone`, `maps.Clone`, or a new value; copied as\nis, the record changes before the body is rejected:\n\n```go\nr.Body = http.MaxBytesReader(w, r.Body, 1\u003C\u003C20)\nreq := &struct {\n    Email string   `json:\"email\"`\n    Phone string   `json:\"phone\"` \u002F\u002F \"phone\": null clears it\n    Tags  []string `json:\"tags\"`\n}{acct.Email, acct.Phone, slices.Clone(acct.Tags)} \u002F\u002F never acct.Tags: v2 writes into its array\nif err := json.UnmarshalRead(r.Body, &req, json.RejectUnknownMembers(true)); err != nil || req == nil {\n    http.Error(w, \"invalid JSON body\", http.StatusBadRequest)\n    return\n}\nif req.Email == \"\" { \u002F\u002F \"email\": null arrives as \"\"\n    http.Error(w, \"email is required\", http.StatusBadRequest)\n    return\n}\nacct.Email, acct.Phone, acct.Tags = req.Email, req.Phone, req.Tags \u002F\u002F a rejected body never touched acct\n```\n\n## Related Skills\n\n- [go-context](..\u002Fgo-context\u002FSKILL.md): derived deadlines and request lifetime.\n- [go-database](..\u002Fgo-database\u002FSKILL.md): handler queries and transactions.\n- [go-testing](..\u002Fgo-testing\u002FSKILL.md): `httptest` and `synctest`.\n- [go-concurrency](..\u002Fgo-concurrency\u002FSKILL.md): server goroutine and shared state.\n- [go-security](..\u002Fgo-security\u002FSKILL.md): input naming files, URLs or commands;\n  cookies, SSRF, and error disclosure.\n- [go-data-structures](..\u002Fgo-data-structures\u002FSKILL.md): nil versus empty slices\n  and maps before they reach the encoder.\n",{"name":5,"description":7},"main","59ac8ac7a0dd394878aaa0a7a7ecbc227356739f","skills\u002Fgo-http",2,"https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills","https:\u002F\u002Fgithub.com\u002Fh0rn3t","2026-11-14 04:23:12",{"source":8,"skillName":5,"commands":32,"prompt":42,"zipAvailable":43},[33,36,39],{"tool":34,"command":35},"npx","npx skills add h0rn3t\u002Fgolang-skills --skill go-http",{"tool":37,"command":38},"bunx","bunx skills add h0rn3t\u002Fgolang-skills --skill go-http",{"tool":40,"command":41},"pnpm","pnpm dlx skills add h0rn3t\u002Fgolang-skills --skill go-http","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-http\u002FSKILL.md",true,[45,51,55],{"path":46,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":49,"sourceHtmlUrl":50},"references\u002FGRPC.md","REFERENCE","参考文档",4099,"https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-http\u002Freferences\u002FGRPC.md",{"path":52,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":53,"sourceHtmlUrl":54},"references\u002FJSON-V2.md",5468,"https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-http\u002Freferences\u002FJSON-V2.md",{"path":56,"resourceType":47,"resourceTypeDesc":48,"sizeBytes":57,"sourceHtmlUrl":58},"references\u002FWEB-SERVER.md",3275,"https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-http\u002Freferences\u002FWEB-SERVER.md",[60,67,74,81,88,95],{"skillNo":61,"name":62,"nameZh":6,"description":63,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":64,"categories":65,"keywords":66,"publishedAt":19},"01M7BQEMJBPJWY6CCGVKW27SH0","go-troubleshooting","Use when investigating a bug or ticket in a Go service whose cause is unknown — wrong or missing results, tenant-specific behavior, a regression, stage\u002Fprod\u002FCI differences, a panic, hang, deadlock, leak, unexplained CPU\u002FRSS growth, or a flaky test. Also use for pasted stack traces, profiles, logs, or requests to find a Go issue's root cause, even without the word debug. Does not cover rewriting ticket text, implementing an already-diagnosed fix alone (use its topic skill), or optimizing a known bottleneck (see go-performance).","https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-troubleshooting\u002FSKILL.md",[],[],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":19},"01M7BQEFVSRHNDND750SB69WD8","go-testing","Use when writing, reviewing, or improving Go test code — including table-driven tests, subtests, parallel tests, test helpers, test doubles, and assertions with cmp.Diff. Also use when a user asks to write a test for a Go function, even if they don't mention specific patterns like table-driven tests or subtests. Does not cover benchmark performance testing (see go-performance).","https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-testing\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":19},"01M7BQEA2DRH6H6WFYNJYJJRQQ","go-style-core","Use when resolving Go style or language mechanics such as formatting, nesting, declarations, initialization, scope, shadowing, loops, switches, or enum zero values. API design, naming, errors, and tests have specialized skills.","https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-style-core\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":19},"01M7BQE3D1H45ANCXAWCS55CDK","go-security","Use when writing or reviewing Go code that touches untrusted input, secrets, or credentials — SQL, shell, or template injection, path traversal, SSRF, cookies and security headers, password hashing, TLS settings, token comparison, or what may appear in a log line. Also use when a handler accepts a file name, URL, or command argument from a client, or when asked to find \"vulnerabilities\", even if the user never says \"security\". Does not cover the os.Root and crypto\u002Frand mechanics (see go-defensive) or the dependency CVE scan in the gate (see go-linting).","https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-security\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"publishedAt":19},"01M7BQDZYHG2YRJA3J26HFPKR7","go-resilience","Use when handling Go dependency failures or overload with retries, backoff\u002Fjitter, budgets, idempotency, duplicate delivery, circuit breakers, bulkheads, rate limits, backpressure, or degradation. Unknown root causes belong to go-troubleshooting.","https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-resilience\u002FSKILL.md",[],[],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":19},"01M7BQDVG7DH2G9Z97Y8H3P3E9","go-performance","Use when optimizing slow or performance-critical Go code, allocations, string concatenation in loops, or benchmarks. Also use when writing or reviewing a cache, including implementing one from a stub — its key, its expiry, and how a miss loads. Concurrent code patterns belong to go-concurrency.","https:\u002F\u002Fgithub.com\u002Fh0rn3t\u002Fgolang-skills\u002Fblob\u002Fmain\u002Fskills\u002Fgo-performance\u002FSKILL.md",[],[]]