{"guides":[],"hints":[{"hint":"Look at which mux the package's init function writes to.","lessonID":"gin.admin-listener","nuance":"Its init calls http.HandleFunc on http.DefaultServeMux, however you import it. Gin never consults that mux, so exposure depends on what serves it: a nil handler, a NoRoute fallback or a second server."},{"hint":"Consider what changes in the bytes when the same object is encoded twice.","lessonID":"gin.api-tests","nuance":"Two encodings of one object can differ in key order and spacing. Decoding compares values, and because DeepEqual still sees every member, an unexpected detail field fails the test."},{"hint":"One header announces a state; the other announces an end.","lessonID":"gin.api-versioning","nuance":"Deprecation only discourages the resource and changes no behavior; Sunset is when it may stop responding. The route-table test enforces Sunset, and traffic per route template shows when removal hurts no one."},{"hint":"Look up when net/http cancels the context of an incoming server request.","lessonID":"gin.async-jobs","nuance":"net/http cancels an incoming request's context when ServeHTTP returns, so the job sees context.Canceled. context.WithoutCancel keeps the values and drops the cancellation; the worker then adds its own deadline."},{"hint":"Would sending the same request again with a freshly issued copy of this token change the outcome?","lessonID":"gin.auth-middleware","nuance":"401 means the credentials are missing or invalid, so a retry with good ones may succeed. This token verified, so the refusal is about permission, which RFC 6750 signals with 403 and insufficient_scope."},{"hint":"Count how often each loader runs, not how many IDs it receives.","lessonID":"gin.batched-includes","nuance":"Each loader receives every ID on the page and makes a single round trip, so the cost is one plus the number of includes whatever the page size; the N+1 shape grows with the page."},{"hint":"MaxBytesReader supplies a 1 KiB input budget.","lessonID":"gin.binding-limits","nuance":"No. Normalize and validate the business rule explicitly; body limits, parsing, authorization and side-effect ordering are separate contracts."},{"hint":"Look at what binding.Uri does right after it maps the path parameters.","lessonID":"gin.binding-sources","nuance":"BindUri maps only uri tags and then runs the validator on the entire struct, so the still-empty Title fails required before ShouldBindJSON has had a chance to fill it."},{"hint":"The cache needs to know which request header changed the response.","lessonID":"gin.compression","nuance":"Vary tells caches to key the stored response by Accept-Encoding. Without it on both variants, the first stored copy is served to every client regardless of what it can decode; no-transform only forbids intermediaries from changing the body."},{"hint":"Check which Cache-Control directives allow a shared cache to reuse a response to an authenticated request.","lessonID":"gin.conditional-requests","nuance":"RFC 9111 lets a shared cache reuse a response to a request with Authorization only when directives such as public allow it. Adding public removes that protection, so the CDN can replay one user's data to the next."},{"hint":"Follow the signal context down to each request's r.Context().","lessonID":"gin.config-startup","nuance":"Every request context derives from BaseContext, so cancelling it on SIGTERM aborts the in-flight requests that a graceful Shutdown is meant to let finish."},{"hint":"Look at what parseAccept keeps from each element of the header.","lessonID":"gin.content-negotiation","nuance":"parseAccept cuts every element at its first semicolon, so q=0 disappears and text/csv is the first accepted entry that matches an offer. RFC 9110 would exclude it and pick application/json through */*."},{"hint":"Look at what Done and Err check before they delegate to c.Request.","lessonID":"gin.context-fallback","nuance":"Deadline, Done and Err delegate to c.Request.Context() only when engine.ContextWithFallback is true, and gin.New leaves it false, so the store never learns the client left. Passing c.Request.Context() works under either setting."},{"hint":"The handler sends a copied string in a small value and never lets the worker use c.Writer.","lessonID":"gin.context-workers","nuance":"No. Extract the data a worker needs, never reuse the completed response writer, and define queue capacity, lifetime and durability."},{"hint":"Compare /v2/notes/7 with the keys of the paths object.","lessonID":"gin.contract-drift","nuance":"c.FullPath() returns the template, such as /v2/notes/:id, which maps to /v2/notes/{id}; raw paths would give one key per ID. It is empty for unmatched requests, so the middleware skips NoRoute answers."},{"hint":"Think about what * would mean for the cookies of every signed-in user on every website.","lessonID":"gin.cors","nuance":"Browsers refuse * when credentials are included, so the server must echo one allow-listed origin and add Vary: Origin. Reflecting any origin instead would expose authenticated data to every site."},{"hint":"Compare what a plain bool holds when the field is missing and when it is false.","lessonID":"gin.crud-resource","nuance":"With a plain bool an omitted field and an explicit false both decode to false, so the handler cannot tell \"leave it\" from \"unpin it\". A nil pointer marks absence."},{"hint":"Remove dive from the program's Items tag and send the invalid SKU again.","lessonID":"gin.custom-validators","nuance":"Without dive the validator checks only the slice itself, such as required and min; dive tells it to descend into every element, applying the tags after dive and each struct element's own tags."},{"hint":"If-Range compares validators the strict way.","lessonID":"gin.downloads-ranges","nuance":"If-Range requires the strong comparison, which a weak ETag never passes. ServeContent then ignores the Range header and sends the whole file with 200, so every resume starts again from byte zero."},{"hint":"The route records an application error and stops the pending handler chain.","lessonID":"gin.errors-testing","nuance":"No. Recovery handles control flow; transaction and external-effect recovery need their own explicit ownership and reconciliation rules."},{"hint":"Read how Request.ParseMultipartForm describes its maxMemory argument.","lessonID":"gin.file-uploads","nuance":"MaxMultipartMemory is the maxMemory argument to ParseMultipartForm: the remainder of the file is written to temporary files, so only http.MaxBytesReader actually bounds the request."},{"hint":"Look at which method the test loop calls on the router.","lessonID":"gin.first-service","nuance":"The engine implements ServeHTTP, so httptest.NewRecorder can capture its response exactly as http.Server would deliver it to a client."},{"hint":"Ask which package needs to replace the dependency in its tests.","lessonID":"gin.handler-dependencies","nuance":"The consumer knows which methods it calls. Declaring the interface there keeps it small, leaves the provider concrete and avoids an import from the domain back to the adapter."},{"hint":"Compare the /broken and /broken-buffered responses.","lessonID":"gin.html-templates","nuance":"c.HTML sets the status before executing into the response, so a failure leaves a 200 with an empty or partial page; buffering lets the handler pick the status after execution has succeeded."},{"hint":"The key promises one effect for one request; ask whether this is still the same request.","lessonID":"gin.idempotency-keys","nuance":"Replaying would hand back a note the client did not ask for and hide its bug; running it would allow a second effect. Rejecting with 422 keeps one key bound to one request."},{"hint":"Check which kinds of values omitempty treats as empty.","lessonID":"gin.json-responses","nuance":"omitempty checks false, 0, nil and zero length, and a struct is none of those, so the zero time renders as 0001-01-01T00:00:00Z; omitzero consults the IsZero method instead."},{"hint":"Ask what the platform does when liveness fails on every replica at the same moment.","lessonID":"gin.metrics-health","nuance":"A failed liveness probe triggers a restart. Restarting every replica cannot repair the database and adds reconnect load, while a failed readiness probe only takes the replica out of traffic."},{"hint":"Look at which loop invokes the handlers and when it stops.","lessonID":"gin.middleware-basics","nuance":"Gin's top-level c.Next loop keeps advancing the index after each handler returns; only Abort moves the index past the end, so Next matters only for code that must run afterwards."},{"hint":"Gin keeps a separate routing tree for every method; which one does a HEAD request search?","lessonID":"gin.not-found-and-methods","nuance":"There is no implicit HEAD fallback in Gin's router, so HEAD /items is a 404, or a 405 with Allow: GET when HandleMethodNotAllowed is on."},{"hint":"One status means a condition was evaluated and failed; another means no condition was sent.","lessonID":"gin.optimistic-concurrency","nuance":"412 reports a precondition that was present and false. RFC 6585 defines 428 for a server that requires a precondition the request did not include."},{"hint":"Think about what decides the order of two rows with equal timestamps.","lessonID":"gin.pagination-filtering","nuance":"Without a unique last sort column the order of ties is unspecified, so a page that ends between them leaves the next query no exact point to resume from."},{"hint":"Compare the field after decoding {} with the field after decoding {\"due\":null}.","lessonID":"gin.patch-merge","nuance":"encoding/json sets a pointer to nil for JSON null, which is also what an absent member leaves behind, so the handler cannot tell \"clear it\" from \"leave it alone\". A map of json.RawMessage or a tri-state type keeps the two apart."},{"hint":"Count how many distinct values the label could take across all users.","lessonID":"gin.path-parameters","nuance":"FullPath is the registered pattern, so /users/1 and /users/2 share one series; it is empty when no route matched, so unmatched requests need their own fixed label."},{"hint":"The domain package does not import net/http.","lessonID":"gin.problem-details","nuance":"One mapping middleware means one table to review, one envelope for clients and no handler that can forget to hide an internal error's text."},{"hint":"Look for the one function that names concrete types such as MemoryStore.","lessonID":"gin.project-layout","nuance":"Only the composition root knows every concrete type. The adapters import the domain and the domain imports nothing from the project, so swapping a store changes main and nothing else."},{"hint":"Compare what GetQuery reports for ?limit= and for a request without limit.","lessonID":"gin.query-and-forms","nuance":"DefaultQuery is built on GetQuery, which returns ok=true for ?limit=, so the handler receives \"\" and must decide whether empty is an error."},{"hint":"ReserveN has already updated the bucket as if the request would run later.","lessonID":"gin.rate-limiting","nuance":"A reservation with a delay borrows a token from the future. If the request is dropped instead of delayed, CancelAt returns that token, so the client is not charged for work that never happened."},{"hint":"Ask which file the kernel needs before main can run.","lessonID":"gin.release-builds","nuance":"With a C compiler present cgo is on, so net and os/user link dynamically and need a loader such as ld-linux. The static image has none, so exec reports no such file or directory; CGO_ENABLED=0 builds a static binary."},{"hint":"Count how many distinct values the field would hold after a million requests for different notes.","lessonID":"gin.request-logging","nuance":"FullPath has one value per registered route and never contains IDs or query strings, so it can be grouped and alerted on without leaking tokens or personal data."},{"hint":"Ask whether the key captures every input the handler can read.","lessonID":"gin.response-cache","nuance":"The key holds only the route, its params and the allow-listed query. A handler that reads Authorization can return per-user data, and caching it would serve one caller's response to the next, so the request must bypass the cache."},{"hint":"Ask what happens if the first attempt actually committed.","lessonID":"gin.retries-breakers","nuance":"A timeout is ambiguous: the first attempt may have succeeded and only its response was lost. Resending the same Idempotency-Key lets the upstream replay the stored result instead of charging twice; PUT and DELETE are idempotent too."},{"hint":"Think about who still believes the old Pod is a valid target.","lessonID":"gin.rolling-deploys","nuance":"Endpoint removal and SIGTERM start together, and proxies learn of the removal late. Shutdown closes the listener at once, refusing connections still routed to the Pod; a short serving delay covers that window."},{"hint":"Think about the moment at which a route's handler chain is assembled.","lessonID":"gin.route-groups","nuance":"Registering a route or creating a subgroup copies the group's handlers at that moment; a later Use appends to the group's slice but cannot reach chains that were already copied."},{"hint":"The first middleware records before, delegates with Next and records after when the rest of the chain returns.","lessonID":"gin.routing-middleware","nuance":"Yes. Abort skips pending handlers, but ordinary Go control flow continues; return explicitly when the current middleware must stop."},{"hint":"Look at what URL.Query does with the error returned by url.ParseQuery.","lessonID":"gin.safe-filters","nuance":"URL.Query discards ParseQuery's error and keeps only the pairs it could parse. A semicolon is no longer a separator, so the whole pair is dropped and the query loses its filter. Parse RawQuery yourself and answer 400."},{"hint":"The constructor makes header and idle budgets visible.","lessonID":"gin.server-lifecycle","nuance":"No. The application must own and join workers and manage hijacked connections separately, within an explicit shutdown budget."},{"hint":"Read how CustomRecoveryWithWriter classifies a recovered error before it decides whether to call the handle function.","lessonID":"gin.streaming-export","nuance":"Recovery treats ErrAbortHandler like a broken pipe: it records the error, aborts the chain and returns normally, so net/http completes the chunked body. Re-panic from a middleware registered before Recovery."},{"hint":"Count how many times binding.JSON calls Decode before it validates.","lessonID":"gin.streaming-import","nuance":"Gin's decodeJSON makes one Decode call and never checks for more input, so the remaining lines are never read. A per-line reader with a trailing-data check is what sees every record."},{"hint":"Read the first lines of Context.Stream, then list the interfaces ResponseRecorder implements.","lessonID":"gin.streaming-sse","nuance":"Stream calls c.Writer.CloseNotify(), which type-asserts the underlying writer to http.CloseNotifier. ResponseRecorder does not implement it, so the assertion panics, and tests need a loop on the request context instead."},{"hint":"Look for the engine flag that Context.Done checks before it delegates.","lessonID":"gin.timeouts-cancellation","nuance":"Context.Done delegates to c.Request.Context() only when engine.ContextWithFallback is true. The default is false, so a dependency that waits on c never sees the deadline."},{"hint":"With trusted proxies disabled, ClientIP uses the peer address and ignores the claimed forwarded client address.","lessonID":"gin.trusted-proxies","nuance":"No. Disable proxy trust when unused; behind a proxy trust only controlled peers and keep authentication separate from client IP."},{"hint":"The slow party is neither your client nor your own code.","lessonID":"gin.upstream-clients","nuance":"504 says a server acting as a gateway got no timely answer from an upstream. 408 would blame the client for sending its request slowly, and the Go error text would leak internal hostnames."},{"hint":"Think about what the sender's HMAC was computed over, and what binding does to the request body.","lessonID":"gin.webhook-receiver","nuance":"Binding reads c.Request.Body to EOF, and re-encoding the struct does not reproduce the sender's bytes, so the MAC can only be checked on the raw body, read first and then restored for the handler."}],"id":"gin","labs":[],"practice":{"bugs":[],"drills":[],"interviews":[],"quizzes":[],"reviewPairs":[],"reviewRounds":[]},"readings":[{"conceptTag":"gin.routing-middleware","designGuide":{"cautions":["A middleware that calls AbortWithStatus must still return if later statements must not run.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"gin","flow":["Match group + route","Before middleware","Handler or abort","After middleware"],"ratings":[],"strengths":["Explain route groups, middleware order and the difference between Abort and return.","Makes the owner and the failure boundary explicit."]},"hint":"The first middleware records before, delegates with Next and records after when the rest of the chain returns.","id":"gin.routing-middleware","introduction":"A Gin engine is an HTTP adapter with a middleware chain. Group prefixes and registration order decide which handlers participate; the framework does not supply your business transaction. Follow one request before introducing authentication, metrics or error middleware. In particular, Abort stops pending handlers but does not return from the current Go function.","nuance":"Yes. Abort skips pending handlers, but ordinary Go control flow continues; return explicitly when the current middleware must stop.","objective":"Explain route groups, middleware order and the difference between Abort and return.","question":"After c.AbortWithStatus(401), may later statements in the same middleware still run?","references":["https://pkg.go.dev/github.com/gin-gonic/gin","https://github.com/gin-gonic/gin/blob/master/context.go"],"reviewAnswer":"Next delegates; Abort does not return from Go","reviewPrompt":"Gin middleware chain","sections":[{"body":"A Gin engine is an HTTP adapter with a middleware chain. Group prefixes and registration order decide which handlers participate; the framework does not supply your business transaction. Follow one request before introducing authentication, metrics or error middleware. In particular, Abort stops pending handlers but does not return from the current Go function.","title":"The contract and the failure"},{"body":"Construct the engine and register middleware before serving requests. Group related routes under an explicit version or capability. Keep application services transport-independent and pass only validated input and the request context. Test allowed methods, missing routes and middleware ordering with httptest.NewRecorder and ServeHTTP, without requiring a network listener.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"net/http/httptest\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := gin.New()\n\ttrace := []string{}\n\tr.Use(func(c *gin.Context) { trace = append(trace, \"before\"); c.Next(); trace = append(trace, \"after\") })\n\tv1 := r.Group(\"/v1\")\n\tv1.GET(\"/health\", func(c *gin.Context) { trace = append(trace, \"handler\"); c.JSON(200, gin.H{\"ok\": true}) })\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, httptest.NewRequest(\"GET\", \"/v1/health\", nil))\n\tfmt.Println(w.Code, trace) // 200 [before handler after]\n}","language":"go","title":"Work through the example","walkthrough":"The first middleware records before, delegates with Next and records after when the rest of the chain returns. The slice is safe only because this demonstration serves one request synchronously; a shared mutable trace slice would race in a real concurrent server. Per-request trace data belongs in the request or telemetry system."},{"body":"A middleware that calls AbortWithStatus must still return if later statements must not run. Registering sensitive routes outside the authenticated group can bypass policy. Avoid modifying routes or global Gin settings during traffic. This lesson uses upstream native Gin APIs; GopherForge’s small Gin-compatible teaching adapter does not promise every upstream middleware or router behavior.","title":"Production decisions"},{"body":"After c.AbortWithStatus(401), may later statements in the same middleware still run? Yes. Abort skips pending handlers, but ordinary Go control flow continues; return explicitly when the current middleware must stop. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Explain route groups, middleware order and the difference between Abort and return. Yes. Abort skips pending handlers, but ordinary Go control flow continues; return explicitly when the current middleware must stop.","title":"Gin routing and middleware: follow the chain and stop it deliberately","unitID":"gin","wrongAnswers":["Abort returns from the current function","A route group supplies a database transaction"]},{"conceptTag":"gin.binding-limits","designGuide":{"cautions":["BindJSON may abort and write a response automatically; trying to overwrite it later can produce the wrong status or duplicate output.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"gin","flow":["Limit bytes","Bind DTO","Validate + authorize","Call use case"],"ratings":[],"strengths":["Reject oversized or invalid input before performing a business side effect.","Makes the owner and the failure boundary explicit."]},"hint":"MaxBytesReader supplies a 1 KiB input budget.","id":"gin.binding-limits","introduction":"Binding converts a request into a Go value. It does not prove authorization or a business invariant, and it does not by itself impose your desired body-size budget. A robust handler limits input first, chooses whether errors are returned or immediately written, validates normalized values and only then calls the use case. Return one deliberate response instead of letting several layers compete to write it.","nuance":"No. Normalize and validate the business rule explicitly; body limits, parsing, authorization and side-effect ordering are separate contracts.","objective":"Reject oversized or invalid input before performing a business side effect.","question":"Which sequence should an HTTP JSON boundary follow before changing business state?","references":["https://pkg.go.dev/github.com/gin-gonic/gin#Context.ShouldBindJSON","https://pkg.go.dev/net/http#MaxBytesReader","https://pkg.go.dev/encoding/json#Decoder.DisallowUnknownFields"],"reviewAnswer":"Limit bytes, bind, validate, authorize, then act","reviewPrompt":"Gin request validation","sections":[{"body":"Binding converts a request into a Go value. It does not prove authorization or a business invariant, and it does not by itself impose your desired body-size budget. A robust handler limits input first, chooses whether errors are returned or immediately written, validates normalized values and only then calls the use case. Return one deliberate response instead of letting several layers compete to write it.","title":"The contract and the failure"},{"body":"Select binders explicitly when input sources matter, and distinguish optional, zero and null values in the DTO. Check a second decode for trailing JSON and reject unknown fields when the API contract requires strict JSON; a single successful binder call does not establish those stronger properties. Gin’s decoder options are process-wide configuration and should be set before concurrent serving, not toggled per request.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := gin.New()\n\tr.POST(\"/notes\", func(c *gin.Context) {\n\t\tc.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 1024)\n\t\tvar in struct {\n\t\t\tTitle string `json:\"title\" binding:\"required,max=80\"`\n\t\t}\n\t\tif err := c.ShouldBindJSON(&in); err != nil {\n\t\t\tvar large *http.MaxBytesError\n\t\t\tif errors.As(err, &large) {\n\t\t\t\tc.AbortWithStatus(413)\n\t\t\t} else {\n\t\t\t\tc.AbortWithStatus(400)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\ttitle := strings.TrimSpace(in.Title)\n\t\tif title == \"\" {\n\t\t\tc.AbortWithStatus(400)\n\t\t\treturn\n\t\t}\n\t\tc.JSON(201, gin.H{\"title\": title})\n\t})\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, httptest.NewRequest(\"POST\", \"/notes\", strings.NewReader(`{\"title\":\"   \"}`)))\n\tfmt.Println(w.Code) // 400, before any write to storage\n}","language":"go","title":"Work through the example","walkthrough":"MaxBytesReader supplies a 1 KiB input budget. ShouldBindJSON returns the error so this handler owns the response. The whitespace-only title can pass a required tag, so normalization and the business rule still reject it. The example returns a small error response and never echoes parser internals or secret request content."},{"body":"BindJSON may abort and write a response automatically; trying to overwrite it later can produce the wrong status or duplicate output. Validation tags do not check ownership of a referenced object and do not make arbitrary SQL safe. Test malformed JSON, oversized input, whitespace, omitted fields, trailing values, unknown fields and unauthorized resource IDs as distinct cases.","title":"Production decisions"},{"body":"A title contains only spaces and has a required tag. Is the business input necessarily valid? No. Normalize and validate the business rule explicitly; body limits, parsing, authorization and side-effect ordering are separate contracts. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Reject oversized or invalid input before performing a business side effect. No. Normalize and validate the business rule explicitly; body limits, parsing, authorization and side-effect ordering are separate contracts.","title":"Gin input: size limits, binding and business validation are separate","unitID":"gin","wrongAnswers":["A required tag proves business validity","Binding is a body-size and authorization limit"]},{"conceptTag":"gin.context-workers","designGuide":{"cautions":["A c.Copy call does not make asynchronous response writes safe or turn the request context into a process context.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"gin","flow":["Extract immutable input","Bound admission","Worker owns lifetime","Join or recover durable job"],"ratings":[],"strengths":["Give background work a bounded owner without keeping a pooled Gin context alive.","Makes the owner and the failure boundary explicit."]},"hint":"The handler sends a copied string in a small value and never lets the worker use c.Writer.","id":"gin.context-workers","introduction":"Gin reuses contexts after a handler returns. Passing the original *gin.Context into a goroutine can observe another request’s mutable state. Copy is useful for limited read-only context access, but it does not extend the response writer’s lifetime, clone every referenced object or give detached work a durable owner. Prefer extracting immutable job input and handing it to a deliberately managed queue.","nuance":"No. Extract the data a worker needs, never reuse the completed response writer, and define queue capacity, lifetime and durability.","objective":"Give background work a bounded owner without keeping a pooled Gin context alive.","question":"How should a Gin handler hand work to a worker that continues after the response?","references":["https://github.com/gin-gonic/gin/blob/master/context.go","https://pkg.go.dev/context","https://go.dev/ref/mem"],"reviewAnswer":"Extract input; give the worker its own owner","reviewPrompt":"Gin background work","sections":[{"body":"Gin reuses contexts after a handler returns. Passing the original *gin.Context into a goroutine can observe another request’s mutable state. Copy is useful for limited read-only context access, but it does not extend the response writer’s lifetime, clone every referenced object or give detached work a durable owner. Prefer extracting immutable job input and handing it to a deliberately managed queue.","title":"The contract and the failure"},{"body":"For best-effort work, state its lifetime and cancellation policy. For must-complete work, persist a job before acknowledging acceptance and use idempotent processing. Copy only immutable data required by the worker; slices and maps need an ownership decision. Request cancellation is appropriate for request work, while detached work needs an application-owned context with its own deadline and shutdown path.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"net/http/httptest\"\n\t\"sync\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype Job struct{ Path string }\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tjobs := make(chan Job, 1)\n\tvar wg sync.WaitGroup\n\twg.Add(1)\n\tgo func() {\n\t\tdefer wg.Done()\n\t\tfor job := range jobs {\n\t\t\tfmt.Println(\"work\", job.Path)\n\t\t}\n\t}()\n\tr := gin.New()\n\tr.POST(\"/jobs\", func(c *gin.Context) {\n\t\tjob := Job{Path: c.Request.URL.Path}\n\t\tselect {\n\t\tcase jobs <- job:\n\t\t\tc.Status(202)\n\t\tdefault:\n\t\t\tc.Status(503)\n\t\t}\n\t})\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, httptest.NewRequest(\"POST\", \"/jobs\", nil))\n\tfmt.Println(\"accepted\", w.Code)\n\tclose(jobs)\n\twg.Wait()\n}","language":"go","title":"Work through the example","walkthrough":"The handler sends a copied string in a small value and never lets the worker use c.Writer. The channel has a fixed capacity and the process joins its worker. Output order of accepted versus work is intentionally unspecified. This queue is in-memory: returning 202 here does not promise survival of a process crash."},{"body":"A c.Copy call does not make asynchronous response writes safe or turn the request context into a process context. Unbounded goroutines are an unbounded queue. Sending to a channel while another owner closes it can panic. Test queue-full rejection, shutdown while a handler is enqueueing, duplicate jobs and process recovery separately from ordinary request success.","title":"Production decisions"},{"body":"Does c.Copy make it safe to write a response after the handler returns? No. Extract the data a worker needs, never reuse the completed response writer, and define queue capacity, lifetime and durability. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Give background work a bounded owner without keeping a pooled Gin context alive. No. Extract the data a worker needs, never reuse the completed response writer, and define queue capacity, lifetime and durability.","title":"Gin contexts and goroutines: extract a job, do not retain the response","unitID":"gin","wrongAnswers":["Capture c and write after the response ends","Copy makes a job durable and uncancelled"]},{"conceptTag":"gin.trusted-proxies","designGuide":{"cautions":["Trusting 0.0.0.0/0 or accepting a header called X-User is not authentication.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"gin","flow":["Observe actual peer","Check proxy trust","Derive network address","Authorize principal separately"],"ratings":[],"strengths":["Configure proxy trust explicitly and keep client IP separate from authentication.","Makes the owner and the failure boundary explicit."]},"hint":"With trusted proxies disabled, ClientIP uses the peer address and ignores the claimed forwarded client address.","id":"gin.trusted-proxies","introduction":"A reverse proxy may supply the original client address, but a direct client can also send X-Forwarded-For. If a Go service trusts forwarding headers from every peer, address-based controls can be bypassed. Configure exactly which proxy origins are trusted and make the edge replace or sanitize incoming forwarding headers. An IP address remains a network observation, not a user credential.","nuance":"No. Disable proxy trust when unused; behind a proxy trust only controlled peers and keep authentication separate from client IP.","objective":"Configure proxy trust explicitly and keep client IP separate from authentication.","question":"The service has no proxy. Should it trust X-Forwarded-For supplied by clients?","references":["https://github.com/gin-gonic/gin/blob/master/gin.go","https://pkg.go.dev/github.com/gin-gonic/gin#Engine.SetTrustedProxies"],"reviewAnswer":"Trust configured proxies, not arbitrary peers","reviewPrompt":"Trusted forwarding headers","sections":[{"body":"A reverse proxy may supply the original client address, but a direct client can also send X-Forwarded-For. If a Go service trusts forwarding headers from every peer, address-based controls can be bypassed. Configure exactly which proxy origins are trusted and make the edge replace or sanitize incoming forwarding headers. An IP address remains a network observation, not a user credential.","title":"The contract and the failure"},{"body":"Write down the chain of load balancers and ingress proxies. Restrict direct access to the service where practical, configure Gin trust and verify how the edge processes preexisting forwarding headers. Use TLS according to the actual termination boundary. Rate-limit authenticated identities and service capacity as well as addresses; many legitimate users can share one NAT address.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"net/http/httptest\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := gin.New()\n\tif err := r.SetTrustedProxies(nil); err != nil {\n\t\tpanic(err)\n\t}\n\tr.GET(\"/ip\", func(c *gin.Context) { c.String(200, c.ClientIP()) })\n\treq := httptest.NewRequest(\"GET\", \"/ip\", nil)\n\treq.RemoteAddr = \"192.0.2.10:4321\"\n\treq.Header.Set(\"X-Forwarded-For\", \"203.0.113.77\")\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, req)\n\tfmt.Println(w.Body.String()) // 192.0.2.10, not the supplied header\n}","language":"go","title":"Work through the example","walkthrough":"With trusted proxies disabled, ClientIP uses the peer address and ignores the claimed forwarded client address. The documentation-only addresses are reserved example ranges. Behind a real controlled proxy, configure its actual narrow address ranges instead of copying these values or trusting all private networks."},{"body":"Trusting 0.0.0.0/0 or accepting a header called X-User is not authentication. Forwarded host and scheme can also affect generated URLs and redirects. Test a direct spoofed request, a legitimate proxy, multiple forwarded hops and IPv6. Keep proxy configuration immutable while the engine serves traffic and review it after topology changes.","title":"Production decisions"},{"body":"The service has no proxy. Should it trust X-Forwarded-For supplied by clients? No. Disable proxy trust when unused; behind a proxy trust only controlled peers and keep authentication separate from client IP. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Configure proxy trust explicitly and keep client IP separate from authentication. No. Disable proxy trust when unused; behind a proxy trust only controlled peers and keep authentication separate from client IP.","title":"Trusted proxies: forwarded headers are not proof of identity","unitID":"gin","wrongAnswers":["Every forwarded header is authoritative","Client IP is a user authentication token"]},{"conceptTag":"gin.errors-testing","designGuide":{"cautions":["A test that asserts only status 200 can miss a leaked secret body or a second write after an error.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"gin","flow":["Use case returns cause","Record expected error","Map once","Assert response and effects"],"ratings":[],"strengths":["Test handler contracts through ServeHTTP without confusing recovery with rollback.","Makes the owner and the failure boundary explicit."]},"hint":"The route records an application error and stops the pending handler chain.","id":"gin.errors-testing","introduction":"Framework recovery can keep a panic from crashing a request-serving goroutine, but it cannot undo a committed database write or decide whether a remote operation succeeded. Expected application errors should travel through a deliberate mapping policy. Assign one layer to produce the response, and test both its status and public body rather than checking only that the handler returned.","nuance":"No. Recovery handles control flow; transaction and external-effect recovery need their own explicit ownership and reconciliation rules.","objective":"Test handler contracts through ServeHTTP without confusing recovery with rollback.","question":"What is the ownership rule for turning an expected use-case error into an HTTP response?","references":["https://pkg.go.dev/github.com/gin-gonic/gin#Context.Error","https://pkg.go.dev/net/http/httptest","https://pkg.go.dev/errors#Is"],"reviewAnswer":"One owner maps expected errors to one response","reviewPrompt":"HTTP error boundary","sections":[{"body":"Framework recovery can keep a panic from crashing a request-serving goroutine, but it cannot undo a committed database write or decide whether a remote operation succeeded. Expected application errors should travel through a deliberate mapping policy. Assign one layer to produce the response, and test both its status and public body rather than checking only that the handler returned.","title":"The contract and the failure"},{"body":"Use table-driven requests with method, path, input, verified identity and expected response. Check status, headers, JSON shape and whether forbidden side effects occurred. Inject a narrow application service and test the real storage adapter separately. Add panic recovery as a last-resort boundary, plus structured logging, without using panic as routine validation control flow.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http/httptest\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nvar errMissing = errors.New(\"missing\")\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := gin.New()\n\tr.Use(func(c *gin.Context) {\n\t\tc.Next()\n\t\tif c.Writer.Written() || len(c.Errors) == 0 {\n\t\t\treturn\n\t\t}\n\t\tstatus := 500\n\t\tif errors.Is(c.Errors.Last().Err, errMissing) {\n\t\t\tstatus = 404\n\t\t}\n\t\tc.JSON(status, gin.H{\"error\": \"request failed\"})\n\t})\n\tr.GET(\"/orders/:id\", func(c *gin.Context) { _ = c.Error(errMissing); c.Abort() })\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, httptest.NewRequest(\"GET\", \"/orders/7\", nil))\n\tfmt.Println(w.Code, w.Body.String())\n}","language":"go","title":"Work through the example","walkthrough":"The route records an application error and stops the pending handler chain. After Next returns, middleware maps a known missing value to 404 and writes once if no earlier layer committed the response. The public body is deliberately stable and does not expose a database error. Logging the detailed cause belongs at a protected reporting boundary."},{"body":"A test that asserts only status 200 can miss a leaked secret body or a second write after an error. Returning an error from a helper does not automatically attach it to Gin. Recovery is not a transaction manager. Test malformed and unauthorized requests, missing resources, dependency cancellation, unknown outcomes and a panic after a simulated effect.","title":"Production decisions"},{"body":"A panic recovery middleware returns 500. Does that prove earlier side effects were rolled back? No. Recovery handles control flow; transaction and external-effect recovery need their own explicit ownership and reconciliation rules. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Test handler contracts through ServeHTTP without confusing recovery with rollback. No. Recovery handles control flow; transaction and external-effect recovery need their own explicit ownership and reconciliation rules.","title":"Gin errors and tests: one response owner, explicit failure cases","unitID":"gin","wrongAnswers":["Recovery rolls back committed effects","A helper error automatically becomes an HTTP status"]},{"conceptTag":"gin.server-lifecycle","designGuide":{"cautions":["Shutdown does not close or wait for hijacked connections such as custom WebSocket lifetimes.","Run native service and failure tests in your own development environment."],"cost":"Additional state and tests must be justified by the demonstrated failure; this lesson is not a requirement for every Go program.","family":"gin","flow":["Bound admission","Withdraw readiness","Drain HTTP requests","Join workers + close clients"],"ratings":[],"strengths":["Configure native server timeouts and distinguish HTTP drain from worker completion.","Makes the owner and the failure boundary explicit."]},"hint":"The constructor makes header and idle budgets visible.","id":"gin.server-lifecycle","introduction":"A router handles requests, while net/http.Server owns listener behavior and connection budgets. A short r.Run example is useful for a tutorial, but a deployed service needs an explicit startup and shutdown owner. Readiness, request admission, long-lived streams, background workers and shared clients must fit the same lifecycle rather than each inventing its own stop signal.","nuance":"No. The application must own and join workers and manage hijacked connections separately, within an explicit shutdown budget.","objective":"Configure native server timeouts and distinguish HTTP drain from worker completion.","question":"After http.Server.Shutdown returns, must every application worker and hijacked connection be finished?","references":["https://pkg.go.dev/net/http#Server.Shutdown","https://pkg.go.dev/net/http#Server"],"reviewAnswer":"Server shutdown does not own every goroutine","reviewPrompt":"HTTP drain versus worker join","sections":[{"body":"A router handles requests, while net/http.Server owns listener behavior and connection budgets. A short r.Run example is useful for a tutorial, but a deployed service needs an explicit startup and shutdown owner. Readiness, request admission, long-lived streams, background workers and shared clients must fit the same lifecycle rather than each inventing its own stop signal.","title":"The contract and the failure"},{"body":"Reject new work during drain and stop reporting readiness before termination when the platform requires it. Allow in-flight operations a defined budget, then join owned workers and close shared dependencies in order. ReadTimeout and WriteTimeout interact with request bodies and streaming, so configure them for the protocol instead of copying one magic timeout to every service.","code":"package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc stop(srv *http.Server) error {\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancel()\n\treturn srv.Shutdown(ctx)\n}\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := gin.New()\n\tr.GET(\"/ready\", func(c *gin.Context) { c.Status(200) })\n\tsrv := &http.Server{Addr: \"127.0.0.1:8080\", Handler: r, ReadHeaderTimeout: 2 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10}\n\t// Configuration example: no listener is opened by this program.\n\tfmt.Println(srv.ReadHeaderTimeout, srv.IdleTimeout, srv.MaxHeaderBytes)\n}","language":"go","title":"Work through the example","walkthrough":"The constructor makes header and idle budgets visible. stop creates a fresh bounded shutdown context rather than using an already-cancelled request context. This example opens no socket. In a native service, separately own Serve or ListenAndServe, distinguish http.ErrServerClosed from a startup failure and decide how to handle shutdown exceeding its budget."},{"body":"Shutdown does not close or wait for hijacked connections such as custom WebSocket lifetimes. A readiness endpoint that always returns 200 does not prove downstream capacity; avoid making liveness fail merely because a dependency is temporarily unavailable. Test a slow header, cancellation, a long request during drain and a worker that ignores its stop contract in a native integration environment.","title":"Production decisions"},{"body":"After http.Server.Shutdown returns, must every application worker and hijacked connection be finished? No. The application must own and join workers and manage hijacked connections separately, within an explicit shutdown budget. Describe the state before the operation, its owner, the failure between steps and the evidence you would test. Distinguish what this example demonstrates from the infrastructure a production service still needs.","title":"Explain it in an interview"}],"takeaway":"Configure native server timeouts and distinguish HTTP drain from worker completion. No. The application must own and join workers and manage hijacked connections separately, within an explicit shutdown budget.","title":"Gin in production: the http.Server owns budgets and shutdown","unitID":"gin","wrongAnswers":["Shutdown guarantees all background jobs finished","One timeout value fits every streaming protocol"]},{"conceptTag":"gin.first-service","designGuide":{"cautions":["r.Run starts a server with no timeouts; prefer an explicit http.Server.","Set gin.TestMode before building the engine to keep test output clean."],"cost":"One constructor function and a test table; nothing beyond what a single-route service already needs.","family":"gin","flow":["Build engine","Register routes","Test via ServeHTTP","Host in http.Server"],"ratings":[],"strengths":["Routing is testable in milliseconds without sockets.","The middleware chain is explicit from the first line."]},"hint":"Look at which method the test loop calls on the router.","id":"gin.first-service","introduction":"Gin is a router, a request context and a middleware chain built on top of net/http. A *gin.Engine is an ordinary http.Handler, so everything you know about http.Server, httptest and timeouts still applies. Start with a function that returns a configured engine: main can serve it, and a test can call it directly.","nuance":"The engine implements ServeHTTP, so httptest.NewRecorder can capture its response exactly as http.Server would deliver it to a client.","objective":"Build a Gin engine, register routes with a path parameter and exercise them without opening a port.","question":"Why can a Gin router be tested without opening a network port?","references":["https://gin-gonic.com/en/docs/quickstart/","https://pkg.go.dev/github.com/gin-gonic/gin#Engine.ServeHTTP","https://pkg.go.dev/net/http/httptest#NewRecorder"],"reviewAnswer":"An http.Handler you can host or test directly","reviewPrompt":"What is a *gin.Engine?","sections":[{"body":"The standard library already parses requests, writes responses and runs servers. Gin adds a fast radix-tree router with named parameters, a *gin.Context that carries the request, the response writer and per-request values through a chain of handlers, plus helpers for binding input and rendering JSON. It does not replace http.Server: the engine is the Handler you give to one. Keeping that split in mind answers most questions about timeouts, TLS and shutdown later in the course.","title":"What Gin adds to net/http"},{"body":"A Gin service is an ordinary Go module. Create it with go mod init, add Gin at an explicit version with go get, and commit both go.mod and go.sum: the checksum file is what lets every later build prove that it downloaded the same Gin you reviewed. Pin the version deliberately and upgrade it on purpose after reading the release notes, rather than taking whatever happens to be newest on the day someone clones the repository.","code":"mkdir notes-api && cd notes-api\ngo mod init example.com/notes-api\ngo get github.com/gin-gonic/gin@v1.12.0\n# write main.go, then:\ngo run .\ncurl -i http://localhost:8080/health","language":"bash","title":"Create the module and add Gin","walkthrough":"go get records gin v1.12.0 in go.mod and the hashes of Gin and its dependencies in go.sum. go run . builds and starts the package in the current directory. The curl line answers only once main hosts the engine in an http.Server, as shown later in this lesson. Run these commands in your own development environment; the first download needs access to the Go module proxy."},{"body":"Put route registration in a function such as newRouter. It returns a fully configured *gin.Engine and has no side effects: no listening socket, no global state beyond Gin's mode. The example registers a fixed health route and a route with a :name parameter, then sends three requests through ServeHTTP and prints the status and body of each one.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc newRouter() *gin.Engine {\n\tr := gin.New()\n\tr.Use(gin.Recovery())\n\tr.GET(\"/health\", func(c *gin.Context) {\n\t\tc.JSON(http.StatusOK, gin.H{\"status\": \"ok\"})\n\t})\n\tr.GET(\"/hello/:name\", func(c *gin.Context) {\n\t\tc.String(http.StatusOK, \"hello, %s\", c.Param(\"name\"))\n\t})\n\treturn r\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := newRouter()\n\tfor _, path := range []string{\"/health\", \"/hello/gopher\", \"/missing\"} {\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))\n\t\tfmt.Println(w.Code, w.Body.String())\n\t}\n}","language":"go","title":"Build the engine and register routes","walkthrough":"gin.SetMode(gin.TestMode) runs before the engine is built, so Gin does not print its debug route table. ServeHTTP is the same method http.Server would call; httptest.NewRecorder captures the status and body. /health renders JSON, /hello/gopher binds \"gopher\" to :name, and /missing falls through to Gin's default 404 handler, which writes the plain body \"404 page not found\"."},{"body":"gin.Default() is gin.New() plus the Logger and Recovery middleware. That is convenient for a demo, but a service usually wants to choose its own access log format, fields and destination. Starting from gin.New() makes every piece of the chain visible in one place, which is also where a reviewer will look first when a request misbehaves.","code":"r := gin.New()\n// Recovery turns a handler panic into a 500 instead of killing the connection.\nr.Use(gin.Recovery())\n// Add your own structured access log here rather than relying on defaults.\nr.Use(requestLogger(logger))","language":"go","title":"gin.Default versus gin.New","walkthrough":"This fragment is the explicit form of gin.Default(). Order matters: middleware registered with Use runs for every route added after it, in registration order. requestLogger is a placeholder for the slog-based middleware built later in this course."},{"body":"r.Run(\":8080\") is a shortcut that calls http.ListenAndServe with no timeouts. A production process should construct an http.Server so that header, read, write and idle budgets are explicit and so that shutdown can drain in-flight requests. The engine stays exactly the same; only its host changes.","code":"srv := &http.Server{\n\tAddr:              \":8080\",\n\tHandler:           newRouter(),\n\tReadHeaderTimeout: 5 * time.Second,\n\tIdleTimeout:       time.Minute,\n}\nif err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {\n\tlog.Fatal(err)\n}","language":"go","title":"Serve it with an explicit http.Server","walkthrough":"Run this fragment in your own development environment, not inside the app sandbox. ReadHeaderTimeout bounds slow clients that trickle headers; IdleTimeout closes unused keep-alive connections. http.ErrServerClosed is the normal result after Shutdown, so it is not treated as a failure."},{"body":"Because the router is just a Handler, the fastest feedback loop is a table of requests sent through ServeHTTP. That catches a wrong method, a missing slash or a route conflict in milliseconds, with no port allocation and no flaky network. Keep an integration test that starts a real server too, but let the in-process tests carry the bulk of routing and handler behaviour.","title":"Test before you listen"}],"takeaway":"Return a configured *gin.Engine from a constructor, test it with httptest and ServeHTTP, and host it in an explicit http.Server rather than r.Run when it goes to production.","title":"Your first Gin service: an engine, two routes and a test request","unitID":"gin-foundations","wrongAnswers":["gin.Default disables networking in test mode","Gin ships its own server that replaces http.Server"]},{"conceptTag":"gin.path-parameters","designGuide":{"cautions":["Trailing-slash redirects are written before middleware, so access logs miss them.","Enabling UseRawPath lets parameters contain '/', which handlers must validate."],"cost":"No runtime cost beyond the radix-tree lookup; the work is deciding a slash and encoding policy and pinning it with a table test.","family":"gin","flow":["Declare route templates","Resolve conflicts at boot","Choose slash policy","Label by FullPath"],"ratings":[],"strengths":["Conflicting templates fail at registration, before any traffic.","FullPath gives a stable, bounded route label for logs and metrics."]},"hint":"Count how many distinct values the label could take across all users.","id":"gin.path-parameters","introduction":"Every Gin route is a template stored in a radix tree. The router decides which handler runs, what c.Param returns and whether the client gets a redirect instead of your handler. Most routing bugs are not in handler code: they are a trailing slash, an encoded slash or two templates that cannot share a prefix. Learn the matching rules once and those bugs become predictable.","nuance":"FullPath is the registered pattern, so /users/1 and /users/2 share one series; it is empty when no route matched, so unmatched requests need their own fixed label.","objective":"Declare Gin route templates with :param and *wildcard, predict how slashes and escapes resolve, and label metrics with c.FullPath().","question":"A metrics middleware needs a low-cardinality route label. What does c.FullPath() give it?","references":["https://pkg.go.dev/github.com/gin-gonic/gin#Context.FullPath","https://pkg.go.dev/github.com/gin-gonic/gin#Engine","https://pkg.go.dev/net/url#URL"],"reviewAnswer":"The matched route template, such as /users/:id","reviewPrompt":"What does c.FullPath() return?","sections":[{"body":"A named parameter such as :id matches exactly one non-empty path segment: it stops at the next slash and never matches an empty string. A catch-all such as *path must be the last element of the template and captures everything after its position, including the leading slash. There are no regular expressions and no types in the template, so /users/:id accepts \"42\", \"abc\" and \"-1\" alike; turning the string into a number or a UUID is the handler's job. A static segment registered next to a parameter wins when it matches exactly, which is why /users/new and /users/:id can coexist in Gin v1.12.0.","title":"A route is a template matched segment by segment"},{"body":"The program registers four templates on one engine and sends nine requests. Each handler prints the matched template and every parameter in path order, so you can see what the router decided rather than what you expected. The last request goes to a second engine with UseRawPath enabled to show why one encoded character changes the outcome.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nfunc describe(c *gin.Context) {\n\tvar b strings.Builder\n\tb.WriteString(c.FullPath())\n\tfor _, p := range c.Params {\n\t\tfmt.Fprintf(&b, \" %s=%q\", p.Key, p.Value)\n\t}\n\tc.String(http.StatusOK, b.String())\n}\n\nfunc newRouter() *gin.Engine {\n\tr := gin.New()\n\tr.GET(\"/users/:id\", describe)\n\tr.GET(\"/users/new\", describe)\n\tr.GET(\"/users/:id/posts/:slug\", describe)\n\tr.GET(\"/files/*path\", describe)\n\treturn r\n}\n\nfunc send(r *gin.Engine, path string) {\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))\n\tdetail := w.Body.String()\n\tif loc := w.Header().Get(\"Location\"); loc != \"\" {\n\t\tdetail = \"Location: \" + loc\n\t}\n\tfmt.Println(path, w.Code, detail)\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := newRouter()\n\tfor _, path := range []string{\n\t\t\"/users/42\",\n\t\t\"/users/new\",\n\t\t\"/users/42/posts/hello-gin\",\n\t\t\"/files/docs/guide.pdf\",\n\t\t\"/files/\",\n\t\t\"/users/42/\",\n\t\t\"/users/\",\n\t\t\"/users/a%2Fb\",\n\t} {\n\t\tsend(r, path)\n\t}\n\traw := newRouter()\n\traw.UseRawPath = true\n\tsend(raw, \"/users/a%2Fb\")\n}","language":"go","title":"Watch the router resolve real paths","walkthrough":"describe prints c.FullPath() and ranges over c.Params, which preserves path order. /users/new hits the static route, not :id. The catch-all keeps the leading slash, so /files/ yields path=\"/\". /users/42/ never reaches a handler: RedirectTrailingSlash answers 301 with Location /users/42. /users/ is a 404 because :id cannot be empty. /users/a%2Fb is a 404 on the default engine because Gin routes on the decoded URL.Path, where %2F has become a real slash and splits the segment. With UseRawPath the router matches the encoded form and UnescapePathValues hands the handler id=\"a/b\"."},{"body":"Two templates cannot put different wildcards at the same position, and a catch-all cannot share its level with anything else. Gin enforces this when the route is added, by panicking, so a conflicting route table never serves a single request. Treat that panic as a design signal: either the URLs describe different resources and need different prefixes, or one handler should own the position and branch on the value. Registering the same method and path twice also panics with \"handlers are already registered\".","code":"// Each pair below panics when both routes are registered on one engine.\nr.GET(\"/users/:id\", show)\nr.GET(\"/users/:name/posts\", show)\n// ':name' in new path '/users/:name/posts' conflicts with existing wildcard ':id' ...\n\nr.GET(\"/files/:id\", show)\nr.GET(\"/files/*path\", show)\n// '*path' in new path '/files/*path' conflicts with existing wildcard ':id' ...\n\nr.GET(\"/assets/*path\", show)\nr.GET(\"/assets/readme\", show)\n// '/readme' in new path '/assets/readme' conflicts with existing wildcard '/*path' ...\n\nr.GET(\"/raw/*path/meta\", show)\n// catch-all routes are only allowed at the end of the path ...","language":"go","title":"Conflicts fail at startup, which is the good news","walkthrough":"This fragment is not compiled; show stands for any handler. The messages are the start of the v1.12.0 panic text. The first pair fails because :id and :name compete for the same segment, even though the second template is longer. The second and third pairs fail because *path claims the whole remainder of /files/ or /assets/, leaving no room for :id or readme. The last line fails on its own: nothing may follow a catch-all. Because these are panics at registration, a test that only calls newRouter() catches them."},{"body":"Three engine flags decide what happens to paths that almost match. RedirectTrailingSlash is on by default: GET requests get a 301, other methods a 307 so the body and method survive, and the query string is kept. The redirect is written before the handler chain runs, so your logging and metrics middleware never see it; if a client keeps hitting /users/42/, only the proxy log will show the extra round trips. It also honors an X-Forwarded-Prefix request header, sanitized to letters, digits, '/' and '-'. RedirectFixedPath is off by default; when enabled it cleans ../ and // and does a case-insensitive lookup, so /USERS/AbC redirects to /users/AbC with the parameter's case preserved. RemoveExtraSlash cleans the path before lookup and serves it directly, without a redirect. For browser-facing pages the redirects are friendly. For a machine API, a 404 on the non-canonical path can be the better contract: it fails loudly in the client's tests instead of costing a hidden round trip on every call.","code":"r := gin.New()\n// Defaults in v1.12.0, written out so a reviewer sees the policy.\nr.RedirectTrailingSlash = true // /users/42/ -> 301 (GET) or 307 (other methods)\nr.RedirectFixedPath = false    // true: /USERS//42 -> 301 /users/42\nr.RemoveExtraSlash = false     // true: //users//42 is served as /users/42, no redirect\nr.UseRawPath = false           // true: match on URL.RawPath when Go recorded one\nr.UseEscapedPath = false       // true: match on URL.EscapedPath(); overrides UseRawPath\nr.UnescapePathValues = true    // with raw or escaped matching, decode param values","language":"go","title":"Trailing slashes, case and doubled slashes","walkthrough":"This fragment sets every flag to its v1.12.0 default so the routing policy is visible in code review. UseEscapedPath is new in v1.12.0 and takes precedence over UseRawPath. Set these fields before the engine serves traffic: they are plain struct fields read on every request without locking, so changing them later is a data race."},{"body":"Go's url.URL stores both a decoded Path and, only when the client's encoding differs from the default one, a RawPath. A path such as /users/caf%C3%A9 has no RawPath, because that is exactly how Go would encode it, so it matches /users/:id and yields \"café\" with or without UseRawPath. /users/a%2Fb does record a RawPath. If identifiers can legitimately contain a slash, enable UseRawPath (or UseEscapedPath) and keep UnescapePathValues on, then validate the decoded value: a parameter that may contain '/' or '..' must never be joined into a file path or an upstream URL. If identifiers cannot contain a slash, the default 404 is the safer behavior.","title":"Encoded slashes and raw paths"},{"body":"c.FullPath() returns the registered template, such as /users/:id, and an empty string when nothing matched. That makes it the right label for request counters and latency histograms: /users/1 and /users/2 share one series. Labeling with c.Request.URL.Path creates a new time series per user, per typo and per scanner probe, which is how a metrics backend runs out of memory. Pin the routing contract with a table test of path, expected status, expected template and expected parameters, including one trailing-slash case, one empty-segment case and one encoded-slash case.","code":"func routeLabel(c *gin.Context) string {\n\tif route := c.FullPath(); route != \"\" {\n\t\treturn route // \"/users/:id\", never \"/users/42\"\n\t}\n\treturn \"unmatched\" // 404s, 405s and trailing-slash probes share one series\n}","language":"go","title":"Label metrics with FullPath and test with a table","walkthrough":"This helper is a fragment for your own metrics middleware: call it after c.Next() so the value reflects the matched route. An empty FullPath means the router found no handler, which covers 404 and 405 responses; collapsing them into one unmatched label keeps the cardinality bounded no matter what paths clients invent."}],"takeaway":"A :param is one non-empty segment and a *wildcard is the rest of the path; Gin rejects conflicting templates at boot, answers near-misses with redirects before middleware runs, and c.FullPath() gives the low-cardinality route label.","title":"Path parameters in Gin: :param takes one segment, *wildcard takes the rest, conflicts panic at boot","unitID":"gin-foundations","wrongAnswers":["The request path after Gin decodes percent-escapes","The path plus query string, normalized to lowercase"]},{"conceptTag":"gin.query-and-forms","designGuide":{"cautions":["A '+' in a query string is a space, so +7 does not parse as an integer.","Form parse errors are swallowed by the helpers unless you call ParseForm yourself."],"cost":"A small helper per parameter type and a table test; the alternative is declarative binding, covered later, which trades visibility for brevity.","family":"gin","flow":["Name absent vs empty","Pick the matching helper","Parse with strconv","Bound and report 400"],"ratings":[],"strengths":["GetQuery and GetPostForm make absent and empty explicit.","One contract-style message per parameter stays stable across refactors."]},"hint":"Compare what GetQuery reports for ?limit= and for a request without limit.","id":"gin.query-and-forms","introduction":"Every query or form value reaches your handler as a string that may be missing, empty, repeated or malformed. Gin offers several helpers that look interchangeable but answer different questions. Choosing the wrong one turns limit=abc into limit 0, or a deliberately empty field into a default the client never asked for.","nuance":"DefaultQuery is built on GetQuery, which returns ok=true for ?limit=, so the handler receives \"\" and must decide whether empty is an error.","objective":"Read query and form values with the Gin helper that matches the case, convert them with strconv and reject bad input with a clear 400.","question":"When does c.DefaultQuery(\"limit\", \"20\") return \"20\" instead of a value from the request?","references":["https://pkg.go.dev/github.com/gin-gonic/gin#Context.GetQuery","https://pkg.go.dev/github.com/gin-gonic/gin#Context.DefaultPostForm","https://pkg.go.dev/strconv#Atoi","https://pkg.go.dev/net/http#Request.ParseForm"],"reviewAnswer":"Only when the key is absent, not when its value is empty","reviewPrompt":"When does DefaultQuery apply?","sections":[{"body":"For any key a request can be in one of four states: absent, present but empty, present and valid, or present and invalid. c.Query collapses the first two into \"\". c.GetQuery returns the value plus a boolean that is true even for ?q= and for a bare ?q. c.DefaultQuery substitutes its default only when the key is absent. The form helpers PostForm, GetPostForm and DefaultPostForm follow the same rules for the request body. Decide for each parameter what absent and empty mean, then pick the helper that can express that decision.","title":"Four states hide behind one string"},{"body":"The program implements GET /search with a required q, a bounded limit, repeatable tag values and a filter map, plus POST /notes reading a URL-encoded form. Nine requests cover the default path, three kinds of bad limit, a present-but-empty q, the full happy path, an unknown filter key and the two form cases.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// intQuery returns def when key is absent and rejects present values\n// that are not integers inside [lo, hi].\nfunc intQuery(c *gin.Context, key string, def, lo, hi int) (int, error) {\n\traw, ok := c.GetQuery(key)\n\tif !ok {\n\t\treturn def, nil\n\t}\n\tn, err := strconv.Atoi(raw)\n\tif err != nil || n < lo || n > hi {\n\t\treturn 0, fmt.Errorf(\"%s must be an integer between %d and %d\", key, lo, hi)\n\t}\n\treturn n, nil\n}\n\nvar filterKeys = map[string]bool{\"status\": true, \"owner\": true}\n\nfunc search(c *gin.Context) {\n\tq, ok := c.GetQuery(\"q\")\n\tif !ok || strings.TrimSpace(q) == \"\" {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"q is required\"})\n\t\treturn\n\t}\n\tlimit, err := intQuery(c, \"limit\", 20, 1, 100)\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\ttags := c.QueryArray(\"tag\")\n\tif len(tags) > 5 {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"at most 5 tag values\"})\n\t\treturn\n\t}\n\tfilter := c.QueryMap(\"filter\")\n\tfor k := range filter {\n\t\tif !filterKeys[k] {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"unknown filter \" + k})\n\t\t\treturn\n\t\t}\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"q\": q, \"limit\": limit, \"tags\": tags, \"filter\": filter})\n}\n\nfunc createNote(c *gin.Context) {\n\ttitle, ok := c.GetPostForm(\"title\")\n\tif !ok || title == \"\" {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"title is required\"})\n\t\treturn\n\t}\n\tpriority := c.DefaultPostForm(\"priority\", \"normal\")\n\tswitch priority {\n\tcase \"low\", \"normal\", \"high\":\n\tdefault:\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"priority must be low, normal or high\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusCreated, gin.H{\"title\": title, \"priority\": priority})\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := gin.New()\n\tr.GET(\"/search\", search)\n\tr.POST(\"/notes\", createNote)\n\n\tfor _, target := range []string{\n\t\t\"/search?q=gin\",\n\t\t\"/search?q=gin&limit=abc\",\n\t\t\"/search?q=gin&limit=500\",\n\t\t\"/search?q=gin&limit=+7\",\n\t\t\"/search?q=&tag=go\",\n\t\t\"/search?q=gin&limit=5&tag=go&tag=web&filter[status]=open\",\n\t\t\"/search?q=gin&filter[secret]=1\",\n\t} {\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil))\n\t\tfmt.Println(w.Code, w.Body.String())\n\t}\n\tfor _, form := range []string{\"title=Ship+it\", \"title=Ship+it&priority=\"} {\n\t\treq := httptest.NewRequest(http.MethodPost, \"/notes\", strings.NewReader(form))\n\t\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tfmt.Println(w.Code, w.Body.String())\n\t}\n}","language":"go","title":"A search endpoint and a form endpoint","walkthrough":"intQuery returns the default only when the key is absent; a present value must parse and fall in range, otherwise the client gets one message that states the contract. limit=+7 fails because '+' in a query string decodes to a space, so strconv.Atoi sees \" 7\". q= is present, so GetQuery reports ok and the TrimSpace check rejects it. QueryArray collects repeated tag values in order and returns nil when there are none, which JSON renders as null. QueryMap turns filter[status]=open into a map, and the loop rejects keys outside the allowlist. The last request sends priority= explicitly, so DefaultPostForm returns \"\" instead of \"normal\" and the switch rejects it."},{"body":"When a key repeats, GetQuery and Query return the first value and QueryArray returns all of them. QueryMap and PostFormMap read bracket keys such as filter[status]; the result is a Go map, so never let its iteration order reach output or logic that must be stable (encoding/json sorts map keys, which is why the program's output is deterministic). A malformed escape such as %zz is dropped by Go's query parser and Gin does not surface the error, so the key simply looks absent. Forms have a second trap: PostForm reads only the parsed body, never the query string, and Gin's form cache logs a parse failure only in debug mode. A truncated or oversized body therefore shows up as missing fields. When that difference matters, parse explicitly first.","code":"func createNote(c *gin.Context) {\n\t// Parse explicitly so a malformed or truncated body becomes a 400\n\t// instead of a field that silently looks absent.\n\tif err := c.Request.ParseForm(); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"malformed form body\"})\n\t\treturn\n\t}\n\ttitle, ok := c.GetPostForm(\"title\") // reads the parsed body only\n\t// ...\n}","language":"go","title":"Repeated, bracketed and malformed keys","walkthrough":"This fragment shows the explicit parse step. Request.ParseForm reads URL-encoded bodies and the query string and returns the first error it meets, including an invalid escape or a body cut off by http.MaxBytesReader. After it succeeds Gin's helpers reuse the parsed values, because ParseForm does not parse twice. GetPostForm still looks only at Request.PostForm, the body values."},{"body":"strconv.Atoi accepts an optional sign and leading zeros, so \"+7\", \"007\" and \"-1\" parse, while \" 5\", \"1e3\" and \"0x10\" are syntax errors and \"99999999999999999999\" fails with strconv.ErrRange. Use strconv.ParseInt(raw, 10, 32) when the value must fit an int32 column. Do not echo the Go error text to clients: it describes your implementation, not your contract. A message such as \"limit must be an integer between 1 and 100\" tells a caller exactly how to fix the request and stays stable when you refactor. Use 400 Bad Request for malformed query parameters and keep the error body shape the same across endpoints.","title":"strconv is strict; your error message should be too"},{"body":"A limit decides how many rows the database reads, how much JSON the server encodes and how long the response holds a connection, so it needs a ceiling as well as a default. An offset needs one too: OFFSET 100000 still makes most databases walk 100000 rows, which is why deep pagination usually moves to a cursor. Cap repeated values, because each tag tends to become another predicate, and allowlist map keys, because filter keys are often mapped to column names and must never be interpolated into SQL. Rejecting out-of-range values surfaces client bugs early; clamping is friendlier for interactive UIs, but if you clamp, echo the effective limit as the program does so the client can see it. Test each parameter as a table: absent, empty, non-numeric, below and above the bounds, '+' and '%2B', repeated, malformed escape and unknown map key. The binding-sources lesson later in this course shows how ShouldBindQuery with form tags and default= values expresses the same rules declaratively.","title":"Bound every parameter that sizes the work"}],"takeaway":"Use GetQuery or GetPostForm when absent and empty mean different things, parse numbers with strconv and a stated range, and give every limit-style parameter a default, a ceiling and a clear 400 message.","title":"Query strings and forms in Gin: tell absent from empty, parse numbers strictly, bound every limit","unitID":"gin-foundations","wrongAnswers":["Whenever the value is empty or fails to parse","Whenever the key is absent or its value is empty"]},{"conceptTag":"gin.route-groups","designGuide":{"cautions":["A late group.Use silently skips earlier routes and subgroups.","Group middleware never runs for 404, 405 or trailing-slash redirects."],"cost":"One table test over r.Routes() and the discipline to pass middleware to Group; nothing at request time beyond the copied chain.","family":"gin","flow":["Pass middleware to Group","Register routes after","List with r.Routes()","Probe every route"],"ratings":[],"strengths":["Prefixes and shared middleware are declared once per API area.","Versions can coexist and be retired independently by prefix."]},"hint":"Think about the moment at which a route's handler chain is assembled.","id":"gin.route-groups","introduction":"r.Group(\"/api/v1\") looks like a folder that routes live in, with middleware guarding the door. It is really a registration helper: when you add a route, Gin copies the group's prefix and handler list into that route, and the group plays no part when requests arrive. That one fact explains the most common group bug and tells you how to test for it.","nuance":"Registering a route or creating a subgroup copies the group's handlers at that moment; a later Use appends to the group's slice but cannot reach chains that were already copied.","objective":"Organize a Gin API into nested, versioned groups with scoped middleware and prove with r.Routes() that every route has the protection you intended.","question":"A team calls v1.Use(auth) after registering some v1 routes and creating v1.Group(\"/admin\"). Which routes does auth protect?","references":["https://pkg.go.dev/github.com/gin-gonic/gin#RouterGroup.Group","https://pkg.go.dev/github.com/gin-gonic/gin#Engine.Routes","https://www.rfc-editor.org/rfc/rfc8594"],"reviewAnswer":"Only for routes and subgroups created after the call","reviewPrompt":"When does group.Use take effect?","sections":[{"body":"A RouterGroup holds a base path and a slice of handlers. Group(path, middleware...) returns a new group whose handlers are a fresh copy of the parent's plus the ones you pass. Registering GET or POST on a group joins the paths and copies the group's handlers in front of your handler, and the resulting chain is stored with the route in the router tree. At request time Gin finds the route and runs that stored chain; it never asks which group the route came from. Nesting therefore composes cleanly: /api/v1/admin inherits everything /api/v1 had at the moment the admin group was created, plus its own middleware.","title":"A group is a prefix plus a copied handler list"},{"body":"The program builds a public health check, a v1 group with authentication, an admin subgroup that also requires a role, and a v2 group that changes the response shape. main then lists every route with r.Routes(), calls each one without credentials and labels it, before exercising the authenticated paths.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype user struct {\n\tID    int\n\tFirst string\n\tLast  string\n}\n\nvar users = []user{{ID: 1, First: \"Test\", Last: \"User\"}}\n\n// requireToken stands in for real authentication: it maps a bearer token to a role.\nfunc requireToken(c *gin.Context) {\n\troles := map[string]string{\"Bearer user-token\": \"user\", \"Bearer admin-token\": \"admin\"}\n\trole, ok := roles[c.GetHeader(\"Authorization\")]\n\tif !ok {\n\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\"error\": \"unauthenticated\"})\n\t\treturn\n\t}\n\tc.Set(\"role\", role)\n}\n\nfunc requireRole(want string) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tif c.GetString(\"role\") != want {\n\t\t\tc.AbortWithStatusJSON(http.StatusForbidden, gin.H{\"error\": \"forbidden\"})\n\t\t\treturn\n\t\t}\n\t}\n}\n\nfunc health(c *gin.Context) { c.JSON(http.StatusOK, gin.H{\"status\": \"ok\"}) }\n\nfunc listUsersV1(c *gin.Context) {\n\tout := []gin.H{}\n\tfor _, u := range users {\n\t\tout = append(out, gin.H{\"id\": u.ID, \"name\": u.First + \" \" + u.Last})\n\t}\n\tc.JSON(http.StatusOK, out)\n}\n\nfunc listUsersV2(c *gin.Context) {\n\tout := []gin.H{}\n\tfor _, u := range users {\n\t\tout = append(out, gin.H{\"id\": u.ID, \"first_name\": u.First, \"last_name\": u.Last})\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"data\": out, \"next_cursor\": nil})\n}\n\nfunc getUserV1(c *gin.Context) { c.JSON(http.StatusOK, gin.H{\"id\": c.Param(\"id\")}) }\n\nfunc adminStats(c *gin.Context) { c.JSON(http.StatusOK, gin.H{\"users\": len(users)}) }\n\nfunc newRouter() *gin.Engine {\n\tr := gin.New()\n\tr.GET(\"/health\", health)\n\n\tapi := r.Group(\"/api\")\n\tv1 := api.Group(\"/v1\", requireToken)\n\tv1.GET(\"/users\", listUsersV1)\n\tv1.GET(\"/users/:id\", getUserV1)\n\tadmin := v1.Group(\"/admin\", requireRole(\"admin\"))\n\tadmin.GET(\"/stats\", adminStats)\n\n\tv2 := api.Group(\"/v2\", requireToken)\n\tv2.GET(\"/users\", listUsersV2)\n\treturn r\n}\n\nfunc call(r *gin.Engine, method, path, token string) *httptest.ResponseRecorder {\n\treq := httptest.NewRequest(method, path, nil)\n\tif token != \"\" {\n\t\treq.Header.Set(\"Authorization\", \"Bearer \"+token)\n\t}\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, req)\n\treturn w\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := newRouter()\n\n\troutes := r.Routes()\n\tsort.Slice(routes, func(i, j int) bool { return routes[i].Path < routes[j].Path })\n\tpublic := map[string]bool{\"/health\": true}\n\tfor _, rt := range routes {\n\t\tpath := strings.ReplaceAll(rt.Path, \":id\", \"1\")\n\t\tcode := call(r, rt.Method, path, \"\").Code\n\t\tverdict := \"protected\"\n\t\tif code != http.StatusUnauthorized {\n\t\t\tverdict = \"open\"\n\t\t\tif !public[rt.Path] {\n\t\t\t\tverdict = \"OPEN BY MISTAKE\"\n\t\t\t}\n\t\t}\n\t\tfmt.Println(rt.Method, rt.Path, rt.Handler, code, verdict)\n\t}\n\n\tfmt.Println(\"v1\", call(r, http.MethodGet, \"/api/v1/users\", \"user-token\").Body.String())\n\tfmt.Println(\"v2\", call(r, http.MethodGet, \"/api/v2/users\", \"user-token\").Body.String())\n\tfmt.Println(\"admin as user\", call(r, http.MethodGet, \"/api/v1/admin/stats\", \"user-token\").Code)\n\tfmt.Println(\"admin as admin\", call(r, http.MethodGet, \"/api/v1/admin/stats\", \"admin-token\").Body.String())\n}","language":"go","title":"Two versions, an admin subgroup and a route-table test","walkthrough":"Middleware is passed to Group itself, so it is in place before any route is added. requireToken stores the role with c.Set; requireRole reads it, so the admin chain is requireToken, requireRole(\"admin\"), adminStats in that order. r.Routes() returns method, path and the name of the final handler; the order is not documented, so the program sorts it. Each route is called with its :id replaced by 1 and no Authorization header. Anything that does not answer 401 must be on the public allowlist, or it prints OPEN BY MISTAKE. v1 and v2 share the users slice but render different JSON, and the user token gets 403 from the admin subgroup while the admin token succeeds."},{"body":"group.Use appends to that group's slice. Routes registered earlier already hold their own copy of the chain, and subgroups created earlier hold theirs, so neither gains the new middleware. The failure is silent: the code reads as if the whole /v1 tree is authenticated, the server starts, and the earlier routes answer anyone. Passing middleware as arguments to Group, as the program does, makes the order impossible to get wrong. If you must call Use, call it on the line right after creating the group and before any route or subgroup.","code":"api := r.Group(\"/api\")\nv1 := api.Group(\"/v1\")\nv1.GET(\"/export\", exportAll)    // chain copied now: no auth\nadmin := v1.Group(\"/admin\")     // chain copied now: no auth\nv1.Use(requireToken)            // appends to v1's own slice only\nv1.GET(\"/users\", listUsersV1)   // protected\nadmin.GET(\"/stats\", adminStats) // NOT protected","language":"go","title":"Use after registration protects nothing that came before","walkthrough":"This fragment shows the bug, not a pattern to copy. /api/v1/export and /api/v1/admin/stats were wired from v1's chain before requireToken was appended, so both serve unauthenticated requests; only /api/v1/users is protected. The route-table test from the program would print OPEN BY MISTAKE for both, which is why that test exists."},{"body":"A v2 group is the place for breaking changes to the HTTP contract: renamed fields, a pagination envelope, stricter validation. Keep both versions as thin adapters over the same application service so a bug fix lands once, and let each group own only its request parsing and response shape. Retire v1 deliberately: label metrics by c.FullPath() so you can see which v1 routes still get traffic, announce the end date with a Sunset response header (RFC 8594) set by a middleware on the v1 group, and delete the group only when its traffic is gone. Versioning by path prefix is the simplest scheme to route, cache and log; header-based versioning is possible but every proxy, cache key and log query then has to know about the header.","title":"Versions side by side, one core underneath"},{"body":"Group middleware runs only for routes registered through that group. A request for /api/v1/typo matches no route, so Gin answers with its 404 chain, which contains only engine-level middleware from r.Use; the same is true for 405 responses, and trailing-slash redirects run no middleware at all. An unauthenticated client therefore gets 404 for unknown paths and 401 for real ones, which is normal but worth knowing when you reason about route enumeration. r.Routes() reports only the last handler of each chain, so you cannot inspect middleware statically; test behavior instead, as the program does. Give handlers names: a named function shows as main.listUsersV1, while an anonymous one appears as something like main.main.func3, which makes a route-table diff useless in review. Run the route-table test in CI so a newly added route without the expected protection fails the build.","title":"What a group cannot see, and what to test"}],"takeaway":"Pass middleware to Group before registering routes, keep versions as thin adapters over one core, and assert the protection of every entry in r.Routes() with requests rather than trusting how the code reads.","title":"Gin route groups: prefixes and middleware are copied at registration, so test the route table","unitID":"gin-foundations","wrongAnswers":["Every route under /v1, because groups are resolved per request","Every route registered on v1, but none of its subgroups"]},{"conceptTag":"gin.json-responses","designGuide":{"cautions":["Marshal errors and repeated renders leave the first status in place.","AsciiJSON mis-encodes characters above U+FFFF."],"cost":"One DTO type and mapping function per resource, plus contract tests; mapping is cheap compared with an accidental data leak.","family":"gin","flow":["Map model to DTO","Tag omit rules per field","Pick renderer by bytes","Assert status and body"],"ratings":[],"strengths":["A DTO makes every published field a reviewed decision.","c.JSON output is HTML-safe and has a stable Content-Type."]},"hint":"Check which kinds of values omitempty treats as empty.","id":"gin.json-responses","introduction":"The bytes a handler writes are a public contract: field names, which fields exist, how characters are escaped, the Content-Type and the status. Gin has five JSON renderers that look interchangeable and are not, and c.JSON will happily publish every field of whatever struct you hand it, including the ones you add next year.","nuance":"omitempty checks false, 0, nil and zero length, and a struct is none of those, so the zero time renders as 0001-01-01T00:00:00Z; omitzero consults the IsZero method instead.","objective":"Choose between c.JSON, PureJSON, IndentedJSON, SecureJSON and AsciiJSON by their exact output, set status codes deliberately and render a response DTO with correct omitempty and omitzero tags.","question":"A DTO field is CreatedAt time.Time `json:\"created_at,omitempty\"` and the value is zero. What does encoding/json do?","references":["https://pkg.go.dev/github.com/gin-gonic/gin#Context.JSON","https://pkg.go.dev/github.com/gin-gonic/gin/render#SecureJSON","https://pkg.go.dev/encoding/json#Marshal"],"reviewAnswer":"It is still encoded; omitzero drops it via IsZero","reviewPrompt":"omitempty on a zero time.Time?","sections":[{"body":"All of Gin's JSON renderers start from the configured codec, which is encoding/json unless the binary is built with the jsoniter, go_json or sonic tags. encoding/json exports every exported field, using the Go field name when there is no tag. Rendering a storage struct therefore couples the API to the schema: renaming a column renames a JSON key, and adding a field such as PasswordHash or an internal flag publishes it immediately. A separate response type, a DTO, is the boundary where you decide what leaves the process.","title":"Rendering is where internal state leaks"},{"body":"The program renders the same small value with each JSON renderer, then contrasts a storage struct with its DTO, and finishes with two cases where Gin drops the body. Newlines in bodies are printed as \\n so you can see exactly where each renderer adds one.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// account is the storage model. It is never rendered directly.\ntype account struct {\n\tID           int64\n\tEmail        string\n\tPasswordHash string\n\tCreatedAt    time.Time\n\tUpdatedAt    time.Time\n\tDeletedAt    time.Time\n}\n\n// accountResponse is the public contract for GET /accounts/:id.\ntype accountResponse struct {\n\tID        int64     `json:\"id\"`\n\tEmail     string    `json:\"email\"`\n\tCreatedAt time.Time `json:\"created_at\"`\n\tUpdatedAt time.Time `json:\"updated_at,omitempty\"` // omitempty never omits a struct\n\tDeletedAt time.Time `json:\"deleted_at,omitzero\"`  // omitzero uses time.Time.IsZero\n}\n\nfunc toResponse(a account) accountResponse {\n\treturn accountResponse{ID: a.ID, Email: a.Email, CreatedAt: a.CreatedAt, UpdatedAt: a.UpdatedAt, DeletedAt: a.DeletedAt}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tacct := account{\n\t\tID:           7,\n\t\tEmail:        \"dev@example.com\",\n\t\tPasswordHash: \"$2a$10$not-a-real-hash\",\n\t\tCreatedAt:    time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC),\n\t}\n\ttext := gin.H{\"note\": \"<b>R&D</b> café\"}\n\n\tvar lastErr string\n\tr := gin.New()\n\tr.Use(func(c *gin.Context) {\n\t\tc.Next()\n\t\tif len(c.Errors) > 0 {\n\t\t\tlastErr = c.Errors.Last().Error()\n\t\t}\n\t})\n\tr.GET(\"/json\", func(c *gin.Context) { c.JSON(http.StatusOK, text) })\n\tr.GET(\"/pure\", func(c *gin.Context) { c.PureJSON(http.StatusOK, text) })\n\tr.GET(\"/ascii\", func(c *gin.Context) { c.AsciiJSON(http.StatusOK, text) })\n\tr.GET(\"/indented\", func(c *gin.Context) { c.IndentedJSON(http.StatusOK, gin.H{\"ok\": true}) })\n\tr.GET(\"/secure-list\", func(c *gin.Context) { c.SecureJSON(http.StatusOK, []int{1, 2}) })\n\tr.GET(\"/secure-object\", func(c *gin.Context) { c.SecureJSON(http.StatusOK, gin.H{\"ok\": true}) })\n\tr.GET(\"/leaky\", func(c *gin.Context) { c.JSON(http.StatusOK, acct) })\n\tr.GET(\"/accounts/7\", func(c *gin.Context) { c.JSON(http.StatusOK, toResponse(acct)) })\n\tr.GET(\"/no-content\", func(c *gin.Context) { c.JSON(http.StatusNoContent, gin.H{\"dropped\": true}) })\n\tr.GET(\"/nan\", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{\"ratio\": math.NaN()}) })\n\n\tfor _, path := range []string{\n\t\t\"/json\", \"/pure\", \"/ascii\", \"/indented\", \"/secure-list\", \"/secure-object\",\n\t\t\"/leaky\", \"/accounts/7\", \"/no-content\", \"/nan\",\n\t} {\n\t\tlastErr = \"\"\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))\n\t\tbody := strings.ReplaceAll(w.Body.String(), \"\\n\", `\\n`)\n\t\tif body == \"\" {\n\t\t\tbody = \"(empty body)\"\n\t\t}\n\t\tfmt.Printf(\"%s %d [%s] %s\\n\", path, w.Code, w.Header().Get(\"Content-Type\"), body)\n\t\tif lastErr != \"\" {\n\t\t\tfmt.Println(\"  c.Errors:\", lastErr)\n\t\t}\n\t}\n}","language":"go","title":"Ten responses side by side","walkthrough":"c.JSON escapes <, > and & as \\u003c, \\u003e and \\u0026 and leaves the UTF-8 é alone. PureJSON writes the characters literally and ends with \\n, because it uses a json.Encoder. AsciiJSON also rewrites é as \\u00e9 and sends Content-Type application/json without a charset. IndentedJSON uses four spaces. SecureJSON prefixes while(1); only to the array. /leaky shows Go field names and the password hash; the DTO uses snake_case tags, drops the hash, keeps the zero updated_at because omitempty never omits a struct, and drops deleted_at because omitzero asks time.Time.IsZero. The 204 body is discarded. The NaN cannot be marshaled, so Gin records the error in c.Errors, writes nothing, and the client receives 200 with an empty body."},{"body":"Use c.JSON by default: its HTML escaping makes the output safe to embed in a page and it adds no trailing newline. PureJSON is for clients that need literal characters, such as a payload that is signed or compared byte for byte; never embed its output in HTML. IndentedJSON costs bytes and CPU on every request, so keep it for debugging endpoints. SecureJSON defends against JSON hijacking in very old browsers by prefixing top-level arrays (the check is literally output that starts with [ and ends with ]); r.SecureJsonPrefix changes the prefix, and note that the method's doc comment says while(1), while the v1.12.0 default is while(1);. Returning an object at the top level avoids the issue and leaves room for pagination fields. AsciiJSON rewrites each non-ASCII rune with the format \\u%04x, so characters above U+FFFF, which includes most emoji, come out as \\u plus five hex digits, which a JSON parser reads as a different character followed by a digit. Do not use it for user-generated text.","title":"Choose a renderer by its exact bytes"},{"body":"c.Status(code) records the status; with no body written, the response goes out empty when the chain finishes. For 1xx, 204 and 304, c.JSON writes the Content-Type header but discards the body, so c.Status(http.StatusNoContent) states the intent more honestly. c.Data(code, contentType, bytes) sends pre-encoded bytes and, since v1.12.0, sets Content-Length. In middleware, c.AbortWithStatusJSON stops the chain and answers in one call. Two failures are silent. A marshal error, from NaN, an infinity, a channel or a cycle, leaves a 200 with an empty body plus an entry in c.Errors, so an error middleware must check c.Errors as the errors-testing lesson does. A second render after the first one has written appends its body to the first and cannot change the status, so one function must own the response.","title":"Status codes and the bodies Gin drops"},{"body":"omitempty omits false, 0, \"\", nil pointers and interfaces, and slices, maps or strings of length zero; it never omits a struct, so a zero time.Time renders as 0001-01-01T00:00:00Z. omitzero, added in Go 1.24, omits a field when its type's IsZero method returns true or, without such a method, when the value is the zero value. That makes it right for time.Time and for value structs, but a non-nil empty slice is not a zero value, so omitzero keeps [] where omitempty drops it. With both options the field is omitted if either rule applies. Decide per field whether clients should see absent, null, zero or empty, and write that down in the tag.","code":"type page struct {\n\tItems      []item    `json:\"items\"`                 // nil renders null: initialize to []item{}\n\tNextCursor string    `json:\"next_cursor,omitempty\"` // omitted on the last page\n\tTotal      int       `json:\"total,omitzero\"`        // omitted when 0: is 0 a real answer?\n\tGenerated  time.Time `json:\"generated_at,omitzero\"` // omitted when IsZero reports true\n}","language":"go","title":"omitempty versus omitzero in a DTO","walkthrough":"This fragment annotates a pagination DTO. A nil Items slice encodes as null, which many clients mishandle, so initialize it to an empty slice. NextCursor disappears on the last page. Total with omitzero disappears when it is 0, which is wrong if zero is a meaningful count, so think before tagging numbers. Generated relies on time.Time.IsZero, which is exactly what omitzero consults."},{"body":"For each endpoint assert the status, the Content-Type and the body. Decode the body into map[string]any and assert that sensitive keys such as password_hash are absent, because a struct-to-struct comparison cannot notice an extra field. Keep a golden file per DTO for contract review, and add one test that marshals every DTO with representative values, including floats from calculations, so a NaN fails in CI rather than as an empty 200 in production. If the JSON codec is swapped with build tags, run the same tests under that build.","title":"Test the bytes, not just the status"}],"takeaway":"Render DTOs with explicit tags, use c.JSON unless a renderer's exact bytes are required, and remember that a marshal error or a second render does not change the status already chosen.","title":"Gin JSON responses: know what each renderer writes and return a DTO, never your storage model","unitID":"gin-foundations","wrongAnswers":["It omits the field because the time is the zero value","It encodes null because zero times are treated as nil"]},{"conceptTag":"gin.binding-sources","designGuide":{"cautions":["ShouldBind falls back to form binding for unknown content types.","ShouldBindBodyWith buffers the whole body; cap its size first."],"cost":"A few small structs per endpoint and one extra in-memory copy of the body when it must be decoded twice.","family":"gin","flow":["One struct per source","Bind path, query, headers","Bind the body last","Cache body to read twice"],"ratings":[],"strengths":["Each error names the source that was wrong.","default= options keep simple query defaults declarative."]},"hint":"Look at what binding.Uri does right after it maps the path parameters.","id":"gin.binding-sources","introduction":"A single request carries input in four places: path parameters, the query string, headers and the body. Gin has a binder and a struct tag for each, and they compose well as long as you respect two rules the API does not advertise. Every binder validates the entire struct it fills, and a request body can be read only once unless you ask Gin to keep a copy.","nuance":"BindUri maps only uri tags and then runs the validator on the entire struct, so the still-empty Title fails required before ShouldBindJSON has had a chance to fill it.","objective":"Bind each request source with its own Gin binder and tag, predict what content-type-driven ShouldBind reads, and decode one body twice with ShouldBindBodyWithJSON.","question":"A struct has a uri-tagged ID and a json-tagged Title, both binding:\"required\". Why does ShouldBindUri fail on a valid request?","references":["https://pkg.go.dev/github.com/gin-gonic/gin#Context.ShouldBindUri","https://pkg.go.dev/github.com/gin-gonic/gin#Context.ShouldBindBodyWith","https://pkg.go.dev/github.com/gin-gonic/gin/binding#Default"],"reviewAnswer":"Each binder validates the whole struct, not its own tags","reviewPrompt":"Why one struct per binding source?","sections":[{"body":"ShouldBindUri fills fields tagged uri from c.Params. ShouldBindQuery fills form-tagged fields from the URL query only. ShouldBindHeader fills header-tagged fields, canonicalizing the tag with textproto.CanonicalMIMEHeaderKey, so header:\"x-request-id\" works. ShouldBindJSON decodes the body into json-tagged fields. After mapping, every binder runs the validator, which reads the binding tag. The Should variants return the error and leave the response to you; the Bind variants abort with a bare 400 and, in v1.12.0, no body at all, which is rarely the error contract an API wants. A form tag can carry a default, as in form:\"limit,default=20\", which applies only when the key is absent.","title":"Four sources, four tags, one binder each"},{"body":"The program defines one small struct per source and wires them into five handlers: a list endpoint with path, query and header input, a PATCH that needs an If-Match header, a create endpoint that accepts JSON or a form through ShouldBind, and two webhook handlers that read the same body twice, one correctly and one naively.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// One small struct per source: each binder validates the whole struct it fills.\ntype projectURI struct {\n\tProject string `uri:\"project\" binding:\"required,alphanum,max=32\"`\n}\n\ntype listQuery struct {\n\tLimit int    `form:\"limit,default=20\" binding:\"min=1,max=100\"`\n\tSort  string `form:\"sort,default=created\" binding:\"oneof=created title\"`\n}\n\ntype traceHeader struct {\n\tRequestID string `header:\"X-Request-Id\"`\n}\n\ntype noteURI struct {\n\tID int64 `uri:\"id\" binding:\"required,min=1\"`\n}\n\ntype patchHeader struct {\n\tIfMatch string `header:\"If-Match\" binding:\"required\"`\n}\n\ntype patchBody struct {\n\tTitle string `json:\"title\" binding:\"required,max=80\"`\n}\n\ntype createNote struct {\n\tTitle string `json:\"title\" form:\"title\" binding:\"required,max=80\"`\n}\n\ntype envelope struct {\n\tType string `json:\"type\" binding:\"required\"`\n}\n\ntype noteCreated struct {\n\tData struct {\n\t\tID    int64  `json:\"id\" binding:\"required\"`\n\t\tTitle string `json:\"title\" binding:\"required\"`\n\t} `json:\"data\"`\n}\n\nfunc bad(c *gin.Context, source string) {\n\tc.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\"error\": \"invalid \" + source})\n}\n\nfunc listNotes(c *gin.Context) {\n\tvar uri projectURI\n\tvar q listQuery\n\tvar h traceHeader\n\tif c.ShouldBindUri(&uri) != nil {\n\t\tbad(c, \"path\")\n\t\treturn\n\t}\n\tif c.ShouldBindQuery(&q) != nil {\n\t\tbad(c, \"query\")\n\t\treturn\n\t}\n\tif c.ShouldBindHeader(&h) != nil {\n\t\tbad(c, \"headers\")\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"project\": uri.Project, \"limit\": q.Limit, \"sort\": q.Sort, \"request_id\": h.RequestID})\n}\n\nfunc patchNote(c *gin.Context) {\n\tvar uri noteURI\n\tvar h patchHeader\n\tvar body patchBody\n\tif c.ShouldBindUri(&uri) != nil {\n\t\tbad(c, \"path\")\n\t\treturn\n\t}\n\tif c.ShouldBindHeader(&h) != nil {\n\t\tbad(c, \"headers\")\n\t\treturn\n\t}\n\tif c.ShouldBindJSON(&body) != nil {\n\t\tbad(c, \"body\")\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, gin.H{\"id\": uri.ID, \"if_match\": h.IfMatch, \"title\": body.Title})\n}\n\nfunc postNote(c *gin.Context) {\n\tvar in createNote\n\tif err := c.ShouldBind(&in); err != nil {\n\t\tbad(c, \"body\")\n\t\treturn\n\t}\n\tc.JSON(http.StatusCreated, gin.H{\"title\": in.Title, \"via\": c.ContentType()})\n}\n\nfunc webhook(c *gin.Context) {\n\tvar env envelope\n\tif c.ShouldBindBodyWithJSON(&env) != nil {\n\t\tbad(c, \"envelope\")\n\t\treturn\n\t}\n\tswitch env.Type {\n\tcase \"note.created\":\n\t\tvar ev noteCreated\n\t\tif c.ShouldBindBodyWithJSON(&ev) != nil {\n\t\t\tbad(c, \"note.created payload\")\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusAccepted, gin.H{\"handled\": env.Type, \"id\": ev.Data.ID})\n\tdefault:\n\t\tc.JSON(http.StatusAccepted, gin.H{\"ignored\": env.Type})\n\t}\n}\n\nfunc webhookNaive(c *gin.Context) {\n\tvar env envelope\n\tvar ev noteCreated\n\t_ = c.ShouldBindJSON(&env)\n\tif err := c.ShouldBindJSON(&ev); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"second_read\": err.Error()})\n\t\treturn\n\t}\n\tc.Status(http.StatusAccepted)\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := gin.New()\n\tr.GET(\"/projects/:project/notes\", listNotes)\n\tr.PATCH(\"/notes/:id\", patchNote)\n\tr.POST(\"/notes\", postNote)\n\tr.POST(\"/webhooks\", webhook)\n\tr.POST(\"/webhooks-naive\", webhookNaive)\n\n\tconst event = `{\"type\":\"note.created\",\"data\":{\"id\":9,\"title\":\"Hi\"}}`\n\tcases := []struct {\n\t\tmethod, target, contentType, body string\n\t\theaders                           map[string]string\n\t}{\n\t\t{\"GET\", \"/projects/core/notes\", \"\", \"\", nil},\n\t\t{\"GET\", \"/projects/core/notes?limit=0\", \"\", \"\", nil},\n\t\t{\"GET\", \"/projects/core/notes?limit=5&sort=title\", \"\", \"\", map[string]string{\"X-Request-Id\": \"r-42\"}},\n\t\t{\"GET\", \"/projects/core.v2/notes\", \"\", \"\", nil},\n\t\t{\"PATCH\", \"/notes/abc\", \"application/json\", `{\"title\":\"Renamed\"}`, nil},\n\t\t{\"PATCH\", \"/notes/7\", \"application/json\", `{\"title\":\"Renamed\"}`, nil},\n\t\t{\"PATCH\", \"/notes/7\", \"application/json\", `{\"title\":\"Renamed\"}`, map[string]string{\"If-Match\": `\"v3\"`}},\n\t\t{\"POST\", \"/notes\", \"application/json\", `{\"title\":\"From JSON\"}`, nil},\n\t\t{\"POST\", \"/notes\", \"application/x-www-form-urlencoded\", \"title=From+a+form\", nil},\n\t\t{\"POST\", \"/webhooks\", \"application/json\", event, nil},\n\t\t{\"POST\", \"/webhooks-naive\", \"application/json\", event, nil},\n\t}\n\tfor _, tc := range cases {\n\t\treq := httptest.NewRequest(tc.method, tc.target, strings.NewReader(tc.body))\n\t\tif tc.contentType != \"\" {\n\t\t\treq.Header.Set(\"Content-Type\", tc.contentType)\n\t\t}\n\t\tfor k, v := range tc.headers {\n\t\t\treq.Header.Set(k, v)\n\t\t}\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tfmt.Println(tc.method, tc.target, w.Code, w.Body.String())\n\t}\n}","language":"go","title":"Path, query, headers, body and a webhook","walkthrough":"The first request gets limit 20 and sort created from the default= options. limit=0 is present, so the default does not apply and min=1 rejects it. core.v2 fails alphanum in the path. /notes/abc fails before validation because strconv cannot parse an int64. The PATCH without If-Match fails header validation, and the one with it echoes the quoted entity tag. ShouldBind picks the JSON or form binder from Content-Type, so both create requests succeed. /webhooks decodes the envelope, switches on its type, then decodes the full payload from the cached bytes. /webhooks-naive calls ShouldBindJSON twice; the first call drained the body, so the second sees EOF."},{"body":"It is tempting to describe a whole request in one struct with uri, json and header tags side by side. Each binder maps only its own tag, but binding.Uri, binding.Query, binding.Header and the body binders all validate the complete struct afterwards. A required body field is therefore still empty when ShouldBindUri runs, and the call fails on a perfectly valid request. Separate structs per source avoid the problem and also make the error message honest: you know which source was wrong. If you insist on one struct, the only arrangement that works is to put binding rules solely on the fields filled by the binder you call last, which quietly gives up validation for every other source.","code":"// Looks tidy, fails on every request.\ntype patchNoteRequest struct {\n\tID    int64  `uri:\"id\" binding:\"required,min=1\"`\n\tTitle string `json:\"title\" binding:\"required,max=80\"`\n}\n\nvar in patchNoteRequest\nerr := c.ShouldBindUri(&in)\n// Key: 'patchNoteRequest.Title' Error:Field validation for 'Title'\n// failed on the 'required' tag","language":"go","title":"Why one struct per source","walkthrough":"This fragment is the anti-pattern, with the v1.12.0 error text as a comment. ShouldBindUri sets ID correctly, then validation reaches Title, which is empty because the JSON body has not been decoded yet, and required fails. Swapping the call order only moves the failure: ShouldBindJSON would then complain about ID."},{"body":"ShouldBind asks binding.Default(method, contentType) for a binder. For GET it always returns the form binder, so a JSON body on a GET is ignored and only the query string is read. For other methods the media type, with parameters such as charset stripped, selects JSON, XML, YAML, TOML, protobuf, MessagePack, BSON or multipart. Anything else, including a missing Content-Type or text/plain, falls back to the form binder, which reads Request.Form: the URL-encoded body merged with the query string, body values first. A client can therefore supply a field through the query string of a POST. If an endpoint accepts only JSON, call ShouldBindJSON and answer 415 for other content types instead of letting the fallback guess.","title":"Content-Type decides what ShouldBind reads"},{"body":"Request.Body is a stream; once a decoder has consumed it, the next read returns EOF. ShouldBindBodyWith(obj, binding.JSON), or the shortcut ShouldBindBodyWithJSON, reads the whole body with io.ReadAll on first use, stores the bytes in c.Keys under gin.BodyBytesKey and decodes from that copy on every later call. That is what an envelope-then-payload webhook needs. It only works with body binders such as JSON, XML, YAML, TOML and Plain, not with the form binder, and once one call has cached the body every other read in that request must use the BodyWith variants too. Because the whole body is buffered in memory, put http.MaxBytesReader in front of it as described in the binding-limits lesson; that lesson also covers when to reject unknown fields.","title":"Reading the body twice without losing it"},{"body":"Write table cases per source rather than per endpoint: a path value of the wrong type, a query key that is absent versus present with a zero value, a header in unusual case, a body with no Content-Type, an empty body, and a second read of the same body. Assert both the status and which source the error names, because a test that only checks for 400 cannot tell a header mistake from a body mistake. The next lesson turns validator errors into a stable field-level JSON response.","title":"Test each source on its own"}],"takeaway":"Give each request source its own struct and binder, call ShouldBindJSON when only JSON is acceptable, and use ShouldBindBodyWithJSON behind a size limit when one body must be decoded twice.","title":"Gin binding sources: bind path, query, headers and body separately, and cache the body to read it twice","unitID":"gin-foundations","wrongAnswers":["ShouldBindUri also reads the JSON body and finds it empty","Gin forbids mixing uri and json tags in one struct"]},{"conceptTag":"gin.custom-validators","designGuide":{"cautions":["Register methods are not thread-safe; finish them before serving.","Without dive, struct elements of a slice are never validated."],"cost":"One setup function, one error mapper shared by all handlers and a table test per rule; registration is global, so tag names need care.","family":"gin","flow":["Register tags at startup","Report JSON field names","dive into collections","Map errors to field JSON"],"ratings":[],"strengths":["Domain rules live next to the DTO and run for every binder.","Field, rule and param objects stay stable across refactors."]},"hint":"Remove dive from the program's Items tag and send the invalid SKU again.","id":"gin.custom-validators","introduction":"Gin's binding tags cover shape: required, lengths, ranges, enumerations. Real input also has domain rules, such as a SKU format or an address that is required unless the customer picks the order up. Gin's validator accepts both kinds, but the default error text names Go structs and fields, which makes a poor API. This lesson adds the rules and a response format you can keep stable.","nuance":"Without dive the validator checks only the slice itself, such as required and min; dive tells it to descend into every element, applying the tags after dive and each struct element's own tags.","objective":"Register a custom tag and a struct-level rule on Gin's validator, validate slice elements with dive and convert validator errors into a stable field-level JSON response.","question":"Items []line has binding:\"required,min=1\" and every line struct has its own binding tags. What does adding dive change?","references":["https://pkg.go.dev/github.com/go-playground/validator/v10#Validate.RegisterValidation","https://pkg.go.dev/github.com/go-playground/validator/v10#ValidationErrors","https://pkg.go.dev/github.com/gin-gonic/gin/binding#StructValidator"],"reviewAnswer":"It makes the validator visit and validate each element","reviewPrompt":"What does dive do in a slice tag?","sections":[{"body":"binding.Validator is a package-level StructValidator. The default implementation lazily creates a go-playground/validator v10 instance with its tag name set to binding, and Engine() returns it as any. Type-assert it to *validator.Validate and you can register custom tags, struct-level rules and a tag-name function. Because the instance is global, everything you register applies to every binder in the process: ShouldBindJSON, ShouldBindQuery, ShouldBindUri and the rest. Give custom tags specific names such as sku rather than code, so two packages cannot collide.","title":"Gin's validator is a shared go-playground instance"},{"body":"The program registers a sku tag, a struct-level rule for the address and a tag-name function, then posts five orders: a valid one, one with four separate problems, one with no items, one with a wrongly typed field and one that is not JSON at all.","code":"package main\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/gin-gonic/gin/binding\"\n\t\"github.com/go-playground/validator/v10\"\n)\n\ntype line struct {\n\tSKU string `json:\"sku\" binding:\"required,sku\"`\n\tQty int    `json:\"qty\" binding:\"min=1,max=99\"`\n}\n\ntype order struct {\n\tItems   []line   `json:\"items\" binding:\"required,min=1,max=20,dive\"`\n\tCoupons []string `json:\"coupons\" binding:\"max=3,dive,alphanum,len=8\"`\n\tPickup  bool     `json:\"pickup\"`\n\tAddress string   `json:\"address\" binding:\"max=200\"`\n}\n\nvar skuPattern = regexp.MustCompile(`^[A-Z]{3}-[0-9]{4}$`)\n\n// setupValidation runs once at startup, before the engine serves requests.\nfunc setupValidation() error {\n\tv, ok := binding.Validator.Engine().(*validator.Validate)\n\tif !ok {\n\t\treturn errors.New(\"binding.Validator is not go-playground/validator\")\n\t}\n\tv.RegisterTagNameFunc(func(f reflect.StructField) string {\n\t\tname, _, _ := strings.Cut(f.Tag.Get(\"json\"), \",\")\n\t\tif name == \"-\" {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn name\n\t})\n\tif err := v.RegisterValidation(\"sku\", func(fl validator.FieldLevel) bool {\n\t\treturn skuPattern.MatchString(fl.Field().String())\n\t}); err != nil {\n\t\treturn err\n\t}\n\tv.RegisterStructValidation(func(sl validator.StructLevel) {\n\t\to := sl.Current().Interface().(order)\n\t\tif !o.Pickup && strings.TrimSpace(o.Address) == \"\" {\n\t\t\tsl.ReportError(o.Address, \"address\", \"Address\", \"required_unless_pickup\", \"\")\n\t\t}\n\t}, order{})\n\treturn nil\n}\n\ntype fieldError struct {\n\tField string `json:\"field\"`\n\tRule  string `json:\"rule\"`\n\tParam string `json:\"param,omitempty\"`\n}\n\n// wirePath turns \"items.0.qty\" from encoding/json into \"items[0].qty\".\nfunc wirePath(field string) string {\n\tvar b strings.Builder\n\tfor i, part := range strings.Split(field, \".\") {\n\t\tif _, err := strconv.Atoi(part); err == nil {\n\t\t\tb.WriteString(\"[\" + part + \"]\")\n\t\t\tcontinue\n\t\t}\n\t\tif i > 0 {\n\t\t\tb.WriteByte('.')\n\t\t}\n\t\tb.WriteString(part)\n\t}\n\treturn b.String()\n}\n\nfunc writeBindError(c *gin.Context, err error) {\n\tvar invalid validator.ValidationErrors\n\tvar typeErr *json.UnmarshalTypeError\n\tswitch {\n\tcase errors.As(err, &invalid):\n\t\tout := make([]fieldError, 0, len(invalid))\n\t\tfor _, fe := range invalid {\n\t\t\t_, path, _ := strings.Cut(fe.Namespace(), \".\")\n\t\t\tout = append(out, fieldError{Field: path, Rule: fe.Tag(), Param: fe.Param()})\n\t\t}\n\t\tc.JSON(http.StatusUnprocessableEntity, gin.H{\"errors\": out})\n\tcase errors.As(err, &typeErr):\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"errors\": []fieldError{{Field: wirePath(typeErr.Field), Rule: \"type\"}}})\n\tdefault:\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"malformed JSON body\"})\n\t}\n}\n\nfunc createOrder(c *gin.Context) {\n\tvar in order\n\tif err := c.ShouldBindJSON(&in); err != nil {\n\t\twriteBindError(c, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusCreated, gin.H{\"lines\": len(in.Items)})\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tif err := setupValidation(); err != nil {\n\t\tpanic(err)\n\t}\n\tr := gin.New()\n\tr.POST(\"/orders\", createOrder)\n\n\tfor _, body := range []string{\n\t\t`{\"items\":[{\"sku\":\"ABC-1234\",\"qty\":2}],\"pickup\":true}`,\n\t\t`{\"items\":[{\"sku\":\"ABC-1234\",\"qty\":2},{\"sku\":\"abc\",\"qty\":0}],\"coupons\":[\"SAVE2026\",\"x\"]}`,\n\t\t`{\"items\":[],\"address\":\"1 Main St\"}`,\n\t\t`{\"items\":[{\"sku\":\"ABC-1234\",\"qty\":\"2\"}],\"pickup\":true}`,\n\t\t`{\"items\":[`,\n\t} {\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, httptest.NewRequest(http.MethodPost, \"/orders\", strings.NewReader(body)))\n\t\tfmt.Println(w.Code, w.Body.String())\n\t}\n}","language":"go","title":"An order endpoint with domain rules","walkthrough":"RegisterTagNameFunc makes errors report JSON names, so Namespace() yields order.items[1].sku and the handler strips the leading type name. The sku function is an ordinary predicate over the field. The struct-level rule reports its own tag, required_unless_pickup, through ReportError. The second request produces four errors in struct order with element errors by index and the struct-level error last. {\"items\":[]} passes required, because a non-nil empty slice is not missing, and fails min=1. \"qty\":\"2\" never reaches validation: encoding/json returns an UnmarshalTypeError whose Field is items.0.qty, which wirePath rewrites as items[0].qty. A truncated body is reported as malformed JSON."},{"body":"The validator is safe for concurrent validation, but its Register methods are documented as not thread-safe: they must all run before any validation. Call your setup from main before the server starts, or wrap it in sync.OnceValue when tests construct routers concurrently. The type assertion is worth checking rather than ignoring: if someone installs a different binding.Validator, registration should fail at startup instead of silently doing nothing. Unit-test a custom tag directly with Validate.Var, which runs one tag against one value without a request.","code":"// setupOnce makes registration safe when tests build routers in parallel.\nvar setupOnce = sync.OnceValue(setupValidation)\n\nfunc newRouter() (*gin.Engine, error) {\n\tif err := setupOnce(); err != nil {\n\t\treturn nil, err\n\t}\n\tr := gin.New()\n\tr.POST(\"/orders\", createOrder)\n\treturn r, nil\n}\n\n// Unit-test a custom tag without HTTP:\n// v.Var(\"ABC-1234\", \"sku\") == nil, v.Var(\"abc-1234\", \"sku\") != nil","language":"go","title":"Register once, before serving","walkthrough":"This fragment shows the startup guard. sync.OnceValue runs setupValidation exactly once and returns the same error to every caller, so a broken registration fails every router construction consistently. Validate.Var is the cheapest place to test the edges of the SKU pattern: case, length and separator."},{"body":"Rules before dive apply to the collection, rules after dive apply to each element. Without dive the validator checks only the slice itself and never visits the elements, even when they are structs with their own binding tags, so items:[{\"sku\":\"abc\"}] would pass. Nested struct fields are validated without dive; a nil pointer to a struct is skipped unless the pointer field itself is required. Watch required on non-strings: on a slice it rejects only a nil value, so pair it with min=1, and on an int it rejects 0, which is why qty uses min=1 and reports a meaningful rule. If 0 must be distinguishable from an absent field, use a pointer such as *int.","title":"dive, required and the zero value"},{"body":"err.Error() on ValidationErrors produces text such as Key: 'order.Items[1].SKU' Error:Field validation for 'SKU' failed on the 'sku' tag. It exposes Go type names and changes when you rename a struct. Return a list of objects instead: field as the wire path with JSON names and [i] indices, rule as the tag name, which is a short machine-readable code, and param for bounds such as min=1 or len=8. Clients can map rule to a localized message, or you can use the validator's translation support on the server. Type errors from encoding/json happen before validation, so map them into the same shape. Use 422 for well-formed input that breaks a rule and 400 for input that cannot be decoded, or one status for both, but keep the convention identical across endpoints.","title":"A stable field-error contract"},{"body":"Table tests should hit both sides of every boundary: SKU in lower case or with three digits, quantities 0, 1, 99 and 100, zero, one, twenty and twenty-one items, a fourth coupon, a seven-character coupon, pickup false with a blank address. Assert the exact JSON body, since the order of errors is deterministic. Keep business rules that need current state, such as stock levels or coupon ownership, out of validators: they belong in the use case, after validation, as the binding-limits lesson argues.","title":"Test the rules at their edges"}],"takeaway":"Register custom tags and struct rules on binding.Validator once at startup, dive into collections explicitly, and translate ValidationErrors into field, rule and param objects that use wire names.","title":"Custom validators in Gin: register domain rules once and return field errors clients can rely on","unitID":"gin-foundations","wrongAnswers":["It stops validation at the first failing element","It applies the slice's own rules again to nested slices"]},{"conceptTag":"gin.middleware-basics","designGuide":{"cautions":["c.Value ignores non-string keys stored with c.Set.","With Recovery outermost, panicking requests leave no access-log line."],"cost":"A few small functions and one ordering decision per engine; the per-request overhead is a slice index and a map write per value.","family":"gin","flow":["Set headers before Next","Abort, then return","Read outcome after Next","Order observers outermost"],"ratings":[],"strengths":["Post-Next code observes status, errors and abort state for every request.","Typed keys and accessors make request values collision-free and explicit."]},"hint":"Look at which loop invokes the handlers and when it stops.","id":"gin.middleware-basics","introduction":"Gin middleware is an ordinary handler that happens to run before others in the same chain. Most middleware bugs come from a wrong mental model of that chain: expecting Abort to return, expecting a middleware without c.Next to stop the request, or reading a status before the handler has chosen it. This lesson builds four realistic middleware functions and traces exactly what runs.","nuance":"Gin's top-level c.Next loop keeps advancing the index after each handler returns; only Abort moves the index past the end, so Next matters only for code that must run afterwards.","objective":"Write Gin middleware that runs code after c.Next, stops the chain with Abort and return, shares typed values through c.Set and c.Get, and is ordered so logs see the final outcome.","question":"A middleware sets a header and returns without calling c.Next(). What happens to the rest of the chain?","references":["https://pkg.go.dev/github.com/gin-gonic/gin#Context.Next","https://pkg.go.dev/github.com/gin-gonic/gin#Context.Abort","https://pkg.go.dev/github.com/gin-gonic/gin#Context.Set","https://github.com/gin-gonic/gin/blob/v1.12.0/context.go"],"reviewAnswer":"The chain still continues when the middleware returns","reviewPrompt":"Middleware without c.Next()?","sections":[{"body":"For a matched route Gin stores one slice of handlers: engine middleware from r.Use, then group middleware, then the handlers passed to the route, in registration order. Serving a request calls c.Next once, which runs the slice in a loop. When a handler calls c.Next itself, the remaining handlers run inside that call and control comes back afterwards; when it returns without calling c.Next, the outer loop simply continues with the next handler. So c.Next is needed only when you want code to run after the rest of the chain. c.Abort sets the chain index to a sentinel so every loop stops, and c.IsAborted reports whether that happened. Abort does not return from the current function and does not undo anything already written.","title":"The chain is one loop over a slice"},{"body":"The program registers an access log and a request-ID middleware globally, an authentication guard on two routes and a role guard on one of them. Each middleware appends to a trace, so every response line shows which functions ran and in what order. The access-log lines printed at the end show what the outermost middleware can observe after c.Next.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// ctxKey is unexported, so no other package can collide with these keys.\ntype ctxKey int\n\nconst (\n\trequestIDKey ctxKey = iota\n\tuserKey\n)\n\ntype user struct {\n\tID   string\n\tRole string\n}\n\nvar trace []string\n\nfunc accessLog(lines *[]string) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\ttrace = append(trace, \"log>\")\n\t\tc.Next() // everything below runs after the rest of the chain\n\t\ttrace = append(trace, \"<log\")\n\t\troute := c.FullPath()\n\t\tif route == \"\" {\n\t\t\troute = \"unmatched\"\n\t\t}\n\t\t*lines = append(*lines, fmt.Sprintf(\"id=%s %s %s status=%d aborted=%t\",\n\t\t\tc.GetString(requestIDKey), c.Request.Method, route, c.Writer.Status(), c.IsAborted()))\n\t}\n}\n\nfunc requestID(next func() string) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tid := c.GetHeader(\"X-Request-Id\")\n\t\tif id == \"\" || len(id) > 64 {\n\t\t\tid = next()\n\t\t}\n\t\tc.Set(requestIDKey, id)\n\t\tc.Header(\"X-Request-Id\", id)\n\t\ttrace = append(trace, \"id\")\n\t\t// No c.Next(): Gin continues the chain when this function returns.\n\t}\n}\n\nfunc requireUser(c *gin.Context) {\n\ttokens := map[string]user{\"t-user\": {ID: \"u-1\", Role: \"member\"}, \"t-admin\": {ID: \"u-2\", Role: \"admin\"}}\n\tu, ok := tokens[strings.TrimPrefix(c.GetHeader(\"Authorization\"), \"Bearer \")]\n\tif !ok {\n\t\ttrace = append(trace, \"user:abort\")\n\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\"error\": \"unauthenticated\"})\n\t\treturn // Abort stops later handlers, return stops this one\n\t}\n\ttrace = append(trace, \"user\")\n\tc.Set(userKey, u)\n}\n\nfunc requireRole(role string) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tif currentUser(c).Role != role {\n\t\t\ttrace = append(trace, \"role:abort\")\n\t\t\tc.AbortWithStatusJSON(http.StatusForbidden, gin.H{\"error\": \"forbidden\"})\n\t\t\treturn\n\t\t}\n\t\ttrace = append(trace, \"role\")\n\t}\n}\n\n// currentUser is only called behind requireUser, so a missing key is a wiring bug.\nfunc currentUser(c *gin.Context) user {\n\treturn c.MustGet(userKey).(user)\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tvar lines []string\n\tn := 0\n\tr := gin.New()\n\tr.Use(accessLog(&lines), requestID(func() string { n++; return fmt.Sprintf(\"req-%d\", n) }))\n\tr.GET(\"/health\", func(c *gin.Context) { trace = append(trace, \"health\"); c.Status(http.StatusOK) })\n\tr.GET(\"/me\", requireUser, func(c *gin.Context) {\n\t\ttrace = append(trace, \"me\")\n\t\tc.JSON(http.StatusOK, gin.H{\"id\": currentUser(c).ID})\n\t})\n\tr.DELETE(\"/users/:id\", requireUser, requireRole(\"admin\"), func(c *gin.Context) {\n\t\ttrace = append(trace, \"delete\")\n\t\tc.Status(http.StatusNoContent)\n\t})\n\n\tfor _, tc := range []struct{ method, path, token, reqID string }{\n\t\t{\"GET\", \"/health\", \"\", \"\"},\n\t\t{\"GET\", \"/me\", \"\", \"\"},\n\t\t{\"GET\", \"/me\", \"t-user\", \"client-7\"},\n\t\t{\"DELETE\", \"/users/9\", \"t-user\", \"\"},\n\t\t{\"DELETE\", \"/users/9\", \"t-admin\", \"\"},\n\t\t{\"GET\", \"/missing\", \"\", \"\"},\n\t} {\n\t\ttrace = nil\n\t\treq := httptest.NewRequest(tc.method, tc.path, nil)\n\t\tif tc.token != \"\" {\n\t\t\treq.Header.Set(\"Authorization\", \"Bearer \"+tc.token)\n\t\t}\n\t\tif tc.reqID != \"\" {\n\t\t\treq.Header.Set(\"X-Request-Id\", tc.reqID)\n\t\t}\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tfmt.Println(tc.method, tc.path, w.Code, trace)\n\t}\n\tfor _, line := range lines {\n\t\tfmt.Println(line)\n\t}\n}","language":"go","title":"An access log, a request ID and two guards","walkthrough":"accessLog wraps everything: \"log>\" is recorded before c.Next and \"<log\" after it, even for the aborted requests and the 404, because aborting stops later handlers but returns control to earlier ones. requestID never calls c.Next, yet the chain continues. requireUser aborts with 401 and returns, so neither \"me\" nor the role check runs. On the DELETE with a member token the role guard aborts with 403. After c.Next the log reads the request ID set by an inner middleware, the template from FullPath, the final status and IsAborted. The unmatched request runs only engine middleware, which is why its trace has no guards."},{"body":"After c.Next returns, c.Writer.Status() holds the status the chain chose, which is 200 if nobody set one, so a handler that writes nothing still logs as 200. c.Writer.Written() and c.Writer.Size() tell you whether a body was written; Size is -1 when nothing was, because Gin flushes the final header only after the whole chain returns. c.Errors holds errors attached with c.Error. It is too late to change headers once the body is written, so set response headers such as X-Request-Id before c.Next, as requestID does. Panics skip the code after c.Next unless a recovery runs inside you: with accessLog registered before gin.Recovery(), the log sees the 500 that Recovery writes; with the order reversed the log line for a panicking request is simply missing.","title":"Code after Next sees the outcome, not the bytes on the wire"},{"body":"In v1.12.0 c.Keys is a map[any]any protected by a mutex, and Set, Get and MustGet take a key of type any. Use an unexported key type, as with context.WithValue, so two packages cannot overwrite each other's \"user\". Wrap reads in a typed accessor such as currentUser. MustGet panics with \"key ... does not exist\", which is right when a missing value means the route was wired without its guard; use Get and its ok flag for optional values. One trap: *gin.Context implements context.Context, but its Value method looks in Keys only for string keys, so c.Value(userKey) returns nil here and then falls back to the request context only if engine.ContextWithFallback is set. Pass the user to services as an argument, or attach it with c.Request.WithContext. Keys are cleared when the context returns to Gin's pool, so never keep them past the handler; the context-workers lesson covers that boundary.","title":"Typed keys for c.Set and c.Get"},{"body":"Engine-level middleware runs for every request, including 404 and 405 responses, so it is the place for access logs, metrics, request IDs and recovery. Group middleware suits authentication for an area of the API. Per-route middleware suits authorization and endpoint-specific policies such as a body limit or an idempotency check. Order them so observers wrap actors: logging and metrics outermost, recovery inside them, request ID before anything that logs, authentication before authorization.","code":"r := gin.New()\n// Outermost first: the log observes the 500 that Recovery writes.\nr.Use(accessLog(logger), gin.Recovery(), requestID(newID))\n\napi := r.Group(\"/api\", requireUser)                        // authentication per area\napi.GET(\"/me\", me)                                         // any signed-in user\napi.DELETE(\"/users/:id\", requireRole(\"admin\"), deleteUser) // authorization per route","language":"go","title":"Choose where each middleware lives","walkthrough":"This fragment shows the layering with placeholder constructors. The access log is outermost so it records every status, including the 500 from a recovered panic. requireUser guards the whole /api group, and requireRole(\"admin\") runs only for the DELETE route, after authentication has stored the user."},{"body":"Build a tiny engine with the middleware under test and a probe handler that records it ran. Assert the status, the headers, whether the probe ran, and what an outer recording middleware observed. Cover every abort path, a panic behind the recovery, and hostile input: a client-supplied X-Request-Id flows into your logs, so cap its length as the program does and restrict its characters before trusting it.","title":"Test middleware as part of a chain"}],"takeaway":"Call c.Next only when you need to run code afterwards, follow every Abort with return, read the outcome after Next from c.Writer and c.Errors, and share request values through typed keys and accessors.","title":"Writing Gin middleware: what c.Next returns to, what Abort does not do, and typed request values","unitID":"gin-foundations","wrongAnswers":["The request stops there and the client gets an empty 200","Gin panics because every middleware must call c.Next()"]},{"conceptTag":"gin.file-uploads","designGuide":{"cautions":["FormFile reads the whole body before you can inspect the file.","Sniffing checks signatures only; images still need decoding limits."],"cost":"A size cap, a 512-byte sniff and a hash pass per upload, plus a streaming path once files get large.","family":"gin","flow":["Cap with MaxBytesReader","Check per-file size","Sniff and allowlist","Store under own name"],"ratings":[],"strengths":["Type decisions rest on content, not on client labels.","Generated names remove traversal, collision and overwrite risks."]},"hint":"Read how Request.ParseMultipartForm describes its maxMemory argument.","id":"gin.file-uploads","introduction":"An upload is attacker-controlled bytes wrapped in attacker-controlled labels. The filename, the declared Content-Type and the size all come from the client, and so does the number of parts. c.FormFile makes accepting a file one line long, which is exactly why the limits, the type decision and the storage name have to be written deliberately around it.","nuance":"MaxMultipartMemory is the maxMemory argument to ParseMultipartForm: the remainder of the file is written to temporary files, so only http.MaxBytesReader actually bounds the request.","objective":"Accept a multipart upload in Gin with a hard size cap, decide its type from its content, generate the storage name yourself and test it with a request built by mime/multipart.","question":"An engine sets MaxMultipartMemory = 8 << 20 and has no other limit. What does that setting cap when a client uploads a 2 GiB file?","references":["https://pkg.go.dev/github.com/gin-gonic/gin#Context.FormFile","https://pkg.go.dev/net/http#DetectContentType","https://pkg.go.dev/net/http#MaxBytesReader","https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html"],"reviewAnswer":"Only memory use; larger file parts spill to temp files","reviewPrompt":"What does MaxMultipartMemory cap?","sections":[{"body":"A handler that calls c.FormFile and then c.SaveUploadedFile(file, \"uploads/\"+file.Filename) has four separate bugs. Nothing bounds the request, so one client can fill memory or the temp directory. The declared type is trusted, so an HTML page labeled image/png can be served back from your origin and run script there. The client's name decides where the file lands, so uploads overwrite each other or land somewhere unexpected. And SaveUploadedFile creates the parent directory and, in v1.12.0, also chmods it to 0o750 on every call, which can surprise an operator who set permissions on a shared directory.","title":"What goes wrong with a naive upload handler"},{"body":"The program accepts an avatar, enforces a request cap and a per-file cap, sniffs the first 512 bytes, derives the extension from an allowlist and names the file after its SHA-256. main sends seven requests: six built with mime/multipart, the same encoding a browser uses, including files that lie about their type, and one that is not multipart at all.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"mime/multipart\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/textproto\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nconst (\n\tmaxRequestBytes = 8 << 10 // whole multipart body; tiny so the demo can exceed it\n\tmaxFileBytes    = 4 << 10\n)\n\n// allowed maps a sniffed type to the only extension we will ever store.\nvar allowed = map[string]string{\"image/png\": \".png\", \"image/jpeg\": \".jpg\", \"image/gif\": \".gif\", \"image/webp\": \".webp\"}\n\nfunc uploadAvatar(c *gin.Context) {\n\tc.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxRequestBytes)\n\tfh, err := c.FormFile(\"avatar\")\n\tif err != nil {\n\t\tvar tooLarge *http.MaxBytesError\n\t\tswitch {\n\t\tcase errors.As(err, &tooLarge):\n\t\t\tc.JSON(http.StatusRequestEntityTooLarge, gin.H{\"error\": \"request exceeds 8 KiB\"})\n\t\tcase errors.Is(err, http.ErrMissingFile):\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"avatar file is required\"})\n\t\tdefault:\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"expected multipart/form-data\"})\n\t\t}\n\t\treturn\n\t}\n\tif fh.Size > maxFileBytes {\n\t\tc.JSON(http.StatusRequestEntityTooLarge, gin.H{\"error\": \"avatar exceeds 4 KiB\"})\n\t\treturn\n\t}\n\tf, err := fh.Open()\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"cannot read upload\"})\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\thead := make([]byte, 512)\n\tn, _ := io.ReadFull(f, head) // a short file is fine: sniff what we got\n\tkind := http.DetectContentType(head[:n])\n\text, ok := allowed[kind]\n\tif !ok {\n\t\tc.JSON(http.StatusUnsupportedMediaType, gin.H{\"error\": \"unsupported file type\", \"detected\": kind})\n\t\treturn\n\t}\n\n\tif _, err := f.Seek(0, io.SeekStart); err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"cannot read upload\"})\n\t\treturn\n\t}\n\tsum := sha256.New()\n\tif _, err := io.Copy(sum, f); err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"cannot read upload\"})\n\t\treturn\n\t}\n\tname := hex.EncodeToString(sum.Sum(nil))[:24] + ext\n\t// A real service now streams f to object storage under name.\n\tc.JSON(http.StatusCreated, gin.H{\"stored_as\": name, \"bytes\": fh.Size, \"type\": kind, \"original\": fh.Filename})\n}\n\n// multipartBody builds the request a browser would send for <input type=file>.\nfunc multipartBody(field, filename, declaredType string, content []byte) (*bytes.Buffer, string) {\n\tvar buf bytes.Buffer\n\tmw := multipart.NewWriter(&buf)\n\tmust(mw.SetBoundary(\"lesson-boundary-0123456789\"))\n\tmust(mw.WriteField(\"caption\", \"profile picture\"))\n\tif field != \"\" {\n\t\th := make(textproto.MIMEHeader)\n\t\th.Set(\"Content-Disposition\", fmt.Sprintf(`form-data; name=%q; filename=%q`, field, filename))\n\t\th.Set(\"Content-Type\", declaredType) // the client's claim; the handler ignores it\n\t\tpart, err := mw.CreatePart(h)\n\t\tmust(err)\n\t\t_, err = part.Write(content)\n\t\tmust(err)\n\t}\n\tmust(mw.Close())\n\treturn &buf, mw.FormDataContentType()\n}\n\nfunc must(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := gin.New()\n\tr.MaxMultipartMemory = 1 << 20 // in-memory threshold for file parts, not a size limit\n\tr.POST(\"/avatars\", uploadAvatar)\n\n\tpng := append([]byte(\"\\x89PNG\\r\\n\\x1a\\n\"), bytes.Repeat([]byte{0}, 56)...)\n\tcases := []struct {\n\t\tfield, filename, declared string\n\t\tcontent                   []byte\n\t}{\n\t\t{\"avatar\", \"../../avatar.png\", \"image/png\", png},\n\t\t{\"avatar\", \"avatar.png\", \"image/png\", []byte(\"<?php system($_GET['c']); ?>\")},\n\t\t{\"avatar\", \"cat.gif\", \"image/gif\", []byte(\"<html><script>alert(1)</script>\")},\n\t\t{\"avatar\", \"big.png\", \"image/png\", append(png, make([]byte, 5<<10)...)},\n\t\t{\"avatar\", \"huge.png\", \"image/png\", append(png, make([]byte, 10<<10)...)},\n\t\t{\"\", \"\", \"\", nil},\n\t}\n\tfor _, tc := range cases {\n\t\tbody, contentType := multipartBody(tc.field, tc.filename, tc.declared, tc.content)\n\t\treq := httptest.NewRequest(http.MethodPost, \"/avatars\", body)\n\t\treq.Header.Set(\"Content-Type\", contentType)\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tfmt.Println(w.Code, w.Body.String())\n\t}\n\n\treq := httptest.NewRequest(http.MethodPost, \"/avatars\", bytes.NewReader([]byte(`{\"avatar\":\"...\"}`)))\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, req)\n\tfmt.Println(w.Code, w.Body.String())\n}","language":"go","title":"An avatar endpoint and the requests that probe it","walkthrough":"http.MaxBytesReader wraps the body before FormFile parses it, so the 10 KiB file fails with *http.MaxBytesError and a 413, while the 5 KiB file fits the request cap and fails the fh.Size check instead. The PHP script and the HTML page both claim to be images in their part headers, but DetectContentType reports text/plain and text/html and the allowlist rejects them with 415. The first request's filename was ../../avatar.png; mime/multipart already reduced it to avatar.png, and the handler uses it only as display metadata. The stored name is the hash plus the extension chosen by the allowlist. A missing part yields http.ErrMissingFile, and a JSON body fails multipart parsing."},{"body":"Engine.MaxMultipartMemory, 32 MiB by default, is passed to Request.ParseMultipartForm as maxMemory. File parts up to that total stay in memory and the rest spill to temporary files in os.TempDir; non-file fields may use up to another 10 MiB of memory on top. Nothing in it bounds the request, so always wrap the body with http.MaxBytesReader before FormFile, MultipartForm, PostForm or ShouldBind touch it. The cap counts the whole encoded body, including boundaries and other fields, so check fh.Size for the per-file rule. Go also limits a form to 1000 parts by default, adjustable with GODEBUG=multipartmaxparts. http.Server removes the temporary files after the handler returns. Note that FormFile reads the entire body before you see the first byte of the file; for large uploads, stream with Request.MultipartReader instead.","code":"func streamAvatar(c *gin.Context) {\n\tc.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 20<<20)\n\tmr, err := c.Request.MultipartReader() // no buffering, no temp files\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"expected multipart/form-data\"})\n\t\treturn\n\t}\n\tfor {\n\t\tpart, err := mr.NextPart()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"malformed upload\"})\n\t\t\treturn\n\t\t}\n\t\tif part.FormName() != \"avatar\" {\n\t\t\tcontinue\n\t\t}\n\t\tbr := bufio.NewReaderSize(part, 512)\n\t\thead, _ := br.Peek(512) // fewer bytes for a short part is fine\n\t\tif _, ok := allowed[http.DetectContentType(head)]; !ok {\n\t\t\tc.JSON(http.StatusUnsupportedMediaType, gin.H{\"error\": \"unsupported file type\"})\n\t\t\treturn\n\t\t}\n\t\t// Copy br to storage through a hash writer, then commit the name.\n\t}\n}","language":"go","title":"MaxMultipartMemory is a buffer size, not a limit","walkthrough":"This fragment is a streaming variant for large files; run it in your own environment against real storage. MultipartReader yields parts one at a time without buffering them or creating temp files. bufio.Reader.Peek exposes the first bytes of the avatar part for sniffing without consuming them, so the same reader can then be copied to storage while hashing. The size cap still wraps the body because the client decides how much it sends."},{"body":"http.DetectContentType implements the WHATWG MIME sniffing algorithm over at most 512 bytes and always returns a valid type, falling back to application/octet-stream. Allowlist the sniffed type and derive the extension from the allowlist, never from the filename. Sniffing only checks signatures: a file can start with a PNG header and still be malformed, or be a polyglot that is valid in two formats. For images, also run image.DecodeConfig to bound the pixel dimensions before decoding, since a small file can declare an enormous canvas, and consider re-encoding to strip metadata such as GPS coordinates. When serving uploads back, send the stored type with X-Content-Type-Options: nosniff, use Content-Disposition: attachment for anything that is not an image, and prefer a separate domain for user content.","title":"Decide the type from the bytes, then constrain how you serve it"},{"body":"mime/multipart passes the filename through filepath.Base, as RFC 7578 requires, but that is a platform-dependent cleanup, not a policy. Client names still collide, can contain control characters or lookalike Unicode, can be thousands of bytes long and can carry a misleading extension. Generate the name. A content hash, as in the program, deduplicates identical files and makes retries idempotent, but two users uploading the same file share a name, and a public URL then reveals that a known file exists. crypto/rand.Text returns an unguessable name per upload when that matters. Keep the original name only as length-capped display metadata, store files outside any directory you serve statically, and write through a temporary name followed by a rename so a half-written file never becomes visible.","title":"Generate the storage name yourself"},{"body":"Build test requests with mime/multipart and a fixed boundary, as main does, so the bodies are deterministic. Cover a missing part, a wrong field name, a request over the cap, a file over its own cap but under the request cap, each kind of disguised content, an empty file and a request that is not multipart. Assert the status and the stored name, and assert that rejected uploads left nothing in storage.","title":"Test uploads with real multipart bodies"}],"takeaway":"Wrap the body in http.MaxBytesReader before parsing, check fh.Size, choose the type from DetectContentType against an allowlist, and store under a name you generate rather than one the client sent.","title":"File uploads in Gin: cap the request, sniff the bytes and never let the client name the file","unitID":"gin-foundations","wrongAnswers":["The request size: Gin answers 413 after 8 MiB","The file size: it is truncated to 8 MiB for the handler"]},{"conceptTag":"gin.html-templates","designGuide":{"cautions":["Template errors after c.HTML starts still return 200.","Plain http.FS exposes directory listings through StaticFS."],"cost":"One startup parse, a buffer per buffered page and a cache policy to maintain alongside the build step that fingerprints assets.","family":"gin","flow":["Embed templates and assets","Parse once at startup","Buffer all-or-nothing pages","Cache by asset class"],"ratings":[],"strengths":["Contextual escaping covers HTML, attributes, URLs and scripts.","Embedded templates and assets ship inside one binary."]},"hint":"Compare the /broken and /broken-buffered responses.","id":"gin.html-templates","introduction":"Gin can render server-side HTML with very little code, and Go's html/template does the hardest part, escaping, for you. What Gin leaves to you are the operational decisions: how templates reach the binary, what happens when a template fails halfway, whether a directory listing is exposed and how long browsers and CDNs may keep each file.","nuance":"c.HTML sets the status before executing into the response, so a failure leaves a 200 with an empty or partial page; buffering lets the handler pick the status after execution has succeeded.","objective":"Render html/template pages with c.HTML from templates parsed out of an embedded file system, serve embedded static assets with StaticFS and set cache headers per kind of asset.","question":"Why does renderPage execute the template into a bytes.Buffer instead of calling c.HTML directly?","references":["https://pkg.go.dev/html/template","https://pkg.go.dev/github.com/gin-gonic/gin#Engine.LoadHTMLFS","https://pkg.go.dev/embed","https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control"],"reviewAnswer":"So a template error can still become a 500, not a 200","reviewPrompt":"Why render HTML into a buffer?","sections":[{"body":"c.HTML(code, name, data) asks the engine's HTMLRender for the named template and executes it into the response with Content-Type text/html; charset=utf-8. The escaping comes from html/template, which parses the template's HTML structure and escapes each action for the context it appears in: element text, an attribute, a URL, a script or a style. The same string therefore gets different encodings in different places, and none of them can break out of its context. Two rules keep that guarantee: import html/template, never text/template, for HTML, and reserve template.HTML, template.URL and template.JS for content you produced yourself, because those types switch escaping off.","title":"html/template escapes by context; Gin only picks the template"},{"body":"The program parses two templates from a file system, renders a profile whose display name is an XSS payload, serves two static files through StaticFS with different cache rules and shows what happens when a template is missing, with and without buffered rendering. An fstest.MapFS stands in for embed.FS because go:embed needs files next to the source; both implement fs.FS, so the code is the same.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"io/fs\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"regexp\"\n\t\"strings\"\n\t\"testing/fstest\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// site stands in for an embed.FS; the files are inline so the lesson is one main.go.\nvar site = fstest.MapFS{\n\t\"templates/header.html\": {Data: []byte(`{{define \"header\"}}<!doctype html><title>{{.Title}}</title>` +\n\t\t`<link rel=\"stylesheet\" href=\"{{asset \"app.css\"}}\">{{end}}`)},\n\t\"templates/profile.html\": {Data: []byte(`{{define \"profile.html\"}}{{template \"header\" .}}` +\n\t\t`<h1>{{.Name}}</h1><a href=\"/search?q={{.Name}}\">search</a><script>const name = {{.Name}};</script>{{end}}`)},\n\t\"static/app.5d41402a.css\": {Data: []byte(\"body{margin:0}\")},\n\t\"static/logo.svg\":         {Data: []byte(`<svg xmlns=\"http://www.w3.org/2000/svg\"/>`)},\n}\n\n// manifest maps logical asset names to the fingerprinted files a build step wrote.\nvar manifest = map[string]string{\"app.css\": \"app.5d41402a.css\"}\n\nvar fingerprinted = regexp.MustCompile(`\\.[0-9a-f]{8}\\.`)\n\nfunc cacheAssets(fsys fs.FS) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tname := strings.TrimPrefix(c.Param(\"filepath\"), \"/\")\n\t\tinfo, err := fs.Stat(fsys, name)\n\t\tswitch {\n\t\tcase err != nil || info.IsDir():\n\t\t\t// No cache header on 404s.\n\t\tcase fingerprinted.MatchString(name):\n\t\t\tc.Header(\"Cache-Control\", \"public, max-age=31536000, immutable\")\n\t\tdefault:\n\t\t\tc.Header(\"Cache-Control\", \"public, max-age=300\")\n\t\t}\n\t}\n}\n\n// renderPage executes into a buffer so a template error becomes a clean 500.\nfunc renderPage(c *gin.Context, t *template.Template, name string, data any) {\n\tvar buf bytes.Buffer\n\tif err := t.ExecuteTemplate(&buf, name, data); err != nil {\n\t\t_ = c.Error(err)\n\t\tc.String(http.StatusInternalServerError, \"page unavailable\")\n\t\treturn\n\t}\n\tc.Data(http.StatusOK, \"text/html; charset=utf-8\", buf.Bytes())\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tfuncs := template.FuncMap{\"asset\": func(name string) string { return \"/static/\" + manifest[name] }}\n\ttmpl := template.Must(template.New(\"\").Funcs(funcs).ParseFS(site, \"templates/*.html\"))\n\n\tr := gin.New()\n\tr.SetHTMLTemplate(tmpl)\n\tr.GET(\"/users/:id\", func(c *gin.Context) {\n\t\tc.Header(\"Cache-Control\", \"no-cache\")\n\t\tc.HTML(http.StatusOK, \"profile.html\", gin.H{\"Title\": \"Profile\", \"Name\": `<img src=x onerror=alert(1)>`})\n\t})\n\tr.GET(\"/broken\", func(c *gin.Context) { c.HTML(http.StatusOK, \"missing.html\", nil) })\n\tr.GET(\"/broken-buffered\", func(c *gin.Context) { renderPage(c, tmpl, \"missing.html\", nil) })\n\n\tstatic, err := fs.Sub(site, \"static\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tassets := r.Group(\"/static\", cacheAssets(static))\n\tassets.StaticFS(\"/\", &gin.OnlyFilesFS{FileSystem: http.FS(static)})\n\n\tfor _, path := range []string{\n\t\t\"/users/7\", \"/broken\", \"/broken-buffered\",\n\t\t\"/static/app.5d41402a.css\", \"/static/logo.svg\", \"/static/missing.css\",\n\t} {\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))\n\t\tfmt.Printf(\"%s %d type=%q cache=%q bytes=%d\\n\", path, w.Code,\n\t\t\tw.Header().Get(\"Content-Type\"), w.Header().Get(\"Cache-Control\"), w.Body.Len())\n\t\tif strings.HasPrefix(path, \"/users/\") {\n\t\t\tfmt.Println(w.Body.String())\n\t\t}\n\t}\n}","language":"go","title":"A page, its assets and two failure modes","walkthrough":"Funcs is called before ParseFS because a template that mentions asset cannot parse without it. The payload is escaped three ways: as &lt;img in the heading, percent-encoded in the href query and as a quoted JavaScript string with \\u003c inside the script. /broken shows the trap: c.HTML has already chosen 200 when the lookup fails, so the client gets an empty 200 page. renderPage executes into a buffer first and turns the same error into a 500. The fingerprinted stylesheet gets a year-long immutable lifetime, the logo five minutes, and the missing file no cache header at all."},{"body":"Gin v1.12.0 offers LoadHTMLGlob, LoadHTMLFiles and LoadHTMLFS(fs http.FileSystem, patterns...). With an embed.FS you would call r.LoadHTMLFS(http.FS(site), \"templates/*.html\"), which panics through template.Must if a template does not parse. In debug mode all three install a renderer that re-parses on every request, useful for files on disk during development and pointless for embedded ones. Parsing yourself with template.ParseFS and handing the result to SetHTMLTemplate returns an ordinary error and leaves you holding the *template.Template for buffered rendering. All files share one namespace, so if two pages each {{define \"content\"}}, the last one parsed silently wins. Give blocks unique names, as the program does, or build one template set per page behind a custom render.HTMLRender.","code":"//go:embed templates/*.html static\nvar site embed.FS\n\nfunc newRouter() (*gin.Engine, error) {\n\ttmpl, err := template.New(\"\").Funcs(funcs).ParseFS(site, \"templates/*.html\")\n\tif err != nil {\n\t\treturn nil, err // a syntax error fails startup, not a request\n\t}\n\tstatic, err := fs.Sub(site, \"static\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := gin.New()\n\tr.SetHTMLTemplate(tmpl) // before serving: it is not safe to swap later\n\tassets := r.Group(\"/static\", cacheAssets(static))\n\tassets.StaticFS(\"/\", &gin.OnlyFilesFS{FileSystem: http.FS(static)})\n\treturn r, nil\n}","language":"go","title":"Load templates from an embedded file system","walkthrough":"This fragment is the production shape; build it in your own module with templates/ and static/ directories next to the source file, which the go:embed line compiles into the binary. It is the program's code with embed.FS in place of fstest.MapFS. Gin calls tmpl.Funcs(engine.FuncMap) inside SetHTMLTemplate, but functions used by templates must already be registered before parsing, which is why funcs is passed to template.New(\"\").Funcs."},{"body":"c.HTML records the status and then executes the template straight into the response writer. If execution fails, Gin appends the error to c.Errors and aborts, but the status is already 200 and any HTML written so far has gone to the client. A missing template yields an empty 200 page; a failure halfway through, for example a method returning an error on a nil field, yields half a page. For pages that must be all-or-nothing, execute into a bytes.Buffer and send it with c.Data, as renderPage does. The cost is holding the page in memory, which is negligible for typical pages and wrong for very large streamed reports.","title":"A template error after the status is a silent 200"},{"body":"StaticFS(\"/static\", fs) registers GET and HEAD for /static/*filepath. With a plain http.FS, a request for a directory returns an HTML listing of its files. Wrapping the file system in &gin.OnlyFilesFS, which must be a pointer because that is the type Gin checks, turns directory requests into 404s; missing files run the NoRoute handlers or return an empty 404. Files in an embed.FS have a zero modification time, so http.FileServer sends no Last-Modified header, and it never computes an ETag, so browsers cannot revalidate cheaply. Set Cache-Control yourself: a year with immutable for fingerprinted names that change whenever the content does, a short max-age for stable names, and no-cache for HTML. Set the header only after confirming the file exists, as cacheAssets does, so a CDN never stores a 404 for a year.","title":"Serve embedded assets with explicit cache rules"},{"body":"Execute every page once in a test with representative data, including hostile strings and nil fields. html/template computes its escaping on first execution, so some template errors appear only then, not at parse time. Assert the Content-Type, the escaped forms of the payload in each context, the Cache-Control value per kind of asset, a 404 for a directory and a 500 rather than an empty 200 for a failing page.","title":"Test pages and assets like any other response"}],"takeaway":"Parse html/template files from an embedded FS at startup, render pages that must not fail halfway through a buffer, disable directory listings with OnlyFilesFS and give each class of asset an explicit Cache-Control.","title":"Server-rendered HTML in Gin: embed the templates, trust contextual escaping, cache assets on purpose","unitID":"gin-foundations","wrongAnswers":["Because c.HTML does not apply html/template escaping","Because Gin cannot render templates parsed from an FS"]},{"conceptTag":"gin.not-found-and-methods","designGuide":{"cautions":["Group middleware, including auth and CORS on a group, never runs for misses.","A wrong 301 is cached by browsers and hard to undo."],"cost":"Two handlers and one flag per engine, plus tests for each miss; the 405 path adds one lookup per method tree on every unmatched request.","family":"gin","flow":["Enable 405 handling","Set NoRoute and NoMethod","Register HEAD if probed","Choose redirect codes"],"ratings":[],"strengths":["Clients get one JSON error format for hits and misses.","Allow headers tell callers exactly which methods exist."]},"hint":"Gin keeps a separate routing tree for every method; which one does a HEAD request search?","id":"gin.not-found-and-methods","introduction":"A Gin engine answers misses on its own: a plain-text 404 for unknown paths and, by default, the same 404 for a known path with the wrong method. API clients that expect JSON errors choke on the text, and a 404 for a wrong method sends whoever is debugging in the wrong direction. A few lines of configuration fix both, and the same lesson applies to redirects: the status code decides whether the method and body survive.","nuance":"There is no implicit HEAD fallback in Gin's router, so HEAD /items is a 404, or a 405 with Allow: GET when HandleMethodNotAllowed is on.","objective":"Configure NoRoute, NoMethod and HandleMethodNotAllowed for consistent JSON 404 and 405 responses with a correct Allow header, and choose between 301, 302, 303, 307 and 308 for redirects.","question":"Does Gin serve HEAD /items from a route registered only with api.GET(\"/items\", ...)?","references":["https://pkg.go.dev/github.com/gin-gonic/gin#Engine.NoMethod","https://pkg.go.dev/github.com/gin-gonic/gin#Context.Redirect","https://www.rfc-editor.org/rfc/rfc9110#section-15.5.6","https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html"],"reviewAnswer":"No; register HEAD explicitly, for example with Match","reviewPrompt":"Does a GET route answer HEAD?","sections":[{"body":"Gin keeps one routing tree per HTTP method and looks only in the tree for the request's method. With HandleMethodNotAllowed at its default of false, PUT /api/items is a 404 even when GET /api/items exists, and the body is the text/plain string \"404 page not found\". Setting HandleMethodNotAllowed to true makes Gin search the other trees after a miss, and NoRoute and NoMethod let you replace the default bodies with the error format the rest of your API uses.","title":"Gin's defaults: plain text, and 404 for wrong methods"},{"body":"The program enables 405 handling, installs JSON NoRoute and NoMethod handlers, registers a small items API plus a health route for GET and HEAD, and adds four redirect routes. Thirteen requests cover wrong methods, HEAD, an unknown path, a trailing slash, each redirect code and an attempted open redirect.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype apiError struct {\n\tCode    string `json:\"code\"`\n\tMessage string `json:\"message\"`\n}\n\n// safeNext accepts only same-site absolute paths, so ?next= cannot become an open redirect.\nfunc safeNext(raw string) string {\n\tif !strings.HasPrefix(raw, \"/\") || strings.HasPrefix(raw, \"//\") || strings.ContainsRune(raw, '\\\\') {\n\t\treturn \"/\"\n\t}\n\treturn raw\n}\n\nfunc newRouter() *gin.Engine {\n\tr := gin.New()\n\tr.HandleMethodNotAllowed = true\n\tr.NoRoute(func(c *gin.Context) {\n\t\tc.JSON(http.StatusNotFound, apiError{Code: \"not_found\", Message: \"no such resource\"})\n\t})\n\tr.NoMethod(func(c *gin.Context) {\n\t\t// Gin has already set Allow from the registered routes.\n\t\tc.JSON(http.StatusMethodNotAllowed, apiError{Code: \"method_not_allowed\", Message: \"allowed: \" + c.Writer.Header().Get(\"Allow\")})\n\t})\n\n\tapi := r.Group(\"/api\")\n\tapi.GET(\"/items\", func(c *gin.Context) { c.JSON(http.StatusOK, []string{\"a\", \"b\"}) })\n\tapi.POST(\"/items\", func(c *gin.Context) { c.Status(http.StatusCreated) })\n\tapi.GET(\"/items/:id\", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{\"id\": c.Param(\"id\")}) })\n\tapi.DELETE(\"/items/:id\", func(c *gin.Context) { c.Status(http.StatusNoContent) })\n\tapi.Match([]string{http.MethodGet, http.MethodHead}, \"/health\", func(c *gin.Context) { c.Status(http.StatusOK) })\n\n\tr.GET(\"/old-items\", func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, \"/api/items\") })\n\tr.POST(\"/old-items\", func(c *gin.Context) { c.Redirect(http.StatusPermanentRedirect, \"/api/items\") })\n\tr.POST(\"/checkout\", func(c *gin.Context) { c.Redirect(http.StatusSeeOther, \"/orders/42\") })\n\tr.GET(\"/login/done\", func(c *gin.Context) { c.Redirect(http.StatusSeeOther, safeNext(c.Query(\"next\"))) })\n\treturn r\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := newRouter()\n\tfor _, line := range []string{\n\t\t\"GET /api/items\",\n\t\t\"PUT /api/items\",\n\t\t\"HEAD /api/items\",\n\t\t\"PATCH /api/items/7\",\n\t\t\"HEAD /api/health\",\n\t\t\"GET /api/nothing\",\n\t\t\"GET /api/items/\",\n\t\t\"GET /old-items\",\n\t\t\"POST /old-items\",\n\t\t\"POST /checkout\",\n\t\t\"GET /login/done?next=/api/items\",\n\t\t\"GET /login/done?next=//evil.example\",\n\t\t\"GET /login/done?next=https://evil.example\",\n\t} {\n\t\tmethod, target, _ := strings.Cut(line, \" \")\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, httptest.NewRequest(method, target, nil))\n\t\tout := []string{line, \"->\", fmt.Sprint(w.Code)}\n\t\tif allow := w.Header().Get(\"Allow\"); allow != \"\" {\n\t\t\tout = append(out, \"Allow: \"+allow)\n\t\t}\n\t\tif loc := w.Header().Get(\"Location\"); loc != \"\" {\n\t\t\tout = append(out, \"Location: \"+loc)\n\t\t}\n\t\tif strings.HasPrefix(w.Header().Get(\"Content-Type\"), \"application/json\") {\n\t\t\tout = append(out, w.Body.String())\n\t\t}\n\t\tfmt.Println(strings.Join(out, \" \"))\n\t}\n}","language":"go","title":"An API that answers its misses","walkthrough":"PUT /api/items finds no PUT route, so Gin checks the other trees, sets Allow: GET, POST and runs NoMethod, which reads that header back into its message. HEAD /api/items is a 405 as well: a GET route does not answer HEAD. /api/health was registered with Match for both methods and answers 200. /api/nothing runs NoRoute. /api/items/ never reaches either handler, because the trailing-slash redirect fires first. GET and POST /old-items show 301 versus 308, /checkout uses 303 after a POST, and safeNext turns //evil.example and https://evil.example into a redirect to /."},{"body":"After a miss in the request method's tree Gin first tries a trailing-slash redirect, then, if RedirectFixedPath is on, a cleaned case-insensitive redirect. Only then, with HandleMethodNotAllowed on, does it look the path up in every other method's tree. If any match, it sets Allow to those methods, in the order their trees were first created on the engine, and runs the NoMethod chain with status 405; otherwise it runs the NoRoute chain with 404. If your handler writes nothing, Gin falls back to \"405 method not allowed\" or \"404 page not found\" as text/plain. Allow lists only methods you registered, so HEAD and OPTIONS never appear by implication. If a load balancer health-checks with HEAD, register it with Match or HEAD; http.Server discards a HEAD response body, but your handler still produces it. CORS preflight OPTIONS requests reach only engine-level middleware, so a CORS middleware must be installed with r.Use to answer them.","title":"How Gin chooses between 404, 405 and a redirect"},{"body":"NoRoute and NoMethod handlers are combined with engine-level middleware from r.Use only; group middleware never runs for a miss, and c.FullPath() is empty there. Reuse the same error type your handlers return so clients parse every failure the same way, and keep the message fixed rather than echoing the request path, which is attacker-controlled text that may end up in a log viewer or an HTML page. Missing files under StaticFS also run the NoRoute handlers, as the HTML-templates lesson showed. A service that serves both pages and an API can branch on the path prefix.","code":"r.NoRoute(func(c *gin.Context) {\n\tif strings.HasPrefix(c.Request.URL.Path, \"/api/\") {\n\t\tc.JSON(http.StatusNotFound, apiError{Code: \"not_found\", Message: \"no such resource\"})\n\t\treturn\n\t}\n\tc.HTML(http.StatusNotFound, \"404.html\", gin.H{\"Title\": \"Page not found\"})\n})","language":"go","title":"One error shape, including for misses","walkthrough":"This fragment assumes the apiError type from the program and a 404.html template loaded with SetHTMLTemplate. Requests under /api/ get the JSON error contract; everything else gets an HTML page with the same 404 status. Only one NoRoute chain exists per engine, so this branch is the single place where that policy lives."},{"body":"301 and 302 are the historical codes, and clients may change a POST into a GET when following them; browsers also cache a 301 aggressively, so a mistaken permanent redirect is hard to take back. Use 302 or 307 while a move is still tentative. 303 See Other tells the client to fetch the result with GET, the post/redirect/get pattern after a form submission. 307 and 308 preserve the method and the body; 308 is permanent. Gin's own trailing-slash redirects use 301 for GET and 307 for other methods for exactly that reason. c.Redirect panics for codes outside 300 to 308, except 201 Created, and http.Redirect writes its short HTML body only for GET and HEAD. Never redirect to a client-supplied URL without validation: accept only paths that start with a single slash, and reject // and backslashes, because browsers treat /\\evil.example like //evil.example, a protocol-relative URL to another host.","title":"Pick the redirect status by what must survive"},{"body":"Extend the route-table test from the route-groups lesson: for every entry in r.Routes(), send the common methods that are not registered and assert 405, the exact Allow value and a JSON Content-Type. Add HEAD for every GET route you expect monitors to probe, an unknown path, a trailing-slash variant, each redirect's status and Location, and a list of hostile next values including //host, /\\host and https://host.","title":"Test the misses as carefully as the hits"}],"takeaway":"Turn on HandleMethodNotAllowed, answer misses through NoRoute and NoMethod in your normal error format, register HEAD explicitly where it is probed, and use 303, 307 or 308 whenever the method or body must survive a redirect.","title":"404, 405 and redirects in Gin: answer misses in your own format and pick redirect codes by what must survive","unitID":"gin-foundations","wrongAnswers":["Yes; Gin runs the GET handler and drops the body","Yes, but only when HandleMethodNotAllowed is enabled"]},{"conceptTag":"gin.auth-middleware","designGuide":{"cautions":["Routes registered outside the group, or before Use, are public.","Stateless HMAC tokens cannot be revoked before expiry without extra state."],"cost":"One HMAC per request is cheap; the real cost is key management: rotation, storage in a secret manager and a revocation story.","family":"gin","flow":["Parse Authorization","Verify MAC with hmac.Equal","Store typed principal","Check scope per group"],"ratings":[],"strengths":["One verification point covers every route in the group.","Handlers receive a typed principal instead of raw headers."]},"hint":"Would sending the same request again with a freshly issued copy of this token change the outcome?","id":"gin.auth-middleware","introduction":"Authentication middleware turns an Authorization header into one of two outcomes before any handler runs: a verified principal, or a refusal the client can act on. The bugs live at the edges of that job: a route registered outside the protected group, a MAC compared with ==, a 403 where the client needed a 401, or a debug log that quietly archives every credential it sees.","nuance":"401 means the credentials are missing or invalid, so a retry with good ones may succeed. This token verified, so the refusal is about permission, which RFC 6750 signals with 403 and insufficient_scope.","objective":"Write middleware that verifies an HMAC-signed bearer token, stores a typed principal and answers 401 or 403 for the right reasons.","question":"A caller sends a valid, unexpired bearer token that lacks the notes:admin scope to an admin-only route. What should the middleware answer?","references":["https://www.rfc-editor.org/rfc/rfc6750#section-3","https://pkg.go.dev/crypto/hmac#Equal","https://pkg.go.dev/github.com/gin-gonic/gin#RouterGroup.Group","https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html"],"reviewAnswer":"403 with error=\"insufficient_scope\"","reviewPrompt":"Valid token, wrong scope: status?","sections":[{"body":"Authentication answers who is calling; authorization answers whether that caller may do this. Keep them in separate middleware so each has one reason to refuse. A 401 Unauthorized means the request carried no usable credentials and a retry with valid ones may succeed; RFC 9110 requires a WWW-Authenticate header on every 401 so the client learns which scheme to use. A 403 Forbidden means the server knows exactly who is calling and the answer is still no, so logging in again will not help. RFC 6750 refines this for bearer tokens: a request with no token gets a bare challenge, an invalid or expired token gets error=\"invalid_token\", and a valid token without the needed scope gets 403 with error=\"insufficient_scope\". Neither middleware decides whether note 7 belongs to user-42. That ownership check needs the stored data, so it belongs to the use case, which receives the principal as an argument.","title":"Decide what the middleware owns"},{"body":"An opaque token is a string the client stores and sends back but never interprets. Here it is base64url(subject|scopes|expiry) followed by a dot and an HMAC-SHA256 tag over those bytes, keyed with a server secret. The verifier recomputes the tag and compares it with hmac.Equal, whose running time does not depend on where the first differing byte is; == on strings or bytes.Equal may stop early and leak how much of a guess was right. Only a payload with a valid tag is parsed, and expiry is checked against an injected clock so tests never sleep. The program forges an admin token by swapping the payload while keeping a real tag, and replays an expired one.","code":"package main\n\nimport (\n\t\"crypto/hmac\"\n\t\"crypto/sha256\"\n\t\"encoding/base64\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"slices\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// Principal is everything downstream code may know about the caller.\ntype Principal struct {\n\tSubject string\n\tScopes  []string\n}\n\n// principalKey is unexported, so no other package can overwrite the value.\ntype principalKey struct{}\n\nvar (\n\terrMalformed = errors.New(\"malformed token\")\n\terrSignature = errors.New(\"bad signature\")\n\terrExpired   = errors.New(\"expired\")\n)\n\n// Verifier checks tokens shaped base64url(payload) \".\" base64url(HMAC-SHA256).\ntype Verifier struct {\n\tkey []byte\n\tnow func() time.Time\n}\n\nfunc (v Verifier) mac(payload []byte) []byte {\n\tm := hmac.New(sha256.New, v.key)\n\tm.Write(payload)\n\treturn m.Sum(nil)\n}\n\n// Issue exists for the demo; in production a separate login flow issues tokens.\nfunc (v Verifier) Issue(subject, scopes string, exp time.Time) string {\n\tpayload := []byte(subject + \"|\" + scopes + \"|\" + strconv.FormatInt(exp.Unix(), 10))\n\tenc := base64.RawURLEncoding\n\treturn enc.EncodeToString(payload) + \".\" + enc.EncodeToString(v.mac(payload))\n}\n\nfunc (v Verifier) Verify(token string) (Principal, error) {\n\tencPayload, encMAC, ok := strings.Cut(token, \".\")\n\tif !ok {\n\t\treturn Principal{}, errMalformed\n\t}\n\tpayload, err1 := base64.RawURLEncoding.DecodeString(encPayload)\n\tgot, err2 := base64.RawURLEncoding.DecodeString(encMAC)\n\tif err1 != nil || err2 != nil {\n\t\treturn Principal{}, errMalformed\n\t}\n\tif !hmac.Equal(got, v.mac(payload)) {\n\t\treturn Principal{}, errSignature\n\t}\n\t// Only a payload with a valid MAC is worth parsing.\n\tparts := strings.Split(string(payload), \"|\")\n\tif len(parts) != 3 {\n\t\treturn Principal{}, errMalformed\n\t}\n\texp, err := strconv.ParseInt(parts[2], 10, 64)\n\tif err != nil {\n\t\treturn Principal{}, errMalformed\n\t}\n\tif !v.now().Before(time.Unix(exp, 0)) {\n\t\treturn Principal{}, errExpired\n\t}\n\treturn Principal{Subject: parts[0], Scopes: strings.Fields(parts[1])}, nil\n}\n\nconst realm = `Bearer realm=\"notes\"`\n\nfunc authenticate(v Verifier, log *slog.Logger) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tscheme, token, ok := strings.Cut(c.GetHeader(\"Authorization\"), \" \")\n\t\tif !ok || !strings.EqualFold(scheme, \"Bearer\") || token == \"\" {\n\t\t\tc.Header(\"WWW-Authenticate\", realm)\n\t\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\"error\": \"authentication required\"})\n\t\t\treturn\n\t\t}\n\t\tp, err := v.Verify(token)\n\t\tif err != nil {\n\t\t\t// Log the route and the reason, never the credential.\n\t\t\tlog.Info(\"auth rejected\", \"route\", c.FullPath(), \"reason\", err.Error())\n\t\t\tc.Header(\"WWW-Authenticate\", realm+`, error=\"invalid_token\"`)\n\t\t\tc.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{\"error\": \"invalid token\"})\n\t\t\treturn\n\t\t}\n\t\tc.Set(principalKey{}, p)\n\t\tc.Next()\n\t}\n}\n\nfunc principalFrom(c *gin.Context) (Principal, bool) {\n\tv, ok := c.Get(principalKey{})\n\tif !ok {\n\t\treturn Principal{}, false\n\t}\n\tp, ok := v.(Principal)\n\treturn p, ok\n}\n\nfunc requireScope(scope string) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tp, ok := principalFrom(c)\n\t\tif !ok {\n\t\t\t// A route was wired without authenticate: fail closed.\n\t\t\tc.AbortWithStatus(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tif !slices.Contains(p.Scopes, scope) {\n\t\t\tc.Header(\"WWW-Authenticate\", realm+`, error=\"insufficient_scope\", scope=\"`+scope+`\"`)\n\t\t\tc.AbortWithStatusJSON(http.StatusForbidden, gin.H{\"error\": \"insufficient scope\"})\n\t\t\treturn\n\t\t}\n\t\tc.Next()\n\t}\n}\n\nfunc newRouter(v Verifier, log *slog.Logger) *gin.Engine {\n\tr := gin.New()\n\tr.GET(\"/healthz\", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{\"status\": \"ok\"}) })\n\n\tapi := r.Group(\"/api\", authenticate(v, log))\n\tapi.GET(\"/notes\", func(c *gin.Context) {\n\t\tp, _ := principalFrom(c)\n\t\tc.JSON(http.StatusOK, gin.H{\"owner\": p.Subject})\n\t})\n\tadmin := api.Group(\"/admin\", requireScope(\"notes:admin\"))\n\tadmin.DELETE(\"/notes/:id\", func(c *gin.Context) { c.Status(http.StatusNoContent) })\n\treturn r\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tnow := time.Unix(1_800_000_000, 0)\n\t// Test key only. A real key comes from a secret store and is rotated.\n\tv := Verifier{key: []byte(\"test-only-key-0123456789abcdef!!\"), now: func() time.Time { return now }}\n\tlog := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{\n\t\tReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {\n\t\t\tif a.Key == slog.TimeKey && len(groups) == 0 {\n\t\t\t\treturn slog.Attr{}\n\t\t\t}\n\t\t\treturn a\n\t\t},\n\t}))\n\tr := newRouter(v, log)\n\n\treader := v.Issue(\"user-42\", \"notes:read\", now.Add(15*time.Minute))\n\texpired := v.Issue(\"user-42\", \"notes:read\", now.Add(-time.Minute))\n\t// Swap in an admin payload but keep the reader's MAC.\n\tforged := base64.RawURLEncoding.EncodeToString([]byte(\"user-42|notes:read notes:admin|1800000900\")) +\n\t\treader[strings.IndexByte(reader, '.'):]\n\n\tcases := []struct{ method, path, auth string }{\n\t\t{\"GET\", \"/healthz\", \"\"},\n\t\t{\"GET\", \"/api/notes\", \"\"},\n\t\t{\"GET\", \"/api/notes\", \"Bearer \" + forged},\n\t\t{\"GET\", \"/api/notes\", \"Bearer \" + expired},\n\t\t{\"GET\", \"/api/notes\", \"bearer \" + reader},\n\t\t{\"DELETE\", \"/api/admin/notes/7\", \"Bearer \" + reader},\n\t}\n\tfor _, tc := range cases {\n\t\treq := httptest.NewRequest(tc.method, tc.path, nil)\n\t\tif tc.auth != \"\" {\n\t\t\treq.Header.Set(\"Authorization\", tc.auth)\n\t\t}\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tfmt.Println(tc.method, tc.path, w.Code, w.Body.String())\n\t\tif h := w.Header().Get(\"WWW-Authenticate\"); h != \"\" {\n\t\t\tfmt.Println(\"  WWW-Authenticate:\", h)\n\t\t}\n\t}\n}","language":"go","title":"Verify the MAC first, then trust the payload","walkthrough":"Verify splits at the first dot, decodes both halves and recomputes the tag before parsing anything, so the forged admin payload fails as a bad signature without its scopes ever being read. authenticate compares the scheme with strings.EqualFold because auth schemes are case-insensitive, which is why the lowercase bearer request succeeds. Each refusal sets WWW-Authenticate before AbortWithStatusJSON writes the response, and the rejection log line carries the route and a reason code but no token. c.Set stores the Principal under the unexported principalKey type, and principalFrom is the only reader, so handlers get a typed value instead of re-parsing headers. requireScope runs inside the admin group, after authenticate, and answers 403 with insufficient_scope. The JSON log handler drops the time attribute so the output is stable."},{"body":"The route group is the policy boundary: anything registered on api passes through authenticate, anything registered on r is public, whether or not that was intended. Gin copies a group's middleware into each route's handler chain at registration time, so calling api.Use(authenticate) after a route was added does not protect that earlier route; it keeps answering 200 to anonymous callers. Pass middleware to Group or call Use before registering routes, and make the gap testable. r.Routes() lists every registered method and path, which lets one test send an anonymous request to each route outside a short public allow-list and fail when any of them answers something other than 401.","code":"// In auth_test.go: every route outside the public allow-list must refuse anonymous calls.\nfunc TestRoutesRequireAuth(t *testing.T) {\n\tgin.SetMode(gin.TestMode)\n\tr := newRouter(testVerifier(), slog.New(slog.DiscardHandler))\n\tpublic := map[string]bool{\"GET /healthz\": true}\n\tfor _, rt := range r.Routes() {\n\t\tif public[rt.Method+\" \"+rt.Path] {\n\t\t\tcontinue\n\t\t}\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, httptest.NewRequest(rt.Method, rt.Path, nil))\n\t\tif w.Code != http.StatusUnauthorized {\n\t\t\tt.Errorf(\"%s %s answered %d without a token\", rt.Method, rt.Path, w.Code)\n\t\t}\n\t}\n}","language":"go","title":"Public and protected routes are a wiring decision","walkthrough":"This fragment is a go test that runs in your own project, next to newRouter. testVerifier is a helper that builds a Verifier with a fixed test key and clock, and slog.DiscardHandler keeps the rejection logs out of the test output. A path such as /api/admin/notes/:id is sent literally, which still matches the parameterized route with id set to \":id\". New routes are covered automatically, so a forgotten group fails CI instead of production."},{"body":"A bearer token is a password with an expiry date: anyone who copies it from a log file can replay it until then. Log a stable reason code such as bad signature or expired, never the header value, and keep the public response generic so clients cannot tell a forged token from an expired one. Do not accept tokens in query strings: gin.Logger records the path together with the raw query unless SkipQueryString is set, and proxies and browser history keep URLs too. Gin's Recovery middleware in debug mode dumps the request headers with only Authorization masked, so a Cookie header is printed as is. Routing every log through one redaction step, covered in the request-logging lesson, is safer than auditing each call site.","title":"Keep credentials out of logs, URLs and error bodies"},{"body":"This verifier is a model; it shows the order of checks, not a complete token system. Real deployments rotate keys, so prefix tokens with a key ID and accept the previous key for one token lifetime. A stateless HMAC token cannot be revoked before it expires, so keep lifetimes short or, when instant logout matters, issue random tokens and store their SHA-256 hash in a session table you can delete from, at the cost of one lookup per request. Load keys of at least 32 random bytes from a secret manager and use a separate key per purpose. The pipe separator only works because the issuer controls the subject; use a structured encoding for anything richer, or a vetted JWT or PASETO library that pins the algorithm. Test missing, malformed, forged, expired, wrong-scope and lowercase-scheme tokens as separate cases, and assert on headers and body as well as on the status.","title":"What a production verifier adds"}],"takeaway":"Authenticate at the group boundary, compare MACs with hmac.Equal before parsing anything, store a typed principal under an unexported key, answer 401 with WWW-Authenticate for bad credentials and 403 for missing permission, and never log the token.","title":"Bearer authentication in Gin: verify once at the group boundary, hand handlers a typed principal","unitID":"gin","wrongAnswers":["401 with error=\"invalid_token\" so the client refreshes","400, because the request asked for the wrong scope"]},{"conceptTag":"gin.cors","designGuide":{"cautions":["CORS does not stop non-browser clients or CSRF form posts.","Group-scoped CORS middleware never sees unmatched OPTIONS preflights."],"cost":"A small middleware and a list of origins to maintain per environment; the risk is in the configuration, so test it like code.","family":"gin","flow":["Add Vary: Origin","Match exact allow-list","Answer preflight with 204","Server still authorizes"],"ratings":[],"strengths":["Exact origins and validated config make the policy reviewable.","Engine-level middleware handles preflights without OPTIONS routes."]},"hint":"Think about what * would mean for the cookies of every signed-in user on every website.","id":"gin.cors","introduction":"CORS is the protocol a server uses to tell a browser which other origins may read its responses. It relaxes the same-origin policy; it never tightens it. Done carelessly it either breaks a legitimate front end or lets any website read a signed-in user's data. Done correctly it is still not authentication, authorization or CSRF protection, and the server has to keep enforcing those on its own.","nuance":"Browsers refuse * when credentials are included, so the server must echo one allow-listed origin and add Vary: Origin. Reflecting any origin instead would expose authenticated data to every site.","objective":"Implement CORS middleware that answers preflights, echoes only allow-listed origins, sets Vary correctly and is never mistaken for access control.","question":"Can a server answer a credentialed request with Access-Control-Allow-Origin: * and still let the page read the response?","references":["https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS","https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Max-Age","https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html","https://pkg.go.dev/github.com/gin-gonic/gin#Engine.Use"],"reviewAnswer":"Rejected: credentialed requests need an exact origin","reviewPrompt":"ACAO * plus credentials?","sections":[{"body":"Simple requests, such as a GET or a form POST with no custom headers, are sent straight to the server with an Origin header; afterwards the browser checks Access-Control-Allow-Origin to decide whether page script may read the answer. Anything else, such as PUT, DELETE, a JSON content type or an Authorization header, first triggers a preflight: an OPTIONS request carrying Access-Control-Request-Method and Access-Control-Request-Headers. The browser sends the real request only if the preflight response approves that origin, method and set of headers. For a simple request the handler has already run by the time the browser decides, so CORS controls who may read a response, not who may send a request. Requests made with credentials, meaning cookies or fetch with credentials: \"include\", additionally need Access-Control-Allow-Credentials: true and an explicit origin.","title":"What the browser asks and what the server decides"},{"body":"The middleware runs engine-wide. It adds Vary: Origin to every response, echoes an allow-listed origin exactly, and terminates preflights itself with 204 so no handler runs. The constructor validates configuration, so the dangerous combinations fail at startup instead of in a browser console. Five requests show an approved preflight, a refused one, a credentialed GET, a GET from an unknown origin and a GET with no Origin at all.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"slices\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype CORSConfig struct {\n\tOrigins     []string // exact scheme://host[:port] values\n\tMethods     []string // methods a preflight may ask for\n\tHeaders     []string // request headers a preflight may ask for\n\tCredentials bool     // allow cookies or Authorization from the page\n\tMaxAge      time.Duration\n}\n\nfunc newCORS(cfg CORSConfig) (gin.HandlerFunc, error) {\n\torigins := map[string]bool{}\n\tfor _, o := range cfg.Origins {\n\t\tif o == \"*\" && cfg.Credentials {\n\t\t\treturn nil, errors.New(`cors: \"*\" cannot be combined with credentials`)\n\t\t}\n\t\tif o == \"null\" {\n\t\t\treturn nil, errors.New(`cors: never allow the \"null\" origin`)\n\t\t}\n\t\torigins[o] = true\n\t}\n\theaders := map[string]bool{}\n\tfor _, h := range cfg.Headers {\n\t\theaders[strings.ToLower(h)] = true\n\t}\n\tallowMethods := strings.Join(cfg.Methods, \", \")\n\tallowHeaders := strings.Join(cfg.Headers, \", \")\n\tmaxAge := strconv.Itoa(int(cfg.MaxAge / time.Second))\n\n\treturn func(c *gin.Context) {\n\t\th := c.Writer.Header()\n\t\t// The response depends on Origin whether or not one was sent.\n\t\th.Add(\"Vary\", \"Origin\")\n\t\torigin := c.GetHeader(\"Origin\")\n\t\tpreflight := c.Request.Method == http.MethodOptions &&\n\t\t\tc.GetHeader(\"Access-Control-Request-Method\") != \"\"\n\t\tif preflight {\n\t\t\th.Add(\"Vary\", \"Access-Control-Request-Method\")\n\t\t\th.Add(\"Vary\", \"Access-Control-Request-Headers\")\n\t\t}\n\t\tallowed := origin != \"\" && (origins[origin] || origins[\"*\"])\n\t\tif !allowed {\n\t\t\tif preflight {\n\t\t\t\tc.AbortWithStatus(http.StatusForbidden)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tc.Next() // no CORS headers: the browser hides the response from the page\n\t\t\treturn\n\t\t}\n\t\tif origins[\"*\"] {\n\t\t\th.Set(\"Access-Control-Allow-Origin\", \"*\")\n\t\t} else {\n\t\t\th.Set(\"Access-Control-Allow-Origin\", origin)\n\t\t}\n\t\tif cfg.Credentials {\n\t\t\th.Set(\"Access-Control-Allow-Credentials\", \"true\")\n\t\t}\n\t\tif !preflight {\n\t\t\tc.Next()\n\t\t\treturn\n\t\t}\n\t\tif !slices.Contains(cfg.Methods, c.GetHeader(\"Access-Control-Request-Method\")) {\n\t\t\tc.AbortWithStatus(http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\t\tfor name := range strings.SplitSeq(c.GetHeader(\"Access-Control-Request-Headers\"), \",\") {\n\t\t\tif name = strings.ToLower(strings.TrimSpace(name)); name != \"\" && !headers[name] {\n\t\t\t\tc.AbortWithStatus(http.StatusForbidden)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\th.Set(\"Access-Control-Allow-Methods\", allowMethods)\n\t\th.Set(\"Access-Control-Allow-Headers\", allowHeaders)\n\t\th.Set(\"Access-Control-Max-Age\", maxAge)\n\t\tc.AbortWithStatus(http.StatusNoContent)\n\t}, nil\n}\n\nfunc show(r http.Handler, method, origin string, extra ...string) {\n\treq := httptest.NewRequest(method, \"/api/notes\", nil)\n\tif origin != \"\" {\n\t\treq.Header.Set(\"Origin\", origin)\n\t}\n\tfor i := 0; i+1 < len(extra); i += 2 {\n\t\treq.Header.Set(extra[i], extra[i+1])\n\t}\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, req)\n\tline := fmt.Sprintf(\"%s from %q: %d\", method, origin, w.Code)\n\tif body := w.Body.String(); body != \"\" {\n\t\tline += \" \" + body\n\t}\n\tfmt.Println(line)\n\tfor _, k := range []string{\"Access-Control-Allow-Origin\", \"Access-Control-Allow-Credentials\",\n\t\t\"Access-Control-Allow-Methods\", \"Access-Control-Allow-Headers\", \"Access-Control-Max-Age\"} {\n\t\tif v := w.Header().Get(k); v != \"\" {\n\t\t\tfmt.Printf(\"  %s: %s\\n\", k, v)\n\t\t}\n\t}\n\tfmt.Printf(\"  Vary: %s\\n\", strings.Join(w.Header().Values(\"Vary\"), \", \"))\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tif _, err := newCORS(CORSConfig{Origins: []string{\"*\"}, Credentials: true}); err != nil {\n\t\tfmt.Println(\"rejected config:\", err)\n\t}\n\tcors, err := newCORS(CORSConfig{\n\t\tOrigins:     []string{\"https://app.example.com\"},\n\t\tMethods:     []string{\"GET\", \"POST\", \"PUT\", \"DELETE\"},\n\t\tHeaders:     []string{\"Authorization\", \"Content-Type\"},\n\t\tCredentials: true,\n\t\tMaxAge:      10 * time.Minute,\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tr := gin.New()\n\tr.Use(cors) // engine-wide, so it also runs for OPTIONS requests that match no route\n\tr.GET(\"/api/notes\", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{\"notes\": 3}) })\n\n\tshow(r, \"OPTIONS\", \"https://app.example.com\",\n\t\t\"Access-Control-Request-Method\", \"PUT\",\n\t\t\"Access-Control-Request-Headers\", \"authorization,content-type\")\n\tshow(r, \"OPTIONS\", \"https://evil.example\", \"Access-Control-Request-Method\", \"PUT\")\n\tshow(r, \"GET\", \"https://app.example.com\")\n\tshow(r, \"GET\", \"https://evil.example\")\n\tshow(r, \"GET\", \"\")\n}","language":"go","title":"An allow-list middleware that answers preflights","walkthrough":"newCORS rejects \"*\" combined with credentials and the \"null\" origin before any request is served. Inside the middleware, Header().Add appends to Vary rather than overwriting a value another layer set. A preflight is an OPTIONS request that carries Access-Control-Request-Method; the requested method and every requested header are checked against the configured lists, lowercased because header names are case-insensitive, and the allowed preflight ends with AbortWithStatus(204). No OPTIONS route is registered, yet the preflight still reaches the middleware because r.Use also attaches it to Gin's 404 chain. The evil.example preflight is refused with 403. Its simple GET still gets 200 and the JSON body, only without CORS headers."},{"body":"When the response echoes the caller's origin, its headers depend on the Origin request header, and caches must know that. Without Vary: Origin, a shared cache or the browser's own HTTP cache can store the copy made for app.example.com and replay it to another origin, or store the copy made for a request with no Origin and replay it to a cross-origin fetch, which then fails with an error that looks random. So add Vary: Origin to every response from CORS-enabled routes, including refusals and requests without an Origin header. The wildcard means any origin may read, and browsers reject it for credentialed requests. The tempting workaround, reflecting whatever Origin arrives while also sending Allow-Credentials: true, is worse than the wildcard: it lets every website read the user's authenticated data. Never allow-list the null origin either, because sandboxed iframes and local files send it and an attacker can produce it on purpose. Compare whole origins exactly; strings.HasSuffix(origin, \"example.com\") also accepts https://evilexample.com.","title":"Vary: Origin and the wildcard rule"},{"body":"Gin runs a group's middleware only for routes that matched. A preflight for /api/notes matches nothing unless an OPTIONS route exists, so CORS middleware attached to the api group never sees it and Gin answers 404, or 405 when HandleMethodNotAllowed is enabled. Middleware registered with Engine.Use is also part of the 404 and 405 handler chains, which is why the program registers CORS there. Access-Control-Max-Age lets the browser cache an approved preflight. Without it the default is 5 seconds, and browsers cap whatever you send: Firefox at 24 hours, current Chromium at 2 hours. Ten minutes removes most preflight round trips while still letting a configuration change take effect quickly. Check Access-Control-Request-Headers against a list instead of echoing it back, so a front end cannot quietly start sending headers nobody has reviewed. The same applies to Access-Control-Expose-Headers: list response headers such as ETag explicitly if page script needs to read them.","title":"Preflight routing and max-age in Gin"},{"body":"The 200 for https://evil.example in the output is the key point: the handler ran and produced data, and only the browser declined to hand it to the page. curl, server-side scripts and attack tools ignore CORS, so every endpoint must still authenticate and authorize each request itself. CORS also does not stop cross-site request forgery. A form POST, or a simple fetch that carries cookies, is sent cross-origin without a preflight and the server performs the side effect; the attacker only loses the ability to read the reply. Cookie-authenticated APIs therefore need CSRF defenses: SameSite cookies, a synchronizer or double-submit token, or rejecting state-changing requests whose Origin or Sec-Fetch-Site header names another site. Bearer tokens sent in an Authorization header are not attached by the browser automatically, which is why they avoid classic CSRF. When reviewing a CORS change, test an approved and a refused preflight, a disallowed method and header, a credentialed request, the presence of Vary on every response and the configuration checks.","title":"What CORS does not protect"}],"takeaway":"CORS relaxes the browser's read barrier for an exact list of origins: answer preflights at the engine level, echo the origin together with Vary: Origin, never pair * or a reflected origin with credentials, and keep authentication and CSRF defenses on the server.","title":"CORS by hand in Gin: an exact origin allow-list, real preflights and Vary: Origin","unitID":"gin","wrongAnswers":["Yes, * covers every origin, credentialed or not","Yes, as long as Allow-Credentials: true is also sent"]},{"conceptTag":"gin.rate-limiting","designGuide":{"cautions":["An IP key is only as good as the trusted-proxy configuration.","In-process limits multiply by the number of replicas."],"cost":"One small struct per active client and a mutex on the map; a global limit additionally costs a shared store and a round trip per request.","family":"gin","flow":["Resolve client key","Find or create bucket","Reserve at explicit time","429 + Retry-After"],"ratings":[],"strengths":["Per-identity buckets isolate noisy clients from everyone else.","Explicit times make every limiter decision unit-testable."]},"hint":"ReserveN has already updated the bucket as if the request would run later.","id":"gin.rate-limiting","introduction":"A rate limiter protects shared capacity from one noisy client. Three decisions matter more than the algorithm: what identifies a client, how much memory the limiter may use, and what a refused client is told. Choose the key badly and an attacker gets a fresh bucket on every request. Forget the memory bound and the limiter becomes the leak it was meant to prevent.","nuance":"A reservation with a delay borrows a token from the future. If the request is dropped instead of delayed, CancelAt returns that token, so the client is not charged for work that never happened.","objective":"Limit each client with golang.org/x/time/rate, pick a key clients cannot forge, bound the limiter map and refuse with 429 and Retry-After.","question":"The middleware calls ReserveN, sees a positive delay and answers 429 without waiting. Why should it call CancelAt on the reservation?","references":["https://pkg.go.dev/golang.org/x/time/rate#Limiter.ReserveN","https://www.rfc-editor.org/rfc/rfc6585#section-4","https://www.rfc-editor.org/rfc/rfc9110#section-10.2.3","https://pkg.go.dev/github.com/gin-gonic/gin#Engine.SetTrustedProxies"],"reviewAnswer":"So the refused request does not consume a future token","reviewPrompt":"Why CancelAt after a 429?","sections":[{"body":"rate.NewLimiter(r, b) models a bucket that holds up to b tokens and refills at r tokens per second; each request takes one. The burst b absorbs short spikes, and r is the sustained rate. A Limiter is safe for concurrent use, but a map of limiters is not, so the store needs its own mutex. The methods differ in what happens when the bucket is empty. Allow reports false and nothing else. Wait blocks until a token arrives, which in an HTTP handler means holding a goroutine and a connection open for a client you meant to slow down. Reserve says how long until a token will be available, which is exactly the number Retry-After needs. AllowN and ReserveN take an explicit time.Time, so a test can drive the limiter with a fake clock instead of sleeping.","title":"Token buckets and the x/time/rate API"},{"body":"The program allows one request per second with a burst of two and keeps at most three buckets. A stand-in for the auth middleware sets the subject. Anonymous callers are keyed by ClientIP, which only means something because the engine trusts exactly one proxy address. A fake clock drives every decision, so the output never depends on how fast the machine is.","code":"package main\n\nimport (\n\t\"container/list\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"golang.org/x/time/rate\"\n)\n\n// Limiters keeps one token bucket per client key, at most max of them.\ntype Limiters struct {\n\tmu    sync.Mutex\n\tlimit rate.Limit\n\tburst int\n\tmax   int\n\tlru   *list.List // front = most recently used\n\tbyKey map[string]*list.Element\n}\n\ntype bucket struct {\n\tkey string\n\tlim *rate.Limiter\n}\n\nfunc NewLimiters(limit rate.Limit, burst, max int) *Limiters {\n\treturn &Limiters{limit: limit, burst: burst, max: max, lru: list.New(), byKey: map[string]*list.Element{}}\n}\n\nfunc (s *Limiters) get(key string) *rate.Limiter {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif el, ok := s.byKey[key]; ok {\n\t\ts.lru.MoveToFront(el)\n\t\treturn el.Value.(*bucket).lim\n\t}\n\tif s.lru.Len() >= s.max {\n\t\toldest := s.lru.Back()\n\t\ts.lru.Remove(oldest)\n\t\tdelete(s.byKey, oldest.Value.(*bucket).key)\n\t}\n\tb := &bucket{key: key, lim: rate.NewLimiter(s.limit, s.burst)}\n\ts.byKey[key] = s.lru.PushFront(b)\n\treturn b.lim\n}\n\nfunc (s *Limiters) Keys() []string {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tvar keys []string\n\tfor el := s.lru.Front(); el != nil; el = el.Next() {\n\t\tkeys = append(keys, el.Value.(*bucket).key)\n\t}\n\treturn keys\n}\n\ntype subjectKey struct{}\n\n// fakeAuth stands in for the bearer-token middleware of the auth lesson.\nfunc fakeAuth(c *gin.Context) {\n\tif c.GetHeader(\"Authorization\") == \"Bearer t-user-17\" {\n\t\tc.Set(subjectKey{}, \"user-17\")\n\t}\n\tc.Next()\n}\n\nfunc clientKey(c *gin.Context) string {\n\tif sub, ok := c.Get(subjectKey{}); ok {\n\t\treturn \"user:\" + sub.(string)\n\t}\n\treturn \"ip:\" + c.ClientIP() // safe only because trusted proxies are configured\n}\n\nfunc rateLimit(s *Limiters, now func() time.Time) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tt := now()\n\t\tres := s.get(clientKey(c)).ReserveN(t, 1)\n\t\tif !res.OK() {\n\t\t\tc.AbortWithStatus(http.StatusTooManyRequests) // burst < 1: never allowed\n\t\t\treturn\n\t\t}\n\t\tif d := res.DelayFrom(t); d > 0 {\n\t\t\tres.CancelAt(t) // we will not wait, so return the reserved token\n\t\t\tc.Header(\"Retry-After\", strconv.Itoa(int((d+time.Second-1)/time.Second)))\n\t\t\tc.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{\"error\": \"rate limited\"})\n\t\t\treturn\n\t\t}\n\t\tc.Next()\n\t}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tstart := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC)\n\tnow := start\n\tlimiters := NewLimiters(rate.Every(time.Second), 2, 3)\n\n\tr := gin.New()\n\tif err := r.SetTrustedProxies([]string{\"192.0.2.1\"}); err != nil {\n\t\tpanic(err)\n\t}\n\tr.Use(fakeAuth, rateLimit(limiters, func() time.Time { return now }))\n\tr.GET(\"/api/search\", func(c *gin.Context) { c.String(http.StatusOK, clientKey(c)) })\n\n\tsend := func(label, peer, xff, auth string) {\n\t\treq := httptest.NewRequest(\"GET\", \"/api/search\", nil)\n\t\treq.RemoteAddr = peer + \":40000\"\n\t\tif xff != \"\" {\n\t\t\treq.Header.Set(\"X-Forwarded-For\", xff)\n\t\t}\n\t\tif auth != \"\" {\n\t\t\treq.Header.Set(\"Authorization\", auth)\n\t\t}\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tline := fmt.Sprintf(\"t=%v %s: %d %s\", now.Sub(start), label, w.Code, w.Body.String())\n\t\tif ra := w.Header().Get(\"Retry-After\"); ra != \"\" {\n\t\t\tline += \" Retry-After=\" + ra\n\t\t}\n\t\tfmt.Println(line)\n\t}\n\n\tfor range 3 {\n\t\tsend(\"user-17\", \"192.0.2.1\", \"198.51.100.7\", \"Bearer t-user-17\")\n\t}\n\tsend(\"anonymous via proxy\", \"192.0.2.1\", \"198.51.100.7\", \"\")\n\tfor _, spoof := range []string{\"10.0.0.1\", \"10.0.0.2\", \"10.0.0.3\"} {\n\t\tsend(\"direct, spoofed XFF \"+spoof, \"203.0.113.9\", spoof, \"\")\n\t}\n\tnow = start.Add(time.Second)\n\tsend(\"user-17\", \"192.0.2.1\", \"198.51.100.7\", \"Bearer t-user-17\")\n\tsend(\"new client\", \"192.0.2.1\", \"198.51.100.8\", \"\")\n\tfmt.Println(\"buckets:\", strings.Join(limiters.Keys(), \" \"))\n}","language":"go","title":"Key by identity, bound the store, refuse with Retry-After","walkthrough":"get moves an existing bucket to the front of the LRU list, or creates a new one and evicts the back entry when the store is full. rateLimit calls ReserveN at the fake time. A positive delay means the bucket is empty, so the middleware calls CancelAt: otherwise the refused request would still hold a future token and the client would be charged twice. The delay is then rounded up to whole seconds for Retry-After. The third request from user-17 at t=0 is refused with Retry-After=1. The direct peer 203.0.113.9 is not a trusted proxy, so ClientIP ignores its forged X-Forwarded-For values and all three requests share one bucket. At t=1s user-17 has a token again; without the CancelAt call this request would also be refused, because the dropped reservation would still hold that token. The fourth key evicts the least recently used bucket, ip:198.51.100.7."},{"body":"The key decides who shares a bucket. A verified subject is the best key: it survives IP changes and maps to a quota a customer can understand, so authenticate before you limit and keep that check cheap. For anonymous endpoints such as login, sign-up and public search, the client address is the only signal, and it is only as trustworthy as your proxy configuration. With SetTrustedProxies covering exactly your load balancer, ClientIP returns the forwarded address. If every peer is trusted, a client can write any address into X-Forwarded-For and get a new bucket each time, as the trusted-proxies lesson shows. Even a correct address key is coarse. Many users behind one carrier NAT or office gateway share an address, and an IPv6 client can rotate through the prefix it was assigned, often a /64, so consider keying IPv6 by prefix. A login endpoint usually needs two limits: per account to slow password guessing, and per address to slow credential stuffing across many accounts.","title":"Choose a key clients cannot forge"},{"body":"Every new key allocates a limiter, so an unbounded map lets anyone who can vary the key grow your heap without limit. The LRU list caps the store with constant-time updates. Eviction has a price: an evicted client comes back with a full bucket, so heavy key churn makes the limit looser, never stricter. That is the right direction to fail for availability, but it means the cap must comfortably exceed the number of clients active at once. A bucket that has been idle for burst divided by rate seconds has refilled completely and behaves exactly like a new one, so dropping those entries loses nothing; a periodic sweep of idle entries keeps the LRU from pushing out active clients. The store also lives in one process. Behind a round-robin balancer, N replicas give each client roughly N times the configured rate. A global quota needs shared state, for example Redis updated atomically, at the cost of a network round trip per request.","title":"Bound the map and know what eviction costs"},{"body":"Answer 429 Too Many Requests, defined in RFC 6585, with Retry-After in whole seconds, rounded up, because a client that retries early is simply refused again. RFC 9110 allows either a number of seconds or an HTTP date; seconds avoid clock-skew problems. Keep the refusal cheap: the goal is to shed work, so do not run the handler, and at high volume count refusals per route instead of writing a full log line for each one. Well-behaved clients add jitter to their retries so they do not return in lockstep. A per-client limit is not overload protection. When the whole service is saturated, a global concurrency limit that answers 503 protects capacity even though every client is within its own quota. Test a burst followed by a refusal, a refill after the advertised Retry-After, independent buckets, forged forwarding headers, eviction at the cap, and concurrent requests under the race detector.","title":"What a refused client should see"}],"takeaway":"Key buckets by a verified identity, or by ClientIP only with trusted proxies configured. Bound the map and accept that eviction loosens limits, drive the limiter with explicit times, and refuse with 429 and a rounded-up Retry-After after canceling the unused reservation.","title":"Rate limiting in Gin: a token bucket per identity, a bounded map and an honest Retry-After","unitID":"gin","wrongAnswers":["CancelAt closes the limiter so the map can evict it","Without CancelAt the 429 response is never written"]},{"conceptTag":"gin.request-logging","designGuide":{"cautions":["ReplaceAttr cannot see inside maps such as a logged http.Header.","Recovery registered outside the logger hides panicking requests."],"cost":"One JSON line per request plus the storage behind it; sample or drop health probes when volume matters.","family":"gin","flow":["Accept or generate ID","Run chain with c.Next","Read route + status","Redact, then emit JSON"],"ratings":[],"strengths":["One request ID correlates logs, responses and support tickets.","Route templates keep log fields low-cardinality and free of secrets."]},"hint":"Count how many distinct values the field would hold after a million requests for different notes.","id":"gin.request-logging","introduction":"An access log is what you search during an incident. It is only useful if every line carries the same small set of fields, if one request can be followed across services by an ID, and if the log never becomes a second copy of your users' credentials. Gin's built-in Logger prints raw paths with query strings as text, so production services usually replace it with middleware built on log/slog.","nuance":"FullPath has one value per registered route and never contains IDs or query strings, so it can be grouped and alerted on without leaking tokens or personal data.","objective":"Add request-ID middleware and a structured slog access log that records low-cardinality routes, redacts credentials and can be tested byte for byte.","question":"Which value should a Gin access log record as the request path to keep the log searchable and safe?","references":["https://pkg.go.dev/log/slog#HandlerOptions","https://pkg.go.dev/github.com/gin-gonic/gin#Context.FullPath","https://pkg.go.dev/crypto/rand#Text","https://cheatsheetseries.owasp.org/cheatsheets/Logging_Cheat_Sheet.html"],"reviewAnswer":"c.FullPath(), the route template such as /notes/:id","reviewPrompt":"Access log path field?","sections":[{"body":"A request ID ties together the access line, application logs, downstream calls and the screenshot in a customer's bug report. If an edge proxy or calling service already assigned X-Request-ID, reuse it so the trail stays continuous; otherwise generate one. The incoming header is still client input. It can be very long, contain newlines that forge extra lines in text logs, or be chosen to collide with someone else's trail. Accept only a short value from a conservative alphabet and replace anything else. In production, crypto/rand.Text returns 26 base32 characters with at least 128 bits of randomness, enough that collisions are not a concern. Echo the ID in the response header so a client can quote it in a support ticket. If public clients can reach the service directly, consider always generating your own ID and logging the incoming one as a separate field.","title":"Accept a request ID only when it is well formed"},{"body":"The chain is requestID, then accessLog, then recovery. The ID exists before anything logs, and the access log wraps everything after it, so it sees the final status even when a handler panics. Four requests cover a valid incoming ID with a token in the query string, a malicious ID, an unmatched path and a panic. The JSON handler uses test options that make the output stable.","code":"package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype requestIDKey struct{}\n\n// validRequestID accepts 8 to 64 characters from a conservative alphabet.\nfunc validRequestID(s string) bool {\n\tif len(s) < 8 || len(s) > 64 {\n\t\treturn false\n\t}\n\tfor _, r := range s {\n\t\tok := r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_' || r == '.'\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc requestID(generate func() string) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tid := c.GetHeader(\"X-Request-ID\")\n\t\tif !validRequestID(id) {\n\t\t\tid = generate()\n\t\t}\n\t\tc.Set(requestIDKey{}, id)\n\t\tc.Request = c.Request.WithContext(context.WithValue(c.Request.Context(), requestIDKey{}, id))\n\t\tc.Header(\"X-Request-ID\", id)\n\t\tc.Next()\n\t}\n}\n\nfunc accessLog(log *slog.Logger) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tstart := time.Now()\n\t\tc.Next()\n\t\troute := c.FullPath() // \"/notes/:id\", never \"/notes/42?token=...\"\n\t\tif route == \"\" {\n\t\t\troute = \"unmatched\"\n\t\t}\n\t\tstatus := c.Writer.Status()\n\t\tlevel := slog.LevelInfo\n\t\tif status >= 500 {\n\t\t\tlevel = slog.LevelError\n\t\t}\n\t\tid, _ := c.Get(requestIDKey{})\n\t\tlog.LogAttrs(c.Request.Context(), level, \"request\",\n\t\t\tslog.Any(\"request_id\", id),\n\t\t\tslog.String(\"method\", c.Request.Method),\n\t\t\tslog.String(\"route\", route),\n\t\t\tslog.Int(\"status\", status),\n\t\t\tslog.Duration(\"latency\", time.Since(start)),\n\t\t\tslog.Group(\"headers\",\n\t\t\t\tslog.String(\"user_agent\", c.Request.UserAgent()),\n\t\t\t\tslog.String(\"authorization\", c.GetHeader(\"Authorization\"))),\n\t\t)\n\t}\n}\n\n// redact is the production ReplaceAttr: credentials never reach the sink.\nfunc redact(groups []string, a slog.Attr) slog.Attr {\n\tswitch strings.ToLower(a.Key) {\n\tcase \"authorization\", \"cookie\", \"set-cookie\":\n\t\tif a.Value.String() != \"\" {\n\t\t\treturn slog.String(a.Key, \"[REDACTED]\")\n\t\t}\n\t}\n\treturn a\n}\n\n// stableForTest also removes the timestamp and pins latency, the only\n// values that change from run to run.\nfunc stableForTest(groups []string, a slog.Attr) slog.Attr {\n\tif len(groups) == 0 && a.Key == slog.TimeKey {\n\t\treturn slog.Attr{}\n\t}\n\tif len(groups) == 0 && a.Key == \"latency\" {\n\t\treturn slog.Duration(a.Key, 0)\n\t}\n\treturn redact(groups, a)\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tlog := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: stableForTest}))\n\tn := 0\n\tgenerate := func() string { n++; return fmt.Sprintf(\"gen-%06d\", n) } // production: crypto/rand.Text\n\n\t// Recovery sits inside accessLog, so a panic still produces an access line.\n\trecovery := gin.CustomRecoveryWithWriter(nil, func(c *gin.Context, rec any) {\n\t\tid, _ := c.Get(requestIDKey{})\n\t\tlog.Error(\"panic recovered\", \"request_id\", id, \"panic\", fmt.Sprint(rec))\n\t\tc.AbortWithStatus(http.StatusInternalServerError)\n\t})\n\tr := gin.New()\n\tr.Use(requestID(generate), accessLog(log), recovery)\n\tr.GET(\"/notes/:id\", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{\"id\": c.Param(\"id\")}) })\n\tr.POST(\"/notes\", func(c *gin.Context) { panic(\"storage adapter bug\") })\n\n\tsend := func(method, target, incomingID string) {\n\t\treq := httptest.NewRequest(method, target, nil)\n\t\treq.Header.Set(\"User-Agent\", \"probe/1.0\")\n\t\treq.Header.Set(\"Authorization\", \"Bearer secret-token-value\")\n\t\tif incomingID != \"\" {\n\t\t\treq.Header.Set(\"X-Request-ID\", incomingID)\n\t\t}\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tfmt.Println(\"->\", w.Code, \"X-Request-ID:\", w.Header().Get(\"X-Request-ID\"))\n\t}\n\tsend(\"GET\", \"/notes/42?token=leaked\", \"edge-7f3a9c21\")\n\tsend(\"GET\", \"/notes/43\", \"bad id\\nlevel=ERROR\")\n\tsend(\"GET\", \"/admin.php\", \"\")\n\tsend(\"POST\", \"/notes\", \"\")\n}","language":"go","title":"Request ID, access log and recovery in one chain","walkthrough":"requestID validates the incoming header, falls back to the injected generator, and stores the ID both in Gin's keys and in the request context, so code that only receives a context.Context can find it. accessLog calls c.Next first; after it returns, c.FullPath and c.Writer.Status are final. The first raw URL contained ?token=leaked, yet the line records only /notes/:id. The second ID contained a newline and was replaced with gen-000001. /admin.php matched no route, so FullPath is empty and the line says unmatched. The panic is caught by recovery, logged with the same request ID and turned into a 500, and the access log still records it. redact prints every authorization value as [REDACTED]; stableForTest also drops the time and pins latency to 0 so the output can be compared exactly."},{"body":"c.FullPath returns the registered pattern, such as /notes/:id. That keeps the field low-cardinality: you can group, count and alert per route, and the log index does not gain a new value for every note ID. Raw URLs also carry data that should not be stored, such as personal identifiers, email addresses in paths and tokens in query strings. Gin's Logger appends the raw query unless SkipQueryString is set. Unmatched requests are mostly scanners, and logging them under one unmatched value keeps them countable without flooding the index. When you need the concrete resource, log the validated parameter on purpose, for example as a note_id field. Order matters too. If Recovery is registered before the logger, a panic unwinds through the logger before its line is written, and the request you most need to see disappears from the access log.","title":"Log the route template, not the URL"},{"body":"Redaction in HandlerOptions.ReplaceAttr applies to every record the logger writes, not only to the call sites a careful author remembered. ReplaceAttr runs for each non-group attribute, including attributes nested in groups, whose names it receives in the groups argument, and returning a zero Attr drops the attribute. It has a limit: it sees attributes, not the inside of values. slog.Any(\"headers\", req.Header) is a single attribute whose value is a map, so a key-based ReplaceAttr never sees the Authorization entry inside it. Log an explicit allow-list of headers instead, or wrap secrets in a type whose LogValue method returns a redacted value. The test options call redact rather than replacing it, so tests run the same redaction code as production.","code":"logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{\n\tLevel:       slog.LevelInfo,\n\tReplaceAttr: redact, // real time and latency; credentials still masked\n}))\nr := gin.New()\nr.Use(requestID(rand.Text), accessLog(logger), recovery)","language":"go","title":"Put redaction in the handler options","walkthrough":"This fragment is the production wiring and runs in your own service. crypto/rand.Text already has the func() string shape that requestID expects. Time and latency stay real, and only redact remains in ReplaceAttr. Writing JSON to stdout lets the platform's log collector ship lines without the process managing files or rotation."},{"body":"Handlers should log through the request context with logger.InfoContext(ctx, ...). The stock JSON handler ignores context values, so either wrap it with a handler that copies request_id from the context into each record, or store logger.With(\"request_id\", id) in the context. Forward X-Request-ID on outbound HTTP calls, plus traceparent if you use OpenTelemetry tracing. Log 5xx at Error and 4xx at Info: client errors are not server incidents, and alerting on them pages someone for every scanner. Health probes usually do not need a line each. Treat the log format as a contract and test it: decode each line as JSON and assert the fields, check that a known secret string never appears in the captured output, check that invalid IDs are replaced, and check that a panic still produces an access line.","title":"Carry the ID downstream and test the log contract"}],"takeaway":"Accept a well-formed incoming request ID or generate one, log after c.Next with c.FullPath, status, latency and the ID, put redaction in ReplaceAttr so every record passes through it, and register the logger outside Recovery so failed requests are logged too.","title":"Request IDs and access logs in Gin: log the route template and the ID, never the credential","unitID":"gin","wrongAnswers":["c.Request.URL.String(), so the query string is kept","c.Request.URL.Path, the exact path the client sent"]},{"conceptTag":"gin.timeouts-cancellation","designGuide":{"cautions":["Code that ignores ctx keeps running after the deadline.","Passing c as a context drops the deadline unless fallback is on."],"cost":"A timer per request and the discipline of threading ctx through every call; dependencies that cannot be canceled still need their own timeouts.","family":"gin","flow":["Derive WithTimeout","Replace c.Request","Pass ctx downstream","Map expiry to 504"],"ratings":[],"strengths":["One budget per request, inherited by every cooperating call.","A single goroutine writes the response, so nothing races."]},"hint":"Look for the engine flag that Context.Done checks before it delegates.","id":"gin.timeouts-cancellation","introduction":"A request stuck on a slow dependency holds a goroutine, a connection and often a database slot. A deadline bounds that wait, but only if every call below the handler receives the context that carries it. Deadlines are cooperative: Go cannot stop a goroutine from outside, so the safe design lets the handler notice expiry and write the response itself instead of racing it from another goroutine.","nuance":"Context.Done delegates to c.Request.Context() only when engine.ContextWithFallback is true. The default is false, so a dependency that waits on c never sees the deadline.","objective":"Give each request a deadline that downstream calls inherit, map its expiry to 504, and avoid the timeout patterns that race on the response.","question":"In Gin v1.12.0, with an engine from gin.New(), what does c.Done() return in a handler whose request context has a deadline?","references":["https://pkg.go.dev/context#WithTimeout","https://pkg.go.dev/github.com/gin-gonic/gin#Context.Done","https://pkg.go.dev/net/http#TimeoutHandler","https://go.dev/blog/context"],"reviewAnswer":"nil: no fallback to the request context","reviewPrompt":"c.Done() with default gin.New()?","sections":[{"body":"http.Server's ReadTimeout and WriteTimeout bound connection I/O; they do not cancel your handler or the query it started. net/http cancels the request context when the client disconnects, when an HTTP/2 stream is reset, or when ServeHTTP returns. How long an answer is still worth computing is an application decision, so set the deadline in middleware where it is uniform and visible. Keep it below the timeout of the client or proxy in front of you, so your own 504 arrives before their generic error, and leave time for writing the response. Downstream calls must receive c.Request.Context(), not context.Background(), or the budget stops at the handler. A child call may tighten the deadline with its own WithTimeout, but it can never extend the parent's.","title":"Decide who owns the budget"},{"body":"The middleware derives a context with a 20 ms budget, replaces c.Request with a copy that carries it, and cancels the context when the chain returns. The store models a dependency that respects its context; the hung variant never answers, so only the deadline can end the call. The last two requests inspect the context.Context methods of *gin.Context itself, with ContextWithFallback off and then on.","code":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// Store models a dependency. A hung store never answers on its own.\ntype Store struct{ hung bool }\n\nfunc (s Store) Lookup(ctx context.Context, id string) (string, error) {\n\tif s.hung {\n\t\t<-ctx.Done() // only the caller's deadline or cancellation ends the wait\n\t\treturn \"\", ctx.Err()\n\t}\n\tif err := ctx.Err(); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn \"note \" + id, nil\n}\n\n// deadline gives every request a budget that downstream calls inherit.\nfunc deadline(d time.Duration) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tctx, cancel := context.WithTimeout(c.Request.Context(), d)\n\t\tdefer cancel()\n\t\tc.Request = c.Request.WithContext(ctx)\n\t\tc.Next()\n\t}\n}\n\nfunc getNote(s Store) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tnote, err := s.Lookup(c.Request.Context(), c.Param(\"id\"))\n\t\tswitch {\n\t\tcase errors.Is(err, context.DeadlineExceeded):\n\t\t\tc.AbortWithStatusJSON(http.StatusGatewayTimeout, gin.H{\"error\": \"dependency timed out\"})\n\t\tcase errors.Is(err, context.Canceled):\n\t\t\tc.AbortWithStatus(499) // client went away: a log label, nobody reads it\n\t\tcase err != nil:\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{\"error\": \"internal\"})\n\t\tdefault:\n\t\t\tc.JSON(http.StatusOK, gin.H{\"note\": note})\n\t\t}\n\t}\n}\n\nfunc inspect(c *gin.Context) {\n\t_, hasDeadline := c.Deadline()\n\tc.String(http.StatusOK, \"deadline=%t done-nil=%t\", hasDeadline, c.Done() == nil)\n}\n\nfunc newRouter(fallback bool) *gin.Engine {\n\tr := gin.New()\n\tr.ContextWithFallback = fallback\n\tr.Use(deadline(20 * time.Millisecond))\n\tr.GET(\"/notes/:id\", getNote(Store{}))\n\tr.GET(\"/reports/:id\", getNote(Store{hung: true}))\n\tr.GET(\"/inspect\", inspect)\n\treturn r\n}\n\nfunc do(r http.Handler, req *http.Request) string {\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, req)\n\tif w.Body.Len() == 0 {\n\t\treturn fmt.Sprint(w.Code)\n\t}\n\treturn fmt.Sprint(w.Code, \" \", w.Body.String())\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := newRouter(false)\n\tfmt.Println(\"fast dependency:\", do(r, httptest.NewRequest(\"GET\", \"/notes/7\", nil)))\n\tfmt.Println(\"hung dependency:\", do(r, httptest.NewRequest(\"GET\", \"/reports/7\", nil)))\n\n\tgone, cancel := context.WithCancel(context.Background())\n\tcancel() // the client disconnected before the handler ran\n\treq := httptest.NewRequest(\"GET\", \"/reports/8\", nil).WithContext(gone)\n\tfmt.Println(\"client gone:\", do(r, req))\n\n\tfmt.Println(\"c as context, fallback off:\", do(r, httptest.NewRequest(\"GET\", \"/inspect\", nil)))\n\tfmt.Println(\"c as context, fallback on:\", do(newRouter(true), httptest.NewRequest(\"GET\", \"/inspect\", nil)))\n}","language":"go","title":"Wrap the request context and pass it down","walkthrough":"c.Request.WithContext returns a shallow copy of the request, and assigning it to c.Request makes every later c.Request.Context() call see the deadline. defer cancel releases the timer as soon as the chain returns, including on success. getNote maps context.DeadlineExceeded to 504 and context.Canceled to 499, nginx's non-standard code for a client that closed the request, which only labels the log because nobody reads that response. The hung store returns once the 20 ms budget expires. The pre-canceled request shows that a derived context inherits cancellation: the WithTimeout child is already done, and Err reports Canceled, not DeadlineExceeded. In the inspect lines, the default engine reports no deadline and a nil Done channel even though c.Request.Context() has a deadline."},{"body":"*gin.Context implements context.Context, so store.Lookup(c, id) compiles. In Gin v1.12.0 its Deadline, Done and Err delegate to c.Request.Context() only when engine.ContextWithFallback is true, and gin.New leaves it false. With the default, Done returns a nil channel, which never becomes ready in a select, and Err always returns nil, so a dependency waiting on c ignores both your deadline and the client's disconnect; against the hung store it would never return. Value splits the same way: string keys are looked up in c.Keys first, and any key not found there reaches the request context only when fallback is on, so trace spans stored by other middleware silently vanish. Pass c.Request.Context() explicitly; it is clear in review and works with any engine. If you also set ContextWithFallback, do it once at startup. Note too that c.Copy keeps the same Request and therefore the same cancellation. That is fine for a short read, but detached work needs its own context; context.WithoutCancel keeps the values and drops the cancellation, as the context-workers lesson discusses.","title":"Why passing c as the context is a trap"},{"body":"A popular timeout middleware runs c.Next in a goroutine, waits on a timer, and writes 504 itself if the timer fires first. Two goroutines now own one response: the handler may still be writing headers or a body while the middleware writes the 504, which is a data race on the ResponseWriter and can send a mixed or duplicated response. Gin makes it worse. As soon as the middleware returns, engine.ServeHTTP puts the *gin.Context back into a sync.Pool, and the next request can receive it while the abandoned handler goroutine is still using it. This is the retention bug from the context-workers lesson, hidden inside middleware. net/http's TimeoutHandler does this safely because it gives the handler a buffered, mutex-protected writer and decides the final response itself. The price is that it buffers the whole body, does not support Flusher, so streaming is impossible, and always answers 503 on timeout. A Gin access log running inside it also records the handler's status, not the 503 the client received. The cooperative design here keeps one writer: the handler notices the deadline and writes the answer.","title":"Never write the response from a second goroutine"},{"body":"504 Gateway Timeout says a dependency did not answer in time. 503 Service Unavailable, ideally with Retry-After, says the service chose not to do the work, for example because a queue was full or the budget was gone before the work started. Pick one convention and document it for clients. Check ctx.Err() before expensive steps so a request with almost no budget left fails fast, and never start a retry after the deadline has passed. Cancellation reaches only code that looks for it: a database driver can cancel a query only through QueryContext and friends, and a CPU-bound loop must check ctx itself. Test the fast path, a hung dependency, a request canceled before it starts, and a dependency that ignores its context. That last case shows the limit of cooperative cancellation, because the request returns late and the goroutine leaks. Run the suite under the race detector.","title":"Choose the status and test the edges"}],"takeaway":"Derive a per-request deadline in middleware, pass c.Request.Context() to every downstream call, map DeadlineExceeded to 504 and Canceled to a log label, and let only the handler goroutine write the response. Do not use *gin.Context as a context unless ContextWithFallback is on.","title":"Request deadlines in Gin: one context budget, cooperative handlers, no writes from a second goroutine","unitID":"gin","wrongAnswers":["The Done channel of c.Request.Context()","A channel that closes when the handler returns"]},{"conceptTag":"gin.streaming-sse","designGuide":{"cautions":["WriteTimeout cuts long streams unless you set per-write deadlines.","Shutdown does not cancel streams; give them a stop signal."],"cost":"One goroutine and one connection per subscriber for the whole session, plus a replay store if clients must resume without gaps.","family":"gin","flow":["Set headers, flush","Select ctx, feed, beat","SSEvent + Flush","Extend write deadline"],"ratings":[],"strengths":["Plain HTTP: works through proxies, with automatic reconnects.","An explicit select loop is deterministic under httptest."]},"hint":"Read the first lines of Context.Stream, then list the interfaces ResponseRecorder implements.","id":"gin.streaming-sse","introduction":"Server-Sent Events keep one HTTP response open and append small text events to it; the browser's EventSource parses them and reconnects on its own. The protocol is simple, and the engineering is all in the lifecycle. Every event must be flushed through buffers, idle streams need heartbeats, the handler must notice when the client leaves, and the server's write deadline must not cut the stream short.","nuance":"Stream calls c.Writer.CloseNotify(), which type-asserts the underlying writer to http.CloseNotifier. ResponseRecorder does not implement it, so the assertion panics, and tests need a loop on the request context instead.","objective":"Stream SSE from a Gin handler that flushes events, sends heartbeats, ends when the client leaves and survives http.Server's WriteTimeout.","question":"What happens in Gin v1.12.0 when a handler that calls c.Stream is exercised with httptest.NewRecorder()?","references":["https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events","https://pkg.go.dev/github.com/gin-gonic/gin#Context.Stream","https://pkg.go.dev/net/http#ResponseController.SetWriteDeadline","https://pkg.go.dev/net/http#Server.RegisterOnShutdown"],"reviewAnswer":"It panics: the recorder lacks CloseNotify","reviewPrompt":"c.Stream under httptest recorder?","sections":[{"body":"An event is a group of field lines ended by a blank line: event: names it, data: carries the payload, and optional id: and retry: lines support reconnection. A line that starts with a colon is a comment that EventSource ignores, which makes it a cheap heartbeat. In Gin v1.12.0, c.SSEvent(name, data) renders through gin-contrib/sse. It sets Content-Type to text/event-stream;charset=utf-8, sets Cache-Control: no-cache unless a value is already present, writes the event: and data: lines, turns newlines inside string data into extra data: lines, and JSON-encodes structs, maps and slices. It never writes an id: line. It also mostly swallows write failures: string payloads ignore them, and a failed JSON write only lands in c.Errors. The handler therefore cannot learn from SSEvent that the client has gone, and has to watch the request context instead.","title":"The wire format and what c.SSEvent writes"},{"body":"c.Stream(step) loops: it checks the channel returned by c.Writer.CloseNotify(), calls step, flushes, and stops when step returns false. Two consequences follow from the v1.12.0 code. Gin's CloseNotify is an unchecked type assertion on the underlying writer, and httptest.ResponseRecorder does not implement http.CloseNotifier, so under a recorder c.Stream panics with a missing method CloseNotify error. Disconnects are also checked only between steps, so a step that blocks waiting for the next event leaves a departed client unnoticed until something is published. net/http deprecates CloseNotifier in favor of Request.Context for exactly this reason. On a real server c.Stream works if the step itself selects on the request context.","code":"ctx := c.Request.Context()\nclientGone := c.Stream(func(w io.Writer) bool {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn false // without this case, a blocked step never sees the disconnect\n\tcase ev, ok := <-feed:\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\tc.SSEvent(ev.Name, ev.Data)\n\t\treturn true // Stream flushes after every step\n\t}\n})","language":"go","title":"What c.Stream does, read from the source","walkthrough":"This fragment runs inside a handler on a real http.Server in your own environment, where the response writer implements CloseNotify. The select inside step makes a disconnect end the stream immediately instead of at the next event. The boolean result reports whether Stream saw CloseNotify fire. Under httptest.NewRecorder the same handler panics before step is ever called, which is why the tested version below uses its own loop."},{"body":"The handler below does the same work with one select over the request context, the event feed and a heartbeat channel. It commits headers with an early flush and uses http.ResponseController to replace the server-wide WriteTimeout with a deadline per write. The test feeds the handler from one goroutine over unbuffered channels, so exactly one select case is ready at any moment and the output is deterministic. Canceling the request context simulates the client disconnecting.","code":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype Event struct {\n\tName string\n\tData any\n}\n\n// events delivers published events; beats is a ticker channel in production.\nfunc events(feed <-chan Event, beats <-chan time.Time, writeBudget time.Duration) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\trc := http.NewResponseController(c.Writer)\n\t\textend := func() bool {\n\t\t\t// Replace the server-wide WriteTimeout with a per-write budget.\n\t\t\terr := rc.SetWriteDeadline(time.Now().Add(writeBudget))\n\t\t\treturn err == nil || errors.Is(err, http.ErrNotSupported)\n\t\t}\n\t\tc.Header(\"Content-Type\", \"text/event-stream\")\n\t\tc.Header(\"Cache-Control\", \"no-cache\")\n\t\tc.Status(http.StatusOK)\n\t\tif !extend() {\n\t\t\treturn\n\t\t}\n\t\tc.Writer.Flush() // commit headers: the client now knows the stream is open\n\n\t\tctx := c.Request.Context()\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn // client gone, or the server is canceling requests\n\t\t\tcase ev, ok := <-feed:\n\t\t\t\tif !ok || !extend() {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tc.SSEvent(ev.Name, ev.Data)\n\t\t\t\tc.Writer.Flush()\n\t\t\tcase <-beats:\n\t\t\t\tif !extend() {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tif _, err := io.WriteString(c.Writer, \": ping\\n\\n\"); err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tc.Writer.Flush()\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tfeed := make(chan Event)\n\tbeats := make(chan time.Time)\n\tr := gin.New()\n\tr.GET(\"/events\", events(feed, beats, 10*time.Second))\n\n\tctx, disconnect := context.WithCancel(context.Background())\n\treq := httptest.NewRequest(\"GET\", \"/events\", nil).WithContext(ctx)\n\tgo func() {\n\t\t// Unbuffered sends: exactly one select case is ready at a time.\n\t\tfeed <- Event{\"note\", \"line one\\nline two\"}\n\t\tbeats <- time.Time{}\n\t\tfeed <- Event{\"price\", gin.H{\"cents\": 4200, \"symbol\": \"GO\"}}\n\t\tdisconnect()\n\t}()\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, req) // returns once the handler sees ctx.Done()\n\n\tres := w.Result()\n\tfmt.Println(res.StatusCode, res.Header.Get(\"Content-Type\"), res.Header.Get(\"Cache-Control\"), \"flushed:\", w.Flushed)\n\tfmt.Print(w.Body.String())\n\terr := http.NewResponseController(w).SetWriteDeadline(time.Now())\n\tfmt.Println(\"recorder supports write deadlines:\", !errors.Is(err, http.ErrNotSupported))\n}","language":"go","title":"An explicit loop that tests cleanly","walkthrough":"The Flush before the first event sends the status and headers, so EventSource fires its open event right away instead of waiting for data. The two-line note becomes two data: lines, the gin.H value is JSON-encoded with sorted keys, and : ping is a comment the browser discards. Result() reports the headers as they were when first written, so it shows the handler's text/event-stream rather than the variant SSEvent later writes into the header map. After disconnect(), ctx.Done is the only ready case, so the handler and ServeHTTP return. The last line shows that the recorder cannot set write deadlines: SetWriteDeadline returns an error matching http.ErrNotSupported, which the handler tolerates. The deadline itself needs a native integration test."},{"body":"http.Server.WriteTimeout sets one deadline on the connection after the request headers are read, and writes do not extend it. A stream that outlives it gets write errors, and clients reconnect in a loop at exactly that interval. Setting WriteTimeout to zero for the whole server removes the protection from every normal route. Instead, call SetWriteDeadline on a ResponseController before each write. The stream can then last for hours, while a client that stops reading can hold the goroutine for at most one write budget. This works through Gin's writer because ResponseController follows its Unwrap method. Heartbeats every 15 to 30 seconds keep load balancers with idle timeouts from closing quiet streams, and buffering proxies need buffering disabled for the route, for example nginx's X-Accel-Buffering: no response header. Shutdown waits for active connections to go idle and does not cancel request contexts, so an open stream blocks it until the shutdown budget expires. Use RegisterOnShutdown to close a stop channel that every stream loop selects on.","title":"WriteTimeout, proxies and shutdown"},{"body":"EventSource reconnects automatically and sends Last-Event-ID with the last id: it received. Resuming without gaps needs IDs from a durable sequence that the server can replay from. Because c.SSEvent has no id parameter, write the id: line yourself, or render a gin-contrib/sse Event with Id set through c.Render. Each stream costs one goroutine and one connection, so cap concurrent streams per user and in total; a reload loop or a forgotten tab adds up quickly. Over HTTP/1.1, browsers allow about six connections per origin across all tabs, while HTTP/2 multiplexes streams over one connection. With in-process fan-out, a slow subscriber must not block the publisher: give each subscriber a small buffered channel and disconnect it when the buffer is full, then let it resume from Last-Event-ID. Test event formatting including newlines, heartbeats, a disconnect, a closed feed and a shutdown signal, and verify write deadlines against a real listener.","title":"Resume, fan-out and limits"}],"takeaway":"Commit headers with a flush, write each event with c.SSEvent and flush it, send comment heartbeats, and select on c.Request.Context().Done() instead of relying on c.Stream's CloseNotify check. Replace the server-wide WriteTimeout with a per-write deadline from ResponseController.","title":"Server-Sent Events in Gin: flush every event, send heartbeats, stop on the request context","unitID":"gin","wrongAnswers":["It streams normally and ResponseRecorder.Flushed is true","c.Stream returns true at once, reporting a disconnect"]},{"conceptTag":"gin.metrics-health","designGuide":{"cautions":["Dependency checks in liveness turn outages into restart storms.","Raw paths or client-chosen methods as labels grow without bound."],"cost":"Two small endpoints, one middleware and a bounded map; a real metrics stack adds a client library and storage for every series you create.","family":"gin","flow":["Liveness: process only","Readiness: deps + budget","Count by route template","Bound every label"],"ratings":[],"strengths":["Probes tell the platform exactly what to do: restart or reroute.","Route-template labels keep metric cardinality fixed."]},"hint":"Ask what the platform does when liveness fails on every replica at the same moment.","id":"gin.metrics-health","introduction":"Health endpoints and request counters are how the platform and the on-call engineer see a service from outside. Each answers a narrow question: should this process be restarted, should it receive traffic right now, and how is each route behaving. Mixing up the first two causes restart storms. Labeling counters with raw paths makes the metrics system the next thing to fall over.","nuance":"A failed liveness probe triggers a restart. Restarting every replica cannot repair the database and adds reconnect load, while a failed readiness probe only takes the replica out of traffic.","objective":"Separate liveness from readiness, check dependencies within a short budget, and count requests by route template and status class.","question":"Should a service's liveness probe fail when its database is unreachable?","references":["https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/","https://prometheus.io/docs/practices/naming/","https://sre.google/sre-book/monitoring-distributed-systems/","https://pkg.go.dev/expvar"],"reviewAnswer":"No: a restart cannot fix it and causes storms","reviewPrompt":"Should liveness ping the database?","sections":[{"body":"An orchestrator such as Kubernetes restarts a container whose liveness probe fails, and stops routing traffic to one whose readiness probe fails without restarting it. If liveness checks the database, a database outage makes every replica fail liveness at once. The platform restarts all of them, the restarts add a reconnect storm to a struggling database, and the outage lasts longer. So liveness checks only what a restart can fix: the process is serving HTTP and is not wedged. Readiness checks what traffic needs: required dependencies are reachable, startup work is finished, and the replica is not draining. During shutdown, readiness turns false first so the load balancer stops sending new requests before the server drains, as the server-lifecycle lesson describes. Kubernetes HTTP probes treat any status from 200 to 399 as success, so return a 5xx code to mean not ready.","title":"Liveness and readiness answer different questions"},{"body":"readiness runs every check concurrently under one 25 ms context, so a hung dependency costs one budget rather than one per check and cannot starve the others. countRequests records the normalized method, route template and status class after c.Next. The traffic includes three user IDs, two scanner paths and a nonsense method, followed by probes before and after a simulated database outage and during a drain.","code":"package main\n\nimport (\n\t\"cmp\"\n\t\"context\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"slices\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype series struct{ method, route, class string }\n\n// Counters is a tiny concurrency-safe stand-in for a metrics client.\ntype Counters struct {\n\tmu sync.Mutex\n\tm  map[series]uint64\n}\n\nfunc (c *Counters) Inc(s series) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tc.m[s]++\n}\n\nfunc (c *Counters) WriteText(b *strings.Builder) {\n\ttype row struct {\n\t\ts series\n\t\tn uint64\n\t}\n\tc.mu.Lock()\n\trows := make([]row, 0, len(c.m))\n\tfor s, n := range c.m {\n\t\trows = append(rows, row{s, n})\n\t}\n\tc.mu.Unlock()\n\tslices.SortFunc(rows, func(a, b row) int { // map order is random; sort for stable output\n\t\treturn cmp.Or(cmp.Compare(a.s.route, b.s.route), cmp.Compare(a.s.method, b.s.method), cmp.Compare(a.s.class, b.s.class))\n\t})\n\tfor _, r := range rows {\n\t\tfmt.Fprintf(b, \"http_requests_total{method=%q,route=%q,class=%q} %d\\n\", r.s.method, r.s.route, r.s.class, r.n)\n\t}\n}\n\nfunc normMethod(m string) string {\n\tswitch m {\n\tcase \"GET\", \"HEAD\", \"POST\", \"PUT\", \"PATCH\", \"DELETE\", \"OPTIONS\":\n\t\treturn m\n\t}\n\treturn \"OTHER\" // the method string is client-controlled too\n}\n\nfunc countRequests(cnt *Counters) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.Next()\n\t\troute := c.FullPath() // the route template, never the raw path\n\t\tif route == \"\" {\n\t\t\troute = \"unmatched\"\n\t\t}\n\t\tcnt.Inc(series{normMethod(c.Request.Method), route, fmt.Sprintf(\"%dxx\", c.Writer.Status()/100)})\n\t}\n}\n\ntype Check struct {\n\tName string\n\tRun  func(context.Context) error\n}\n\nfunc readiness(checks []Check, budget time.Duration, draining *atomic.Bool) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tif draining.Load() {\n\t\t\tc.JSON(http.StatusServiceUnavailable, gin.H{\"status\": \"draining\"})\n\t\t\treturn\n\t\t}\n\t\tctx, cancel := context.WithTimeout(c.Request.Context(), budget)\n\t\tdefer cancel()\n\t\terrs := make([]error, len(checks))\n\t\tvar wg sync.WaitGroup\n\t\tfor i, ch := range checks {\n\t\t\twg.Go(func() { errs[i] = ch.Run(ctx) }) // concurrent: one slow check cannot starve the others\n\t\t}\n\t\twg.Wait()\n\t\tvar failed []string\n\t\tfor i, err := range errs {\n\t\t\tif err != nil {\n\t\t\t\tfailed = append(failed, checks[i].Name)\n\t\t\t}\n\t\t}\n\t\tif len(failed) > 0 {\n\t\t\tc.JSON(http.StatusServiceUnavailable, gin.H{\"status\": \"not ready\", \"failed\": failed})\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusOK, gin.H{\"status\": \"ready\"})\n\t}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tvar dbUp, draining atomic.Bool\n\tdbUp.Store(true)\n\tpingDB := func(ctx context.Context) error {\n\t\tif dbUp.Load() {\n\t\t\treturn nil\n\t\t}\n\t\t<-ctx.Done() // a hung database answers nothing; the budget decides\n\t\treturn ctx.Err()\n\t}\n\tpingCache := func(ctx context.Context) error { return nil }\n\n\tcnt := &Counters{m: map[series]uint64{}}\n\tr := gin.New()\n\tr.Use(countRequests(cnt))\n\tr.GET(\"/livez\", func(c *gin.Context) { c.String(http.StatusOK, \"ok\") })\n\tr.GET(\"/readyz\", readiness([]Check{{\"db\", pingDB}, {\"cache\", pingCache}}, 25*time.Millisecond, &draining))\n\tr.GET(\"/users/:id\", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{\"id\": c.Param(\"id\")}) })\n\tr.GET(\"/metrics\", func(c *gin.Context) {\n\t\tvar b strings.Builder\n\t\tcnt.WriteText(&b)\n\t\tc.String(http.StatusOK, b.String())\n\t})\n\n\tcall := func(method, path string) string {\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, httptest.NewRequest(method, path, nil))\n\t\treturn fmt.Sprint(w.Code, \" \", w.Body.String())\n\t}\n\traw := map[string]bool{}\n\tfor _, p := range []string{\"/users/1\", \"/users/2\", \"/users/3\", \"/wp-login.php\", \"/.env\"} {\n\t\traw[p] = true\n\t\tcall(\"GET\", p)\n\t}\n\tcall(\"BREW\", \"/users/1\")\n\tfmt.Println(\"livez:\", call(\"GET\", \"/livez\"), \"| readyz:\", call(\"GET\", \"/readyz\"))\n\tdbUp.Store(false)\n\tfmt.Println(\"livez:\", call(\"GET\", \"/livez\"), \"| readyz:\", call(\"GET\", \"/readyz\"))\n\tdraining.Store(true)\n\tfmt.Println(\"readyz while draining:\", call(\"GET\", \"/readyz\"))\n\tfmt.Println(len(raw), \"distinct raw paths, but only these series:\")\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, httptest.NewRequest(\"GET\", \"/metrics\", nil))\n\tfmt.Print(w.Body.String())\n}","language":"go","title":"A budgeted readiness check and route-keyed counters","walkthrough":"wg.Go, available since Go 1.25, starts each check, and each check writes only its own slot in errs, so no mutex is needed and the failed list keeps the configured order. The hung database blocks until the budget expires and is reported by name. The body leaves out the error text, because probe responses are often reachable from outside and internal hostnames do not belong there. Liveness answers 200 throughout, and draining short-circuits readiness before any check runs. countRequests labels by c.FullPath, so /users/1, /users/2 and /users/3 collapse into one series, the scanner paths become unmatched, and BREW becomes OTHER because the method string is client-controlled too. WriteText copies the map under the lock and sorts it, because map iteration order is random."},{"body":"Every distinct combination of label values is a separate time series that the metrics backend must store, index and query. Label by raw path, and every user ID, order number and scanner probe mints a new series. A crawler or a hostile client can create millions of them in an hour, which shows up as memory growth in your process, where the counter map lives, and again in the backend, where dashboards slow to a crawl. Prometheus's naming guidance is explicit: do not use labels for unbounded values such as user IDs or email addresses. Keep labels to bounded sets: the route template, a normalized method and the status class, or a short list of exact codes you actually alert on. Put the specifics in logs and traces, keyed by request ID, where high cardinality is expected and affordable. Status classes are enough for error-rate alerts; add exact codes when a dashboard has to tell 404 apart from 429.","title":"Why raw paths explode metric cardinality"},{"body":"A readiness probe runs every few seconds on every replica, so keep it cheap: a ping with a short timeout, not a real query against a large table. One shared budget, set below the probe's own timeout, guarantees the endpoint answers in time. A probe that times out is still a failure, but it tells you nothing about which dependency caused it. Consider caching the result for a second or two, or running the checks in a background goroutine and letting /readyz read the latest result, so a burst of probes cannot add load to a struggling dependency. Include only dependencies without which the replica cannot serve anything. If a recommendations service is optional, degrade that feature instead of going unready; otherwise one optional outage removes the whole fleet from rotation, which is the liveness cascade again in a different form. Serve probes on an internal port where you can, and keep their bodies minimal.","title":"Give readiness checks a budget and restraint"},{"body":"Counters models what a metrics client does: a concurrency-safe map from a bounded label set to a number, exported in a text format. A real client adds latency histograms, which count observations per bucket, process metrics and the exact exposition format with label escaping. The standard library's expvar package is an option for simple counters, but importing it registers /debug/vars on http.DefaultServeMux and publishes the command line and memory statistics, so serve it only on an internal listener. Whichever you choose, keep the metrics endpoint off the public router. Tests should check that requests for different IDs share one series, that unmatched paths and unknown methods are bucketed, that readiness fails within its budget when a dependency hangs, that liveness stays 200 throughout, and that the counter survives parallel requests under the race detector.","title":"From the model counter to a real metrics stack"}],"takeaway":"Keep liveness free of dependency checks. Let readiness check required dependencies concurrently within a short budget and report draining. Label request counters only with bounded values: route template, normalized method and status class.","title":"Health and metrics in Gin: simple liveness, budgeted readiness, counters keyed by route template","unitID":"gin","wrongAnswers":["Yes, so the platform restarts into a healthy state","Yes, liveness and readiness should run the same checks"]},{"conceptTag":"gin.conditional-requests","designGuide":{"cautions":["public on per-user data lets shared caches leak it.","Hashing still renders the full response; it saves bandwidth, not work."],"cost":"A SHA-256 over each response body and a few header checks; version-based validators save more but need a reliable version source.","family":"gin","flow":["Render bytes once","Hash to strong ETag","INM before IMS","304 or 200 + policy"],"ratings":[],"strengths":["Unchanged responses cost a header round trip, not a body.","Byte-derived ETags are always correct, even for same-second edits."]},"hint":"Check which Cache-Control directives allow a shared cache to reuse a response to an authenticated request.","id":"gin.conditional-requests","introduction":"A conditional GET lets a client that already holds a copy ask whether it is still current. When it is, the server answers 304 Not Modified with no body, which saves bandwidth and the client's parsing time. The mechanism has three parts: a validator on every response, a comparison on every request, and a Cache-Control policy that decides who may keep a copy. The policy is where private data leaks.","nuance":"RFC 9111 lets a shared cache reuse a response to a request with Authorization only when directives such as public allow it. Adding public removes that protection, so the CDN can replay one user's data to the next.","objective":"Serve ETag and Last-Modified validators, answer conditional requests with 304, and choose Cache-Control so private data never lands in a shared cache.","question":"A per-user /me response is sent with Cache-Control: public, max-age=60 behind a CDN. What can go wrong?","references":["https://www.rfc-editor.org/rfc/rfc9110#section-13.1.2","https://www.rfc-editor.org/rfc/rfc9111#section-3.5","https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Caching","https://pkg.go.dev/net/http#ServeContent"],"reviewAnswer":"Shared caches may serve it to other users","reviewPrompt":"Per-user JSON marked public: risk?","sections":[{"body":"An ETag is an opaque, quoted identifier for one representation of a resource. A strong ETag such as \"a1fe\" promises byte-for-byte identity, while a weak one such as W/\"a1fe\" promises only semantic equivalence. Last-Modified is a date with one-second resolution. Clients send them back as If-None-Match and If-Modified-Since. The order matters: when If-None-Match is present, the server evaluates it and ignores If-Modified-Since, and the date is consulted only when no ETag condition was sent. If-None-Match uses the weak comparison, so W/\"x\" matches \"x\". A 304 must carry the ETag, Cache-Control, Vary and Expires headers that a 200 would have carried, so a cache can refresh the metadata of its stored copy. This handling applies to GET and HEAD. For state-changing methods, a failed If-None-Match means 412 Precondition Failed, and If-Match is the tool for optimistic concurrency on updates.","title":"Validators and the order RFC 9110 prescribes"},{"body":"serve renders the value to bytes once, derives a strong ETag from the SHA-256 of those bytes, and sets the validators and caching headers before it decides between a bodiless 304 and a 200 carrying the bytes. The requests cover a first fetch, revalidation by ETag in strong and weak form, revalidation by date, an edit made 400 ms after the previous one, and a private endpoint.","code":"package main\n\nimport (\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype Article struct {\n\tID      int       `json:\"id\"`\n\tTitle   string    `json:\"title\"`\n\tUpdated time.Time `json:\"updated\"`\n}\n\n// strongETag names these exact bytes: any change in the body changes it.\nfunc strongETag(body []byte) string {\n\tsum := sha256.Sum256(body)\n\treturn `\"` + hex.EncodeToString(sum[:12]) + `\"`\n}\n\n// matches applies the weak comparison RFC 9110 requires for If-None-Match.\nfunc matches(ifNoneMatch, etag string) bool {\n\tif strings.TrimSpace(ifNoneMatch) == \"*\" {\n\t\treturn true\n\t}\n\tfor candidate := range strings.SplitSeq(ifNoneMatch, \",\") {\n\t\tif strings.TrimPrefix(strings.TrimSpace(candidate), \"W/\") == etag {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc notModified(c *gin.Context, etag string, modified time.Time) bool {\n\tif inm := c.GetHeader(\"If-None-Match\"); inm != \"\" {\n\t\treturn matches(inm, etag) // when present, If-Modified-Since is ignored\n\t}\n\tsince, err := http.ParseTime(c.GetHeader(\"If-Modified-Since\"))\n\treturn err == nil && !modified.Truncate(time.Second).After(since)\n}\n\n// serve renders v once, then answers 200 with the bytes or 304 without them.\nfunc serve(c *gin.Context, cacheControl string, modified time.Time, v any) {\n\tbody, err := json.Marshal(v)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tetag := strongETag(body)\n\tc.Header(\"ETag\", etag)\n\tc.Header(\"Cache-Control\", cacheControl)\n\tif !modified.IsZero() {\n\t\tc.Header(\"Last-Modified\", modified.UTC().Format(http.TimeFormat))\n\t}\n\tif notModified(c, etag, modified) {\n\t\tc.Status(http.StatusNotModified) // same validators and caching headers, no body\n\t\treturn\n\t}\n\tc.Data(http.StatusOK, \"application/json; charset=utf-8\", body)\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tarticle := Article{ID: 7, Title: \"Draining HTTP servers\", Updated: time.Date(2026, 11, 2, 9, 30, 0, 0, time.UTC)}\n\n\tr := gin.New()\n\tr.GET(\"/articles/:id\", func(c *gin.Context) {\n\t\tserve(c, \"public, max-age=60\", article.Updated, article)\n\t})\n\tr.GET(\"/me\", func(c *gin.Context) {\n\t\tif c.GetHeader(\"Authorization\") != \"Bearer t-user-17\" {\n\t\t\tc.AbortWithStatus(http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tc.Header(\"Vary\", \"Authorization\")\n\t\tserve(c, \"private, no-cache\", time.Time{}, gin.H{\"user\": \"user-17\", \"plan\": \"team\"})\n\t})\n\n\tget := func(label, path string, headers ...string) *httptest.ResponseRecorder {\n\t\treq := httptest.NewRequest(\"GET\", path, nil)\n\t\tfor i := 0; i+1 < len(headers); i += 2 {\n\t\t\treq.Header.Set(headers[i], headers[i+1])\n\t\t}\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tfmt.Printf(\"%s: %d etag=%s cache=%q bytes=%d\\n\", label, w.Code,\n\t\t\tw.Header().Get(\"ETag\"), w.Header().Get(\"Cache-Control\"), w.Body.Len())\n\t\treturn w\n\t}\n\n\tfirst := get(\"first fetch\", \"/articles/7\")\n\tetag, lastModified := first.Header().Get(\"ETag\"), first.Header().Get(\"Last-Modified\")\n\tfmt.Println(\"  Last-Modified:\", lastModified)\n\tget(\"If-None-Match\", \"/articles/7\", \"If-None-Match\", etag)\n\tget(\"weak If-None-Match\", \"/articles/7\", \"If-None-Match\", \"W/\"+etag)\n\tget(\"If-Modified-Since\", \"/articles/7\", \"If-Modified-Since\", lastModified)\n\n\t// An edit 400ms later: same second, so Last-Modified cannot see it.\n\tarticle.Title = \"Draining HTTP servers safely\"\n\tarticle.Updated = article.Updated.Add(400 * time.Millisecond)\n\tget(\"edited, If-Modified-Since\", \"/articles/7\", \"If-Modified-Since\", lastModified)\n\tget(\"edited, If-None-Match\", \"/articles/7\", \"If-None-Match\", etag)\n\tget(\"private data\", \"/me\", \"Authorization\", \"Bearer t-user-17\")\n}","language":"go","title":"Hash the bytes, compare, then send 200 or 304","walkthrough":"strongETag quotes the first 12 bytes of the SHA-256 digest in hex; 96 bits makes an accidental collision between versions of one resource irrelevant. Because the ETag names the exact bytes, any change to the JSON changes it. matches splits the header's list, strips W/ to perform the weak comparison and accepts *. notModified checks If-None-Match first and looks at If-Modified-Since only when it is absent, truncating the modification time to whole seconds as the header format does. The edited article shows why the order matters. The edit happened within the same second, so the date check wrongly answers 304. Worse, that 304 carries the new ETag, so a cache would pair the old body with the new validator and keep revalidating it successfully. The ETag check returns the new 82 bytes. c.Status(304) leaves the body empty, and Gin writes the header when the chain ends."},{"body":"Validators say whether a copy is current; Cache-Control says who may keep one and for how long. public, max-age=60 lets any cache, including CDNs and shared proxies, serve the response for 60 seconds without asking and then revalidate with the ETag, which suits data that is identical for every caller. private, no-cache lets only the user's own browser store the response and requires revalidation before each use, which suits per-user data where a 304 still saves the body. no-store forbids keeping a copy at all, which suits tokens, payment details and anything you would not want in a shared computer's disk cache. Note that no-cache does not mean do not cache; it means do not reuse without revalidating. Under RFC 9111, a shared cache must not reuse a response to a request with an Authorization header unless the response explicitly allows it with public, s-maxage or must-revalidate. Adding public to a per-user response therefore removes exactly the protection that kept the CDN from serving it to the next user. HTTP gives cookie-authenticated responses no such default, so mark them private explicitly, and list every request header that changes the response in Vary.","title":"Cache-Control for public and private data"},{"body":"Hashing the rendered bytes is simple and always correct, but the server still loads and renders everything, so a 304 saves bandwidth and client parsing, not database time. When rendering is expensive, derive the validator from a version instead: a row version, or an update timestamp with sub-second precision, combined with whatever shapes the representation, such as API version, language or selected fields. That lets the handler answer 304 before loading the full object. A strong ETag names one representation, including its content coding, so if middleware gzips the body, the compressed bytes need a different strong ETag, or a weak one. Serialization must be deterministic for byte hashing to work. encoding/json sorts map keys, but a hand-written encoder that ranges over a map does not, and every response would then look new. ETags are visible to clients, so never build them from secrets. For files and blobs, http.ServeContent implements If-None-Match, If-Modified-Since and Range for you once you set the ETag header.","title":"Where the ETag should come from"},{"body":"Assert that the first fetch returns an ETag and the intended Cache-Control. A matching If-None-Match should give 304 with an empty body and the same validators. A weak form, a list of several tags and * should all match, and a different tag should give 200. If-Modified-Since alone should work, If-None-Match should take precedence over it, and a same-second edit should be detected. Private routes must never say public, and routes whose output depends on Authorization must list it in Vary. HEAD should behave like GET without a body. The most valuable test runs in a staging environment behind the real CDN: request a private resource as user A, then as user B, and confirm that B never receives A's body. That single check catches the configuration mistakes that unit tests of the handler cannot see.","title":"Test the contract, not just the 200"}],"takeaway":"Compute a strong ETag from the exact response bytes or a precise version, check If-None-Match before If-Modified-Since, answer 304 with the same validators and caching headers but no body, and mark per-user data private or no-store so shared caches never serve it to someone else.","title":"Conditional GETs in Gin: strong ETags from response bytes, 304 Not Modified and safe Cache-Control","unitID":"gin","wrongAnswers":["Nothing: the Authorization header keeps it private","Only the ETag leaks; the body is never cached"]},{"conceptTag":"gin.project-layout","designGuide":{"cautions":["Splitting into many tiny packages early adds ceremony without protection.","Package-level globals or os.Getenv calls inside internal packages defeat the layout."],"cost":"A few more files and constructor calls than a single main.go; the payoff starts with the first test that needs a fake store.","family":"gin","flow":["Domain in internal/notes","Adapters import domain","Wire in cmd/api","Check imports in review"],"ratings":[],"strengths":["Business rules can be tested and reused without HTTP or a database.","A new storage backend or transport is a new adapter plus a line in main.","The import graph documents the architecture and can be checked in CI."]},"hint":"Look for the one function that names concrete types such as MemoryStore.","id":"gin.project-layout","introduction":"One main.go holding handlers, SQL and business rules works until the first test, the second developer or the second storage backend. This unit grows a single notes API over nine lessons, so this first lesson fixes where each piece lives. Later lessons then add CRUD, pagination, problem details, idempotency and versioning without moving code between packages.","nuance":"Only the composition root knows every concrete type. The adapters import the domain and the domain imports nothing from the project, so swapping a store changes main and nothing else.","objective":"Organize a Gin API into cmd/api, httpapi, notes and store packages whose imports point toward the domain, with all concrete wiring in main.","question":"In the notes API layout, which package is allowed to import the store, the HTTP adapter and the domain together?","references":["https://go.dev/doc/modules/layout","https://pkg.go.dev/cmd/go#hdr-Internal_packages","https://go.dev/ref/spec#Import_declarations"],"reviewAnswer":"Only cmd/api, the composition root","reviewPrompt":"Which package imports all others?","sections":[{"body":"The layout follows the server-project shape from the Go documentation: commands under cmd, everything else under internal. Inside internal the split is by responsibility, not by technical layer. notes is the domain: the Note type, the errors callers can test for, the Service with the business rules and the Store interface the service needs. store holds adapters that satisfy that interface. httpapi turns HTTP requests into service calls and service results into responses. cmd/api/main.go is the composition root that builds and connects them. The rule that keeps this from decaying is the direction of imports: both adapters import notes, notes imports neither, and only main imports everything.","code":"notes-api/\n  go.mod                    module example.com/notes-api\n  cmd/\n    api/\n      main.go               composition root: config, wiring, http.Server\n  internal/\n    notes/                  domain: Note, error values, Service, Store interface\n      note.go\n      errors.go\n      service.go\n    store/                  adapters that implement notes.Store\n      memory.go\n      postgres.go\n    httpapi/                Gin adapter: handlers, routes, error mapping\n      handler.go\n      routes.go\n      problems.go\n      handler_test.go\n    config/                 environment parsing and validation\n\nimports:\n  cmd/api       -> config, httpapi, notes, store, gin\n  httpapi       -> notes, gin\n  store         -> notes, a database driver\n  notes         -> standard library only","language":"text","title":"Four packages and one direction of imports","walkthrough":"The tree is the real module the rest of the unit builds. internal/ is enforced by the go command: only code rooted at notes-api/ may import these packages, so nothing outside the module can couple to them. The imports block is the dependency graph to defend in review. If store ever needs something from httpapi, or notes needs Gin, the arrow points the wrong way and the design, not the compiler, is the thing to fix."},{"body":"The runnable model keeps the same boundaries but folds the four packages into one file, with a comment where each package would begin. Read the types as if they were in separate directories: Note, the errors, Store and Service belong to notes; MemoryStore belongs to store; NoteService, Handler, NewRouter and writeError belong to httpapi; main is cmd/api. The program wires the pieces once and sends four requests through the engine with ServeHTTP.","code":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// ---- internal/notes: the domain. Imports only the standard library. ----\n\ntype Note struct {\n\tID    string `json:\"id\"`\n\tTitle string `json:\"title\"`\n}\n\nvar (\n\tErrNotFound = errors.New(\"notes: not found\")\n\tErrInvalid  = errors.New(\"notes: invalid input\")\n)\n\n// Store is what the service needs from persistence; adapters implement it.\ntype Store interface {\n\tInsert(ctx context.Context, n Note) error\n\tGet(ctx context.Context, id string) (Note, error)\n}\n\ntype Service struct {\n\tstore  Store\n\tnextID func() string\n}\n\nfunc NewService(store Store, nextID func() string) *Service {\n\treturn &Service{store: store, nextID: nextID}\n}\n\nfunc (s *Service) Create(ctx context.Context, title string) (Note, error) {\n\ttitle = strings.TrimSpace(title)\n\tif title == \"\" || len(title) > 80 {\n\t\treturn Note{}, ErrInvalid\n\t}\n\tn := Note{ID: s.nextID(), Title: title}\n\treturn n, s.store.Insert(ctx, n)\n}\n\nfunc (s *Service) Get(ctx context.Context, id string) (Note, error) {\n\treturn s.store.Get(ctx, id)\n}\n\n// ---- internal/store: an adapter. Imports notes, never httpapi. ----\n\ntype MemoryStore struct {\n\tmu    sync.RWMutex\n\tnotes map[string]Note\n}\n\nfunc NewMemoryStore() *MemoryStore {\n\treturn &MemoryStore{notes: map[string]Note{}}\n}\n\nfunc (m *MemoryStore) Insert(_ context.Context, n Note) error {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tm.notes[n.ID] = n\n\treturn nil\n}\n\nfunc (m *MemoryStore) Get(_ context.Context, id string) (Note, error) {\n\tm.mu.RLock()\n\tdefer m.mu.RUnlock()\n\tn, ok := m.notes[id]\n\tif !ok {\n\t\treturn Note{}, ErrNotFound\n\t}\n\treturn n, nil\n}\n\n// ---- internal/httpapi: the Gin adapter. Imports notes, never store. ----\n\ntype NoteService interface {\n\tCreate(ctx context.Context, title string) (Note, error)\n\tGet(ctx context.Context, id string) (Note, error)\n}\n\ntype Handler struct{ svc NoteService }\n\nfunc NewRouter(h *Handler) *gin.Engine {\n\tr := gin.New()\n\tr.Use(gin.Recovery())\n\tr.POST(\"/notes\", h.create)\n\tr.GET(\"/notes/:id\", h.get)\n\treturn r\n}\n\nfunc (h *Handler) create(c *gin.Context) {\n\tvar in struct {\n\t\tTitle string `json:\"title\"`\n\t}\n\tif err := c.ShouldBindJSON(&in); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"malformed body\"})\n\t\treturn\n\t}\n\tn, err := h.svc.Create(c.Request.Context(), in.Title)\n\tif err != nil {\n\t\twriteError(c, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusCreated, n)\n}\n\nfunc (h *Handler) get(c *gin.Context) {\n\tn, err := h.svc.Get(c.Request.Context(), c.Param(\"id\"))\n\tif err != nil {\n\t\twriteError(c, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, n)\n}\n\nfunc writeError(c *gin.Context, err error) {\n\tswitch {\n\tcase errors.Is(err, ErrNotFound):\n\t\tc.JSON(http.StatusNotFound, gin.H{\"error\": \"note not found\"})\n\tcase errors.Is(err, ErrInvalid):\n\t\tc.JSON(http.StatusUnprocessableEntity, gin.H{\"error\": \"title must be 1-80 characters\"})\n\tdefault:\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"internal error\"})\n\t}\n}\n\n// ---- cmd/api: the composition root. The only place that knows every concrete type. ----\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\n\tseq := 0\n\tnextID := func() string { seq++; return fmt.Sprintf(\"n%d\", seq) }\n\n\tstore := NewMemoryStore()\n\tsvc := NewService(store, nextID)\n\trouter := NewRouter(&Handler{svc: svc})\n\n\trequests := []struct{ method, path, body string }{\n\t\t{http.MethodPost, \"/notes\", `{\"title\":\"  Buy milk \"}`},\n\t\t{http.MethodGet, \"/notes/n1\", \"\"},\n\t\t{http.MethodPost, \"/notes\", `{\"title\":\"   \"}`},\n\t\t{http.MethodGet, \"/notes/n9\", \"\"},\n\t}\n\tfor _, rq := range requests {\n\t\tw := httptest.NewRecorder()\n\t\treq := httptest.NewRequest(rq.method, rq.path, strings.NewReader(rq.body))\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\trouter.ServeHTTP(w, req)\n\t\tfmt.Println(rq.method, rq.path, w.Code, w.Body.String())\n\t}\n}","language":"go","title":"The whole service in one runnable file","walkthrough":"The domain trims the title and rejects an empty or overlong one with ErrInvalid; that rule lives in Service, so a CLI or a queue consumer would get it too. MemoryStore satisfies Store without naming it, and it returns ErrNotFound from the domain package rather than inventing its own error. The Handler depends on NoteService, an interface listing the two calls it makes, so httpapi never sees MemoryStore. main is the only function that names every concrete type: it builds the ID source, the store, the service and the router, in that order. The output shows a created note, a read, a 422 for a blank title and a 404, all mapped in writeError, which the problem-details lesson later moves into one middleware."},{"body":"The composition root reads configuration, constructs concrete adapters, connects them through constructors and owns the process lifecycle: starting the server, handling signals and calling os.Exit. It should read like a wiring diagram, a few dozen lines with no business decisions. Everything else moves out. Packages under internal should not call os.Getenv, parse flags, open connections in init, keep package-level singletons or call log.Fatal. Each of those hides an input or an exit path from the caller and makes the package impossible to test in isolation. When a package needs a setting, it takes it as a constructor argument or a field; when it fails, it returns an error and lets main decide whether that ends the process. The config-and-startup lesson at the end of this unit fills in main completely.","title":"What belongs in main, and what never does"},{"body":"Package-by-layer trees such as models, controllers and services look organized, but every package imports models, everything is exported to cross the boundaries, and a change to one feature touches all of them. A utils or common package becomes the place where unrelated code goes to import each other. A domain function that accepts *gin.Context or returns gin.H has quietly made Gin part of the business rules, so a background job now needs a fake HTTP request. An httpapi handler that imports store directly to save a layer bypasses the service and its rules. A top-level pkg directory in a service that no other module imports adds a path segment and no protection; internal already says what it means. Start with few packages named for what they provide, and split one only when it has a second reason to change.","title":"Layouts that look tidy and still couple everything"},{"body":"Go refuses to compile an import cycle, so the most damaging mistakes surface early, but a one-way dependency in the wrong direction compiles fine. Make the intended graph visible and cheap to check. go list prints each package with its imports, and a short pipeline can fail a CI job when the domain starts depending on Gin or on an adapter. Review a new import in notes with the same care as a new dependency in go.mod.","code":"# Each package in the module and what it imports.\ngo list -f '{{.ImportPath}} -> {{join .Imports \" \"}}' ./...\n\n# The domain must not depend on Gin, a store or the HTTP adapter.\ngo list -deps ./internal/notes \\\n  | grep -E 'gin-gonic|notes-api/internal/(store|httpapi)' \\\n  && echo \"layering violation\" || echo \"notes is clean\"","language":"bash","title":"Check the direction of imports in review","walkthrough":"Run these commands in your own checkout of the module. The first prints one line per package, for example \"example.com/notes-api/internal/store -> context example.com/notes-api/internal/notes sync\", which is exactly the arrow the layout promises. The second lists every transitive dependency of internal/notes and searches it for Gin or the two adapter packages; any match prints \"layering violation\", and a CI step can turn that into a failing exit code."}],"takeaway":"Keep internal/notes free of Gin and storage imports, let the HTTP and storage adapters import the domain, and confine concrete wiring, configuration and os.Exit to cmd/api/main.go.","title":"Lay out a Gin service so every import points toward the domain","unitID":"gin-project","wrongAnswers":["internal/notes, so the service can build its own store","internal/httpapi, so handlers can open the database"]},{"conceptTag":"gin.handler-dependencies","designGuide":{"cautions":["A typed nil pointer inside an interface passes a nil check.","Hand-written fakes need a mutex if tests share them across goroutines."],"cost":"Constructor parameters and a few small interfaces; main grows by a handful of lines per dependency.","family":"gin","flow":["List what handlers call","Declare consumer interface","Inject via constructor","Swap fakes in tests"],"ratings":[],"strengths":["Every collaborator is visible in one struct and one constructor call.","Tests run the real router with a fake store, clock and IDs.","Missing wiring fails at startup or at compile time, not on a request."]},"hint":"Ask which package needs to replace the dependency in its tests.","id":"gin.handler-dependencies","introduction":"A handler that reaches for a package-level database variable works on the first day and fights you afterwards: tests share state, parallel tests race, and no signature tells a reviewer what the handler can touch. Passing dependencies through a constructor makes them visible, replaceable and checked by the compiler. This lesson does that for the notes API, including the clock and the ID source.","nuance":"The consumer knows which methods it calls. Declaring the interface there keeps it small, leaves the provider concrete and avoids an import from the domain back to the adapter.","objective":"Write handlers as methods on a struct built by a constructor, depend on small consumer-defined interfaces and swap in a fake store for tests.","question":"In the notes API, which package should declare the NoteService interface that the HTTP handlers depend on?","references":["https://go.dev/wiki/CodeReviewComments#interfaces","https://go.dev/doc/effective_go#interfaces","https://pkg.go.dev/github.com/gin-gonic/gin#IRouter"],"reviewAnswer":"In the package that consumes them","reviewPrompt":"Where do Go interfaces belong?","sections":[{"body":"Both shapes below compile and serve requests. The first keeps the store in a package variable, so every test in the package shares one instance, a test that forgets to reset it leaks data into the next, and t.Parallel turns that into a race. The second hides the dependency in the Gin context: some middleware must call c.Set first, the type assertion moves a compile-time fact to run time, and a forgotten Use call becomes a panic on the first request rather than a build error. time.Now and an unseeded random ID generator are hidden globals of the same kind; they are why a response body cannot be compared byte for byte in a test.","code":"// Hidden dependencies: nothing in the signature says what getNote touches.\nvar db *store.Memory // set in init or main; shared by every test\n\nfunc getNote(c *gin.Context) {\n\tn, err := db.Get(c.Request.Context(), c.Param(\"id\"))\n\t// ...\n}\n\n// A service locator through the context: the dependency is resolved at\n// runtime, and a missing middleware becomes a panic on the first request.\nfunc getNoteFromContext(c *gin.Context) {\n\tsvc := c.MustGet(\"notes\").(*notes.Service)\n\t// ...\n}","language":"go","title":"What globals and context lookups cost","walkthrough":"This fragment shows what to avoid and is not meant to compile on its own. getNote has no parameters that mention storage, so a reader must search the package to learn where db is assigned. getNoteFromContext depends on a string key and a concrete type assertion; renaming the key or changing the type is not caught until a request hits the route. Request-scoped values such as the authenticated user do belong in the context; long-lived dependencies do not."},{"body":"The notes service now takes three dependencies in its constructor: a Store, a clock and an ID source. The HTTP Handler takes a NoteService and a *slog.Logger. Register attaches method values such as h.getNote to any gin.IRouter, so the same handler works on an engine or a route group. The test half of the file builds the same graph with a fake store, a fixed clock and sequential IDs, then runs a healthy and a failing scenario through the real router.","code":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// ---- internal/notes ----\n\ntype Note struct {\n\tID        string    `json:\"id\"`\n\tTitle     string    `json:\"title\"`\n\tCreatedAt time.Time `json:\"createdAt\"`\n}\n\nvar ErrNotFound = errors.New(\"notes: not found\")\n\ntype Store interface {\n\tInsert(ctx context.Context, n Note) error\n\tGet(ctx context.Context, id string) (Note, error)\n}\n\ntype Service struct {\n\tstore  Store\n\tnow    func() time.Time\n\tnextID func() string\n}\n\nfunc NewService(store Store, now func() time.Time, nextID func() string) (*Service, error) {\n\tif store == nil || now == nil || nextID == nil {\n\t\treturn nil, errors.New(\"notes: NewService needs a store, a clock and an ID source\")\n\t}\n\treturn &Service{store: store, now: now, nextID: nextID}, nil\n}\n\nfunc (s *Service) Create(ctx context.Context, title string) (Note, error) {\n\tn := Note{ID: s.nextID(), Title: strings.TrimSpace(title), CreatedAt: s.now().UTC()}\n\tif err := s.store.Insert(ctx, n); err != nil {\n\t\treturn Note{}, fmt.Errorf(\"insert note: %w\", err)\n\t}\n\treturn n, nil\n}\n\nfunc (s *Service) Get(ctx context.Context, id string) (Note, error) {\n\treturn s.store.Get(ctx, id)\n}\n\n// ---- internal/httpapi ----\n\n// NoteService lists only what these handlers call. *notes.Service satisfies it implicitly.\ntype NoteService interface {\n\tCreate(ctx context.Context, title string) (Note, error)\n\tGet(ctx context.Context, id string) (Note, error)\n}\n\ntype Handler struct {\n\tnotes NoteService\n\tlog   *slog.Logger\n}\n\nfunc NewHandler(notes NoteService, log *slog.Logger) *Handler {\n\treturn &Handler{notes: notes, log: log}\n}\n\nfunc (h *Handler) Register(r gin.IRouter) {\n\tr.GET(\"/notes/:id\", h.getNote)\n\tr.POST(\"/notes\", h.createNote)\n}\n\nfunc (h *Handler) getNote(c *gin.Context) {\n\tid := c.Param(\"id\")\n\tn, err := h.notes.Get(c.Request.Context(), id)\n\tswitch {\n\tcase errors.Is(err, ErrNotFound):\n\t\tc.JSON(http.StatusNotFound, gin.H{\"error\": \"note not found\"})\n\tcase err != nil:\n\t\th.log.Error(\"get note\", \"id\", id, \"err\", err)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"internal error\"})\n\tdefault:\n\t\tc.JSON(http.StatusOK, n)\n\t}\n}\n\nfunc (h *Handler) createNote(c *gin.Context) {\n\tvar in struct {\n\t\tTitle string `json:\"title\" binding:\"required\"`\n\t}\n\tif err := c.ShouldBindJSON(&in); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"title is required\"})\n\t\treturn\n\t}\n\tn, err := h.notes.Create(c.Request.Context(), in.Title)\n\tif err != nil {\n\t\th.log.Error(\"create note\", \"err\", err)\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"internal error\"})\n\t\treturn\n\t}\n\tc.JSON(http.StatusCreated, n)\n}\n\n// ---- handler_test.go: a fake Store the test fully controls ----\n\ntype fakeStore struct {\n\tnotes map[string]Note\n\terr   error // when set, every call fails with it\n\tcalls []string\n}\n\nfunc (f *fakeStore) Insert(_ context.Context, n Note) error {\n\tf.calls = append(f.calls, \"Insert \"+n.ID)\n\tif f.err != nil {\n\t\treturn f.err\n\t}\n\tf.notes[n.ID] = n\n\treturn nil\n}\n\nfunc (f *fakeStore) Get(_ context.Context, id string) (Note, error) {\n\tf.calls = append(f.calls, \"Get \"+id)\n\tif f.err != nil {\n\t\treturn Note{}, f.err\n\t}\n\tn, ok := f.notes[id]\n\tif !ok {\n\t\treturn Note{}, ErrNotFound\n\t}\n\treturn n, nil\n}\n\nfunc newTestRouter(store Store, log *slog.Logger) (*gin.Engine, error) {\n\tclock := func() time.Time { return time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) }\n\tseq := 0\n\tids := func() string { seq++; return fmt.Sprintf(\"n%d\", seq) }\n\tsvc, err := NewService(store, clock, ids)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr := gin.New()\n\tNewHandler(svc, log).Register(r)\n\treturn r, nil\n}\n\nfunc send(r http.Handler, method, path, body string) {\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))\n\tfmt.Println(method, path, w.Code, w.Body.String())\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tlog := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{\n\t\tReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {\n\t\t\tif a.Key == slog.TimeKey && len(groups) == 0 {\n\t\t\t\treturn slog.Attr{} // drop the timestamp so output is stable\n\t\t\t}\n\t\t\treturn a\n\t\t},\n\t}))\n\n\tif _, err := NewService(nil, time.Now, nil); err != nil {\n\t\tfmt.Println(\"wiring error:\", err)\n\t}\n\n\thealthy := &fakeStore{notes: map[string]Note{\n\t\t\"n7\": {ID: \"n7\", Title: \"Write tests\", CreatedAt: time.Date(2026, 1, 1, 9, 0, 0, 0, time.UTC)},\n\t}}\n\tr, err := newTestRouter(healthy, log)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsend(r, http.MethodGet, \"/notes/n7\", \"\")\n\tsend(r, http.MethodPost, \"/notes\", `{\"title\":\"Review PR\"}`)\n\tfmt.Println(\"store calls:\", healthy.calls)\n\n\tbroken := &fakeStore{err: errors.New(\"dial tcp 192.0.2.10:5432: connection refused\")}\n\tr, err = newTestRouter(broken, log)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tsend(r, http.MethodGet, \"/notes/n7\", \"\")\n}","language":"go","title":"Handlers as methods, dependencies as fields","walkthrough":"NewService refuses a nil dependency, so the first output line is a wiring error at startup instead of a nil-pointer panic during a request. With the healthy fake, GET returns the seeded note and POST creates n1 with the fixed timestamp 2026-01-02T03:04:05Z, which is why the body is stable enough to compare. The fake records every call, so the test can assert that the handler asked for n7 and inserted n1 without inspecting private state. The broken fake returns a dial error: the handler logs the cause through its injected logger (the time attribute is dropped to keep output stable) and the client receives only a generic 500 body."},{"body":"httpapi declares NoteService with exactly the two methods its handlers call, and notes declares Store with exactly what the service calls. The concrete types never mention these interfaces; Go satisfies them implicitly, which is what lets the consumer own the definition. That keeps interfaces small, so a fake is a dozen lines, and it keeps the import arrow pointing from adapter to domain. A provider-side interface with twenty methods that mirrors the store invites fakes that panic on the eighteen methods nobody meant to call. Constructors accept interfaces and return concrete types: NewService returns *Service, and each caller decides which slice of it to depend on. A one-line assertion keeps the provider and the consumer from drifting apart silently.","code":"// internal/httpapi/handler.go: the consumer declares what it calls.\ntype NoteService interface {\n\tCreate(ctx context.Context, title string) (notes.Note, error)\n\tGet(ctx context.Context, id string) (notes.Note, error)\n}\n\n// cmd/api/main.go or a test: break the build if the provider drifts.\nvar _ httpapi.NoteService = (*notes.Service)(nil)","language":"go","title":"Declare the interface where it is consumed","walkthrough":"This fragment belongs in the module from the layout lesson and compiles there, not on its own. The blank-identifier assignment converts a typed nil *notes.Service to httpapi.NoteService at compile time; if someone renames Get or changes its signature, the build fails at this line with a message naming the missing method, instead of failing later where the router is wired. Exporting the interface is what makes this assertion possible from main."},{"body":"A constructor is the right place to reject an incomplete graph, because it runs once at startup where a clear error is cheap. One Go subtlety limits that check: a nil *MemoryStore stored in a Store interface is not equal to nil, so the guard only catches dependencies that were never assigned. For tests, prefer a small hand-written fake over a mocking framework: a map for state, an err field to inject failure and a calls slice to observe what happened. Assert outcomes such as the status, the body and the effect on the fake, not the exact order of every internal call, or the test breaks on every refactor. Build a new fake and a new router per test case; this fake has no mutex, which is fine only because nothing shares it. The API-tests lesson turns this into a full table.","title":"Constructors validate wiring; fakes control the world"},{"body":"When a pull request adds a handler, three questions catch most dependency problems. Can the handler be constructed in a test without a network, a file or an environment variable? Does its struct list every collaborator it uses, including time and randomness? Is each interface field declared in the consuming package with only the methods it calls? If any answer is no, the missing piece is usually a constructor argument. The cost is a few more lines in main; the benefit is that every test from here on builds the real router with controlled edges.","title":"Review questions for a new handler"}],"takeaway":"Build handlers from a struct whose fields are small interfaces declared by the consumer, inject the clock and ID source too, and let tests pass a fake store through the same constructor production uses.","title":"Give Gin handlers their dependencies through a struct, not globals or context keys","unitID":"gin-project","wrongAnswers":["internal/notes, next to the concrete Service type","A shared interfaces package that every package imports"]},{"conceptTag":"gin.crud-resource","designGuide":{"cautions":["Pointer DTOs cannot distinguish an omitted field from an explicit null.","A store-level lock does not prevent lost updates between two clients."],"cost":"Two DTOs per resource and an Update callback in the store; worth it as soon as a client sends partial updates.","family":"gin","flow":["Write the route contract","Guard invariants in store","Bind PUT and PATCH apart","Test every status row"],"ratings":[],"strengths":["Clients can rely on Location, 204 and 409 meaning the same thing everywhere.","Uniqueness is enforced where the data lives, so no check-then-write race.","PATCH can set false and empty values without ambiguity."]},"hint":"Compare what a plain bool holds when the field is missing and when it is false.","id":"gin.crud-resource","introduction":"CRUD looks like boilerplate until a client depends on the details: whether create tells it where the new note lives, whether PUT without a body field clears it, whether PATCH with false can unpin a note, and whether a duplicate title is a 400 or a 409. This lesson pins down each answer for the notes resource, on top of a mutex-protected in-memory store behind the Store interface.","nuance":"With a plain bool an omitted field and an explicit false both decode to false, so the handler cannot tell \"leave it\" from \"unpin it\". A nil pointer marks absence.","objective":"Implement create, read, replace, patch and delete for notes with correct status codes, a Location header and presence-aware PATCH fields.","question":"A PATCH request sends {\"pinned\":false}. Why does patchNote use *bool instead of bool for Pinned?","references":["https://www.rfc-editor.org/rfc/rfc9110#section-9.3.4","https://www.rfc-editor.org/rfc/rfc5789","https://www.rfc-editor.org/rfc/rfc7396","https://pkg.go.dev/sync#RWMutex"],"reviewAnswer":"nil means absent, so false and \"\" stay settable","reviewPrompt":"Why pointer fields in a PATCH DTO?","sections":[{"body":"A resource API is a promise about methods, paths, statuses and headers, and clients code against every part of it. Writing the table first exposes decisions that are easy to fudge in code: who assigns IDs, what a partial update means and which errors exist. Here the server assigns IDs, so POST creates and PUT only replaces an existing note. Titles are unique, which gives the store a real invariant to protect and the API a real reason to answer 409.","code":"POST   /notes        create      201 Created + Location: /notes/{id} + body\n                                 400 unreadable body, 409 title already used\nGET    /notes/{id}   read        200 + body, 404 unknown id\nPUT    /notes/{id}   replace     200 + body, 400 incomplete body, 404, 409\nPATCH  /notes/{id}   merge       200 + body, 400 invalid field, 404, 409\nDELETE /notes/{id}   remove      204 No Content (empty body), 404 unknown id","language":"text","title":"Write the contract before the handlers","walkthrough":"Read each row as a test case. 201 always comes with a Location header pointing at the new resource, so clients never guess URLs. 204 means success with no body: the net/http server rejects a body write for it with http.ErrBodyNotAllowed, and Gin renderers skip the body for that status. 404 and 409 come from domain errors, not from handler logic. 400 is for input the adapter cannot accept; the binding-limits lesson already covers size limits and strict decoding, so this lesson only uses binding tags."},{"body":"The store keeps two maps that must always agree: notes by ID and a unique index from title to ID. Every method takes the mutex, and Update runs a caller-supplied function on a copy while holding the write lock, so read, modify and write happen as one step. Handlers translate HTTP into store calls and use a small writeError helper for now. The program replays a short session against the API and prints each status, Location header and body.","code":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// ---- internal/notes ----\n\ntype Note struct {\n\tID     string `json:\"id\"`\n\tTitle  string `json:\"title\"`\n\tBody   string `json:\"body\"`\n\tPinned bool   `json:\"pinned\"`\n}\n\nvar (\n\tErrNotFound = errors.New(\"notes: not found\")\n\tErrConflict = errors.New(\"notes: title already used\")\n)\n\ntype Store interface {\n\tCreate(ctx context.Context, n Note) error\n\tGet(ctx context.Context, id string) (Note, error)\n\t// Update runs fn on a copy under the store's lock and saves the result.\n\tUpdate(ctx context.Context, id string, fn func(*Note) error) (Note, error)\n\tDelete(ctx context.Context, id string) error\n}\n\n// ---- internal/store ----\n\ntype MemoryStore struct {\n\tmu      sync.RWMutex\n\tbyID    map[string]Note\n\tbyTitle map[string]string // unique index: title -> id\n}\n\nfunc NewMemoryStore() *MemoryStore {\n\treturn &MemoryStore{byID: map[string]Note{}, byTitle: map[string]string{}}\n}\n\nfunc (m *MemoryStore) Create(_ context.Context, n Note) error {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tif _, taken := m.byTitle[n.Title]; taken {\n\t\treturn ErrConflict\n\t}\n\tm.byID[n.ID] = n\n\tm.byTitle[n.Title] = n.ID\n\treturn nil\n}\n\nfunc (m *MemoryStore) Get(_ context.Context, id string) (Note, error) {\n\tm.mu.RLock()\n\tdefer m.mu.RUnlock()\n\tn, ok := m.byID[id]\n\tif !ok {\n\t\treturn Note{}, ErrNotFound\n\t}\n\treturn n, nil // a copy: callers cannot mutate the map behind the lock\n}\n\nfunc (m *MemoryStore) Update(_ context.Context, id string, fn func(*Note) error) (Note, error) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\told, ok := m.byID[id]\n\tif !ok {\n\t\treturn Note{}, ErrNotFound\n\t}\n\tnext := old\n\tif err := fn(&next); err != nil {\n\t\treturn Note{}, err\n\t}\n\tnext.ID = old.ID // the URL owns the identity, not the body\n\tif owner, taken := m.byTitle[next.Title]; taken && owner != id {\n\t\treturn Note{}, ErrConflict\n\t}\n\tdelete(m.byTitle, old.Title)\n\tm.byTitle[next.Title] = id\n\tm.byID[id] = next\n\treturn next, nil\n}\n\nfunc (m *MemoryStore) Delete(_ context.Context, id string) error {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tn, ok := m.byID[id]\n\tif !ok {\n\t\treturn ErrNotFound\n\t}\n\tdelete(m.byTitle, n.Title)\n\tdelete(m.byID, id)\n\treturn nil\n}\n\n// ---- internal/httpapi ----\n\ntype Handler struct {\n\tstore  Store\n\tnextID func() string\n}\n\nfunc (h *Handler) Register(r gin.IRouter) {\n\tr.POST(\"/notes\", h.create)\n\tr.GET(\"/notes/:id\", h.get)\n\tr.PUT(\"/notes/:id\", h.replace)\n\tr.PATCH(\"/notes/:id\", h.patch)\n\tr.DELETE(\"/notes/:id\", h.remove)\n}\n\n// putNote is a full representation: an absent field means its zero value.\ntype putNote struct {\n\tTitle  string `json:\"title\" binding:\"required,max=80\"`\n\tBody   string `json:\"body\" binding:\"max=2000\"`\n\tPinned bool   `json:\"pinned\"`\n}\n\n// patchNote uses pointers: nil means \"not sent\", so false and \"\" stay expressible.\ntype patchNote struct {\n\tTitle  *string `json:\"title\" binding:\"omitempty,min=1,max=80\"`\n\tBody   *string `json:\"body\" binding:\"omitempty,max=2000\"`\n\tPinned *bool   `json:\"pinned\"`\n}\n\nfunc (h *Handler) create(c *gin.Context) {\n\tvar in putNote\n\tif err := c.ShouldBindJSON(&in); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"invalid note\"})\n\t\treturn\n\t}\n\tn := Note{ID: h.nextID(), Title: in.Title, Body: in.Body, Pinned: in.Pinned}\n\tif err := h.store.Create(c.Request.Context(), n); err != nil {\n\t\twriteError(c, err)\n\t\treturn\n\t}\n\tc.Header(\"Location\", \"/notes/\"+n.ID)\n\tc.JSON(http.StatusCreated, n)\n}\n\nfunc (h *Handler) get(c *gin.Context) {\n\tn, err := h.store.Get(c.Request.Context(), c.Param(\"id\"))\n\tif err != nil {\n\t\twriteError(c, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, n)\n}\n\nfunc (h *Handler) replace(c *gin.Context) {\n\tvar in putNote\n\tif err := c.ShouldBindJSON(&in); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"invalid note\"})\n\t\treturn\n\t}\n\tn, err := h.store.Update(c.Request.Context(), c.Param(\"id\"), func(n *Note) error {\n\t\tn.Title, n.Body, n.Pinned = in.Title, in.Body, in.Pinned\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\twriteError(c, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, n)\n}\n\nfunc (h *Handler) patch(c *gin.Context) {\n\tvar in patchNote\n\tif err := c.ShouldBindJSON(&in); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"invalid patch\"})\n\t\treturn\n\t}\n\tn, err := h.store.Update(c.Request.Context(), c.Param(\"id\"), func(n *Note) error {\n\t\tif in.Title != nil {\n\t\t\tn.Title = *in.Title\n\t\t}\n\t\tif in.Body != nil {\n\t\t\tn.Body = *in.Body\n\t\t}\n\t\tif in.Pinned != nil {\n\t\t\tn.Pinned = *in.Pinned\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\twriteError(c, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusOK, n)\n}\n\nfunc (h *Handler) remove(c *gin.Context) {\n\tif err := h.store.Delete(c.Request.Context(), c.Param(\"id\")); err != nil {\n\t\twriteError(c, err)\n\t\treturn\n\t}\n\tc.Status(http.StatusNoContent)\n}\n\n// writeError is a stopgap; the problem-details lesson moves this into one middleware.\nfunc writeError(c *gin.Context, err error) {\n\tswitch {\n\tcase errors.Is(err, ErrNotFound):\n\t\tc.JSON(http.StatusNotFound, gin.H{\"error\": \"note not found\"})\n\tcase errors.Is(err, ErrConflict):\n\t\tc.JSON(http.StatusConflict, gin.H{\"error\": \"title already used\"})\n\tdefault:\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"internal error\"})\n\t}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tseq := 0\n\th := &Handler{store: NewMemoryStore(), nextID: func() string { seq++; return fmt.Sprintf(\"n%d\", seq) }}\n\tr := gin.New()\n\th.Register(r)\n\n\tsteps := []struct{ method, path, body string }{\n\t\t{\"POST\", \"/notes\", `{\"title\":\"Groceries\",\"body\":\"milk, eggs\"}`},\n\t\t{\"POST\", \"/notes\", `{\"title\":\"Groceries\"}`},\n\t\t{\"PATCH\", \"/notes/n1\", `{\"pinned\":true}`},\n\t\t{\"PUT\", \"/notes/n1\", `{\"title\":\"Groceries\"}`},\n\t\t{\"POST\", \"/notes\", `{\"title\":\"Errands\"}`},\n\t\t{\"PATCH\", \"/notes/n3\", `{\"title\":\"\"}`},\n\t\t{\"PATCH\", \"/notes/n3\", `{\"title\":\"Groceries\"}`},\n\t\t{\"DELETE\", \"/notes/n1\", \"\"},\n\t\t{\"GET\", \"/notes/n1\", \"\"},\n\t}\n\tfor _, s := range steps {\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, httptest.NewRequest(s.method, s.path, strings.NewReader(s.body)))\n\t\tline := fmt.Sprintf(\"%s %s -> %d\", s.method, s.path, w.Code)\n\t\tif loc := w.Header().Get(\"Location\"); loc != \"\" {\n\t\t\tline += \" Location: \" + loc\n\t\t}\n\t\tif w.Body.Len() > 0 {\n\t\t\tline += \" \" + w.Body.String()\n\t\t}\n\t\tfmt.Println(line)\n\t}\n}","language":"go","title":"Five routes over one locked store","walkthrough":"The first POST returns 201 with Location: /notes/n1. The duplicate POST gets 409 from the unique index; it still consumed ID n2 because the handler allocates the ID before inserting, just as a database sequence would, so the next note is n3. PATCH with {\"pinned\":true} changes one field and keeps the body. PUT with only a title replaces the whole representation, so body becomes \"\" and pinned becomes false. PATCH with an empty title is rejected with 400 because the field is present and fails min=1. Renaming n3 to an existing title is 409. DELETE answers 204 with no body, and the following GET is 404."},{"body":"putNote has plain fields because PUT sends a complete representation: anything absent takes its zero value, and title is required. patchNote uses pointers because PATCH must tell \"not sent\" from \"set to the zero value\"; with a plain bool, {\"pinned\":false} and {} decode identically. Validator tags cooperate with this: omitempty on a pointer skips only a nil pointer, so a present empty string is still checked against min=1, which is the 400 in the output. One limit remains: JSON null also leaves a pointer nil, so this DTO cannot express \"clear this field\" the way JSON Merge Patch (RFC 7396) does, where null removes a member. If clients need that, decode into map[string]json.RawMessage or a small optional type that records both presence and null. Whichever you choose, document it and accept application/merge-patch+json if you claim merge-patch semantics.","title":"PUT replaces, PATCH merges, pointers carry presence"},{"body":"The mutex protects an invariant, not just a map: byID and byTitle change together or not at all. That is why the uniqueness check lives inside Create and Update rather than in a handler that first asks \"is this title free?\" and then writes; between those two calls another request could take the title. In PostgreSQL the same guarantee comes from a unique index, and the adapter maps SQLSTATE 23505 (unique_violation) to notes.ErrConflict. Get returns a copy of the struct, so callers cannot mutate stored state behind the lock; a Note with slice fields would need a deep copy. The function passed to Update runs under the write lock, so it must be quick and free of I/O. What the lock cannot fix is two clients that each read version one and write back their own edit; that lost update spans two requests and is the subject of the optimistic-concurrency lesson.","title":"What the lock protects, and what it cannot"},{"body":"Should POST return 200? No: 201 plus Location tells the client a new resource exists and where. Can Location be relative? Yes, RFC 9110 allows a URI reference, resolved against the request URL. Is a second DELETE returning 404 a violation of idempotency? No: idempotency is about the effect on server state, which is the same after one or two deletes; the responses may differ. Should PUT to an unknown ID create it? Only when clients choose IDs; then it returns 201. Is a duplicate title 400 or 409? The request is well formed but conflicts with current state, so 409. Never answer 200 with an error object in the body. Test each row of the contract through ServeHTTP, including the Location header and the empty 204 body.","title":"Status-code questions reviewers ask"}],"takeaway":"Return 201 with Location on create and 204 with no body on delete, derive 404 and 409 from domain errors, treat PUT as full replacement and give PATCH presence-aware pointer fields.","title":"Full CRUD on one resource: exact status codes, a Location header and PUT versus PATCH","unitID":"gin-project","wrongAnswers":["Pointers make JSON decoding faster for small structs","Gin binding cannot decode JSON into plain bool fields"]},{"conceptTag":"gin.pagination-filtering","designGuide":{"cautions":["Cursors are readable and forgeable; validate them like any input.","No random page access or cheap total count with keyset pagination."],"cost":"A cursor type, a composite index and an allow-list per sortable field; filters and sorts must be designed, not exposed column by column.","family":"gin","flow":["Parse and allow-list query","Order by key plus id","Fetch limit plus one","Return opaque cursor"],"ratings":[],"strengths":["Pages stay correct while rows are inserted or deleted.","Each page costs about the same with a composite index.","Sort input can never become SQL text."]},"hint":"Think about what decides the order of two rows with equal timestamps.","id":"gin.pagination-filtering","introduction":"A GET /notes that returns every row is fine with ten notes and an outage with ten million. Pagination bounds the work per request, but the naive offset version skips or repeats rows when data changes between pages, and a sort parameter pasted into SQL is an injection point. This lesson adds listing, filtering and sorting to the notes API with both failure modes closed.","nuance":"Without a unique last sort column the order of ties is unspecified, so a page that ends between them leaves the next query no exact point to resume from.","objective":"Serve stable pages of notes with keyset cursors, cap the page size and accept only allow-listed filter and sort parameters.","question":"Two notes share the same created_at value. Why must both the cursor and ORDER BY also include the note ID?","references":["https://www.postgresql.org/docs/current/queries-limit.html","https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html","https://pkg.go.dev/encoding/base64#RawURLEncoding","https://pkg.go.dev/net/url#ParseQuery"],"reviewAnswer":"Ties make page boundaries skip or repeat rows","reviewPrompt":"Why add id to every sort order?","sections":[{"body":"OFFSET 40 LIMIT 20 asks the database to produce sixty rows and throw away forty, so deep pages get slower as the table grows. Worse, positions are not stable: when a note is inserted at the top between two requests, every row shifts down by one and the next page repeats a note; a delete makes one disappear. Keyset pagination remembers the sort key and ID of the last row returned and asks for rows strictly after that point. With an index on those columns each page costs about the same, and concurrent inserts cannot shift a boundary that is a value rather than a count. The trade-offs are honest ones: no jumping to page 37 and no cheap total count. Offset remains acceptable for small, rarely changing admin tables.","title":"Offset pages drift; key-based pages do not"},{"body":"parseList is the gate: it rejects malformed query strings and unknown parameters, bounds the limit, checks the sort against the allow-list and decodes the cursor. The store sorts by the chosen key with the ID as tie-breaker, skips everything up to the cursor, and fetches one extra row to learn whether another page exists. The program first shows offset drift on the same data, then walks the cursor pages while a new note arrives, and finally sends invalid queries.","code":"package main\n\nimport (\n\t\"cmp\"\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"slices\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype Note struct {\n\tID        string    `json:\"id\"`\n\tTitle     string    `json:\"title\"`\n\tPinned    bool      `json:\"pinned\"`\n\tCreatedAt time.Time `json:\"createdAt\"`\n}\n\nconst (\n\tdefaultLimit = 20\n\tmaxLimit     = 100\n)\n\n// The sort allow-list: public name -> direction and key. Nothing else is accepted.\ntype sortSpec struct {\n\tdesc bool\n\tkey  func(Note) string\n}\n\nfunc createdKey(n Note) string {\n\t// Fixed width, UTC, microseconds: compares correctly as a string.\n\treturn n.CreatedAt.UTC().Format(\"2006-01-02T15:04:05.000000Z\")\n}\n\nvar sorts = map[string]sortSpec{\n\t\"created\":  {desc: false, key: createdKey},\n\t\"-created\": {desc: true, key: createdKey},\n\t\"title\":    {desc: false, key: func(n Note) string { return n.Title }},\n}\n\ntype cursor struct {\n\tSort string `json:\"s\"`\n\tKey  string `json:\"k\"`\n\tID   string `json:\"id\"`\n}\n\nfunc encodeCursor(c cursor) string {\n\tb, _ := json.Marshal(c)\n\treturn base64.RawURLEncoding.EncodeToString(b)\n}\n\nfunc decodeCursor(s string) (cursor, error) {\n\tvar c cursor\n\tb, err := base64.RawURLEncoding.DecodeString(s)\n\tif err != nil || json.Unmarshal(b, &c) != nil || c.ID == \"\" {\n\t\treturn cursor{}, errors.New(\"cursor is invalid\")\n\t}\n\treturn c, nil\n}\n\n// compare orders by (key, id); the id tie-breaker makes the order total.\nfunc compare(s sortSpec, aKey, aID, bKey, bID string) int {\n\tc := cmp.Or(cmp.Compare(aKey, bKey), cmp.Compare(aID, bID))\n\tif s.desc {\n\t\treturn -c\n\t}\n\treturn c\n}\n\ntype listQuery struct {\n\tlimit  int\n\tsort   string\n\tpinned *bool\n\tafter  *cursor\n}\n\nfunc parseList(rawQuery string) (listQuery, error) {\n\tq, err := url.ParseQuery(rawQuery)\n\tif err != nil {\n\t\treturn listQuery{}, errors.New(\"query string is malformed\")\n\t}\n\tallowed := map[string]bool{\"limit\": true, \"cursor\": true, \"sort\": true, \"pinned\": true}\n\tfor _, k := range slices.Sorted(maps.Keys(q)) {\n\t\tif !allowed[k] {\n\t\t\treturn listQuery{}, fmt.Errorf(\"unknown query parameter: %s\", k)\n\t\t}\n\t}\n\tlq := listQuery{limit: defaultLimit, sort: \"-created\"}\n\tif v := q.Get(\"limit\"); v != \"\" {\n\t\tn, err := strconv.Atoi(v)\n\t\tif err != nil || n < 1 {\n\t\t\treturn listQuery{}, errors.New(\"limit must be a positive integer\")\n\t\t}\n\t\tlq.limit = min(n, maxLimit)\n\t}\n\tif v := q.Get(\"sort\"); v != \"\" {\n\t\tif _, ok := sorts[v]; !ok {\n\t\t\tnames := slices.Sorted(maps.Keys(sorts))\n\t\t\treturn listQuery{}, fmt.Errorf(\"sort must be one of %s\", strings.Join(names, \", \"))\n\t\t}\n\t\tlq.sort = v\n\t}\n\tif v := q.Get(\"pinned\"); v != \"\" {\n\t\tb, err := strconv.ParseBool(v)\n\t\tif err != nil {\n\t\t\treturn listQuery{}, errors.New(\"pinned must be true or false\")\n\t\t}\n\t\tlq.pinned = &b\n\t}\n\tif v := q.Get(\"cursor\"); v != \"\" {\n\t\tc, err := decodeCursor(v)\n\t\tif err != nil {\n\t\t\treturn listQuery{}, err\n\t\t}\n\t\tif q.Get(\"sort\") != \"\" && c.Sort != lq.sort {\n\t\t\treturn listQuery{}, errors.New(\"cursor was issued for a different sort\")\n\t\t}\n\t\tlq.sort, lq.after = c.Sort, &c\n\t}\n\treturn lq, nil\n}\n\ntype MemoryStore struct {\n\tmu    sync.RWMutex\n\tnotes []Note\n}\n\nfunc (m *MemoryStore) Add(n Note) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tm.notes = append(m.notes, n)\n}\n\n// List returns one page and the cursor for the next one (\"\" when there is none).\nfunc (m *MemoryStore) List(q listQuery) ([]Note, string) {\n\tm.mu.RLock()\n\tall := slices.Clone(m.notes)\n\tm.mu.RUnlock()\n\n\tspec := sorts[q.sort]\n\tslices.SortFunc(all, func(a, b Note) int {\n\t\treturn compare(spec, spec.key(a), a.ID, spec.key(b), b.ID)\n\t})\n\tpage := make([]Note, 0, q.limit+1)\n\tfor _, n := range all {\n\t\tif q.pinned != nil && n.Pinned != *q.pinned {\n\t\t\tcontinue\n\t\t}\n\t\tif q.after != nil && compare(spec, spec.key(n), n.ID, q.after.Key, q.after.ID) <= 0 {\n\t\t\tcontinue\n\t\t}\n\t\tpage = append(page, n)\n\t\tif len(page) == q.limit+1 { // one extra row tells us a next page exists\n\t\t\tbreak\n\t\t}\n\t}\n\tif len(page) <= q.limit {\n\t\treturn page, \"\"\n\t}\n\tpage = page[:q.limit]\n\tlast := page[len(page)-1]\n\treturn page, encodeCursor(cursor{Sort: q.sort, Key: spec.key(last), ID: last.ID})\n}\n\ntype pageBody struct {\n\tItems      []Note `json:\"items\"`\n\tLimit      int    `json:\"limit\"`\n\tNextCursor string `json:\"nextCursor,omitempty\"`\n}\n\nfunc newRouter(st *MemoryStore) *gin.Engine {\n\tr := gin.New()\n\tr.GET(\"/notes\", func(c *gin.Context) {\n\t\tq, err := parseList(c.Request.URL.RawQuery)\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\t\treturn\n\t\t}\n\t\titems, next := st.List(q)\n\t\tc.JSON(http.StatusOK, pageBody{Items: items, Limit: q.limit, NextCursor: next})\n\t})\n\treturn r\n}\n\nfunc at(min int) time.Time { return time.Date(2026, 3, 1, 9, min, 0, 0, time.UTC) }\n\nfunc seed() *MemoryStore {\n\tst := &MemoryStore{}\n\tst.Add(Note{ID: \"n1\", Title: \"Alpha\", Pinned: true, CreatedAt: at(0)})\n\tst.Add(Note{ID: \"n2\", Title: \"Bravo\", CreatedAt: at(5)})\n\tst.Add(Note{ID: \"n3\", Title: \"Charlie\", CreatedAt: at(5)}) // same instant as n2\n\tst.Add(Note{ID: \"n4\", Title: \"Delta\", Pinned: true, CreatedAt: at(10)})\n\tst.Add(Note{ID: \"n5\", Title: \"Echo\", CreatedAt: at(15)})\n\treturn st\n}\n\nfunc get(r http.Handler, target string) (int, pageBody, string) {\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil))\n\tvar p pageBody\n\t_ = json.Unmarshal(w.Body.Bytes(), &p)\n\treturn w.Code, p, w.Body.String()\n}\n\nfunc ids(ns []Note) string {\n\tout := make([]string, len(ns))\n\tfor i, n := range ns {\n\t\tout[i] = n.ID\n\t}\n\treturn \"[\" + strings.Join(out, \" \") + \"]\"\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\n\t// Offset pagination: a write between two page requests shifts every row.\n\tst := seed()\n\tq := listQuery{limit: 100, sort: \"-created\"}\n\tall, _ := st.List(q)\n\tpage1 := all[0:2]\n\tst.Add(Note{ID: \"n6\", Title: \"Foxtrot\", CreatedAt: at(20)})\n\tall, _ = st.List(q)\n\tfmt.Println(\"offset:\", ids(page1), \"then\", ids(all[2:4]))\n\n\t// Cursor pagination: the next page starts after the last key, not at a row count.\n\tst = seed()\n\tr := newRouter(st)\n\t_, p, _ := get(r, \"/notes?limit=2\")\n\tfmt.Println(\"cursor page 1:\", ids(p.Items))\n\traw, _ := base64.RawURLEncoding.DecodeString(p.NextCursor)\n\tfmt.Println(\"cursor decodes to\", string(raw))\n\tst.Add(Note{ID: \"n6\", Title: \"Foxtrot\", CreatedAt: at(20)})\n\tfor page := 2; p.NextCursor != \"\"; page++ {\n\t\t_, p, _ = get(r, \"/notes?limit=2&cursor=\"+p.NextCursor)\n\t\tfmt.Printf(\"cursor page %d: %s more=%t\\n\", page, ids(p.Items), p.NextCursor != \"\")\n\t}\n\n\t_, p, _ = get(r, \"/notes?pinned=true&sort=title\")\n\tfmt.Println(\"pinned by title:\", ids(p.Items))\n\t_, p, _ = get(r, \"/notes?limit=500\")\n\tfmt.Println(\"limit=500 ->\", p.Limit)\n\tfor _, target := range []string{\"/notes?sort=password\", \"/notes?pined=true\", \"/notes?sort=title;DROP\"} {\n\t\tcode, _, body := get(r, target)\n\t\tfmt.Println(target, code, body)\n\t}\n}","language":"go","title":"List, filter and sort the notes","walkthrough":"The offset line returns n5 and n4, then n4 again after n6 is inserted, the classic duplicate. The cursor walk returns n5 n4, then n3 n2, then n1 with more=false; the new n6 does not disturb later pages because it sorts before the cursor and will appear on a fresh first page. n2 and n3 share a timestamp, and the ID breaks the tie deterministically. The decoded cursor is just JSON with the sort, the last key and the last ID. pinned=true with sort=title returns n1 n4, limit=500 is clamped to 100 and echoed back, and the three bad queries each get a 400 naming the problem. The last one matters: URL.Query, and therefore c.Query, silently drops pairs containing a semicolon, while url.ParseQuery reports the error so the API can reject it."},{"body":"If two rows compare equal on the sort key, neither SQL nor slices.SortFunc promises their relative order, and it can differ between two executions of the same query. A page that ends between tied rows then gives the next request no exact place to resume, so a row is skipped or repeated. Appending a unique column, the ID, to every sort order makes the order total, and the cursor must carry both values. Support it with a composite index such as (created_at, id). Watch the key format too. The in-memory model compares keys as strings, so timestamps are formatted at fixed width in UTC. PostgreSQL stores timestamps with microsecond precision while Go keeps nanoseconds, so truncate to microseconds before writing; otherwise the key in the cursor never equals the stored value and the boundary comparison is subtly wrong.","title":"A total order needs a tie-breaker"},{"body":"Calling the cursor opaque is a contract with clients: they must pass it back unchanged and never build one, so you can change its format later. It is not a security property. base64url is an encoding, and the program decodes the cursor in one line. Treat a cursor like any other input: decode it, validate every field, reject it if it was issued for a different sort, and never place in it anything the caller could not already see. If tampering matters, append an HMAC computed with a server key and verify it before use. Authorization must not depend on the cursor; the owner filter comes from the authenticated request on every page, so a forged cursor can at most move the starting point within the caller's own notes. For the limit, pick a default, clamp at a maximum, echo the effective value and reject zero or non-numeric input with 400.","title":"Opaque cursors are encoded, not secret"},{"body":"Reject unknown query parameters: a client that types pined=true and silently receives every note has a bug that nobody will notice. For sorting, the allow-list is not just validation; it is the only bridge between user input and SQL text. A placeholder binds a value, never an identifier, so ORDER BY $1 sorts every row by the same constant and no error appears. Interpolating the column name instead is SQL injection. Map each public sort name to a constant clause and build the query from those constants plus placeholders.","code":"// Public sort name -> constant SQL. Client input selects a key; it never becomes SQL text.\nvar orderBy = map[string]string{\n\t\"created\":  \"created_at ASC, id ASC\",\n\t\"-created\": \"created_at DESC, id DESC\",\n\t\"title\":    \"title ASC, id ASC\",\n}\n\nvar afterCursor = map[string]string{\n\t\"created\":  \"(created_at, id) > ($2, $3)\",\n\t\"-created\": \"(created_at, id) < ($2, $3)\",\n\t\"title\":    \"(title, id) > ($2, $3)\",\n}\n\n// listSQL assumes q came from parseList, so q.sort is a key of orderBy.\nfunc listSQL(ownerID string, q listQuery) (string, []any) {\n\tquery := \"SELECT id, title, pinned, created_at FROM notes WHERE owner_id = $1\"\n\targs := []any{ownerID}\n\tif q.after != nil {\n\t\tquery += \" AND \" + afterCursor[q.sort]\n\t\targs = append(args, q.after.Key, q.after.ID)\n\t}\n\tif q.pinned != nil {\n\t\targs = append(args, *q.pinned)\n\t\tquery += fmt.Sprintf(\" AND pinned = $%d\", len(args))\n\t}\n\targs = append(args, q.limit+1) // one extra row reveals whether a next page exists\n\tquery += fmt.Sprintf(\" ORDER BY %s LIMIT $%d\", orderBy[q.sort], len(args))\n\treturn query, args\n}","language":"go","title":"Allow-lists for filters and sorts, constants for SQL","walkthrough":"This fragment is the PostgreSQL side of the same API; run it against a database in your own environment. orderBy and afterCursor are the allow-list expressed as SQL constants, and parseList has already guaranteed that q.sort is one of their keys. Only placeholder numbers are formatted into the string; every client-supplied value, including the cursor key and ID, travels in args. The row comparison (created_at, id) < ($2, $3) matches the ORDER BY direction and can use the composite index. Text keys such as title compare with the column collation in SQL, which may differ from the byte order the in-memory model uses."}],"takeaway":"Page by the last (sort key, id) in a validated opaque cursor, cap the limit, reject unknown parameters, and map allow-listed sort names to constant SQL instead of interpolating them.","title":"Paginate with opaque cursors, a bounded limit and a total order; filter only through allow-lists","unitID":"gin-project","wrongAnswers":["The ID makes the base64 cursor harder to forge","PostgreSQL rejects ORDER BY on a non-unique column"]},{"conceptTag":"gin.problem-details","designGuide":{"cautions":["An unmapped new error kind silently becomes a 500 unless a test checks coverage.","A handler that writes before failing leaves the middleware able only to log."],"cost":"A small taxonomy, one mapping function and a middleware; existing handlers change from writing JSON to returning after c.Error.","family":"gin","flow":["Define domain errors","Handlers call c.Error","Map once in middleware","Render problem+json"],"ratings":[],"strengths":["Clients parse one documented error shape and branch on a stable type URI.","Internal error text stays in logs by construction.","Adding a route cannot add a new, undocumented error format."]},"hint":"The domain package does not import net/http.","id":"gin.problem-details","introduction":"By now each notes handler writes its own gin.H{\"error\": ...}. Clients parse several shapes, someone eventually returns err.Error() and leaks a database host, and nobody can list which statuses an endpoint produces. RFC 9457 supplies a standard envelope. A taxonomy in the domain and one mapping function supply the discipline. The errors-testing lesson established one response owner; this lesson gives that owner a contract.","nuance":"One mapping middleware means one table to review, one envelope for clients and no handler that can forget to hide an internal error's text.","objective":"Return application/problem+json for every failure by mapping a small domain error taxonomy to HTTP statuses in a single Gin middleware.","question":"In the notes API, where should a wrapped notes.ErrConflict become a 409 application/problem+json response?","references":["https://www.rfc-editor.org/rfc/rfc9457","https://pkg.go.dev/errors#AsType","https://pkg.go.dev/github.com/gin-gonic/gin#Context.Error","https://cheatsheetseries.owasp.org/cheatsheets/Error_Handling_Cheat_Sheet.html"],"reviewAnswer":"One error middleware, using errors.Is and errors.As","reviewPrompt":"Who turns domain errors into HTTP?","sections":[{"body":"The notes package defines what can go wrong in business terms: ErrNotFound, ErrConflict and ErrForbidden as sentinel values, and *ValidationError as a type that carries field-level reasons. Services wrap them with fmt.Errorf and %w to add context such as the note ID, and the wrapped chain still matches. The domain does not import net/http and does not know that 404 exists; a CLI or a queue worker can use the same errors. Malformed JSON is different: the domain never sees request bytes, so that error belongs to httpapi. Keep the taxonomy small. Four or five kinds cover most APIs, and each new kind is a decision about how clients should react, not a new spelling of \"something failed\".","title":"Name failures in the domain, not in HTTP"},{"body":"Every handler now ends a failure with c.Error(err) and returns; none of them chooses a status. The problems middleware calls c.Next, looks at the last recorded error and asks problemFor, the only mapping table in the service, for a Problem. It logs the cause of server errors, skips writing if a handler already committed a response, and renders application/problem+json. NoRoute records ErrNotFound, so unknown paths get the same envelope.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// ---- internal/notes: the error taxonomy. No HTTP here. ----\n\nvar (\n\tErrNotFound  = errors.New(\"notes: not found\")\n\tErrConflict  = errors.New(\"notes: conflicts with current state\")\n\tErrForbidden = errors.New(\"notes: caller may not do this\")\n)\n\ntype FieldError struct {\n\tField  string `json:\"field\"`\n\tReason string `json:\"reason\"`\n}\n\n// ValidationError carries messages written for clients; it is safe to expose.\ntype ValidationError struct{ Fields []FieldError }\n\nfunc (e *ValidationError) Error() string {\n\treturn fmt.Sprintf(\"notes: %d invalid fields\", len(e.Fields))\n}\n\n// ---- internal/httpapi: the one place that maps errors to HTTP. ----\n\nvar errMalformedBody = errors.New(\"httpapi: malformed body\")\n\ntype Problem struct {\n\tType     string       `json:\"type\"`\n\tTitle    string       `json:\"title\"`\n\tStatus   int          `json:\"status\"`\n\tDetail   string       `json:\"detail,omitempty\"`\n\tInstance string       `json:\"instance,omitempty\"`\n\tErrors   []FieldError `json:\"errors,omitempty\"`\n}\n\nconst typeBase = \"https://example.com/problems/\"\n\nfunc problemFor(err error) Problem {\n\tif ve, ok := errors.AsType[*ValidationError](err); ok {\n\t\treturn Problem{Type: typeBase + \"validation\", Title: \"Invalid note\", Status: http.StatusUnprocessableEntity,\n\t\t\tDetail: \"One or more fields are invalid.\", Errors: ve.Fields}\n\t}\n\tswitch {\n\tcase errors.Is(err, errMalformedBody):\n\t\treturn Problem{Type: typeBase + \"malformed-body\", Title: \"Malformed request body\", Status: http.StatusBadRequest}\n\tcase errors.Is(err, ErrNotFound):\n\t\treturn Problem{Type: typeBase + \"not-found\", Title: \"Note not found\", Status: http.StatusNotFound}\n\tcase errors.Is(err, ErrConflict):\n\t\treturn Problem{Type: typeBase + \"conflict\", Title: \"Note conflicts with current state\", Status: http.StatusConflict,\n\t\t\tDetail: \"Another note already uses this title.\"}\n\tcase errors.Is(err, ErrForbidden):\n\t\treturn Problem{Type: typeBase + \"forbidden\", Title: \"Action not allowed\", Status: http.StatusForbidden}\n\t}\n\treturn Problem{Type: \"about:blank\", Title: \"Internal Server Error\", Status: http.StatusInternalServerError}\n}\n\nfunc problems(logf func(format string, args ...any)) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.Next()\n\t\tif len(c.Errors) == 0 {\n\t\t\treturn\n\t\t}\n\t\terr := c.Errors.Last().Err\n\t\tp := problemFor(err)\n\t\tif p.Status >= http.StatusInternalServerError {\n\t\t\tlogf(\"%s %s: %v\", c.Request.Method, c.Request.URL.Path, err) // full cause, server side only\n\t\t}\n\t\tif c.Writer.Written() {\n\t\t\treturn // a handler already committed a response; never write a second one\n\t\t}\n\t\tp.Instance = c.Request.URL.Path\n\t\tc.Header(\"Content-Type\", \"application/problem+json\")\n\t\tc.JSON(p.Status, p)\n\t}\n}\n\n// Handlers record the cause and return. They never choose a status for an error.\n\nfunc getNote(c *gin.Context) {\n\t_ = c.Error(fmt.Errorf(\"load note %s: %w\", c.Param(\"id\"), ErrNotFound))\n}\n\nfunc createNote(c *gin.Context) {\n\tvar in struct {\n\t\tTitle *string `json:\"title\"`\n\t}\n\tif err := c.ShouldBindJSON(&in); err != nil {\n\t\t_ = c.Error(fmt.Errorf(\"%w: %v\", errMalformedBody, err))\n\t\treturn\n\t}\n\tif in.Title == nil || strings.TrimSpace(*in.Title) == \"\" {\n\t\t_ = c.Error(&ValidationError{Fields: []FieldError{{Field: \"title\", Reason: \"must not be blank\"}}})\n\t\treturn\n\t}\n\t_ = c.Error(fmt.Errorf(\"insert note: %w\", ErrConflict))\n}\n\nfunc deleteNote(c *gin.Context) {\n\t_ = c.Error(fmt.Errorf(\"delete note %s owned by u2: %w\", c.Param(\"id\"), ErrForbidden))\n}\n\nfunc exportNotes(c *gin.Context) {\n\t_ = c.Error(errors.New(`pq: password authentication failed for user \"notes_rw\" at 192.0.2.10:5432`))\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := gin.New()\n\tr.Use(problems(func(format string, args ...any) { fmt.Printf(\"log: \"+format+\"\\n\", args...) }))\n\tr.NoRoute(func(c *gin.Context) { _ = c.Error(ErrNotFound) })\n\tr.GET(\"/notes/:id\", getNote)\n\tr.POST(\"/notes\", createNote)\n\tr.DELETE(\"/notes/:id\", deleteNote)\n\tr.GET(\"/export\", exportNotes)\n\n\trequests := []struct{ method, path, body string }{\n\t\t{\"GET\", \"/notes/n9\", \"\"},\n\t\t{\"POST\", \"/notes\", `{\"title\":`},\n\t\t{\"POST\", \"/notes\", `{\"title\":\"  \"}`},\n\t\t{\"POST\", \"/notes\", `{\"title\":\"Groceries\"}`},\n\t\t{\"DELETE\", \"/notes/n1\", \"\"},\n\t\t{\"GET\", \"/export\", \"\"},\n\t\t{\"GET\", \"/nowhere\", \"\"},\n\t}\n\tfor _, rq := range requests {\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, httptest.NewRequest(rq.method, rq.path, strings.NewReader(rq.body)))\n\t\tfmt.Println(w.Code, w.Header().Get(\"Content-Type\"), w.Body.String())\n\t}\n}","language":"go","title":"Handlers record, the middleware responds","walkthrough":"problemFor checks the typed error first with errors.AsType, the generic counterpart of errors.As in the Go 1.27 standard library, then the sentinels with errors.Is; both see through the %w wrapping, so \"load note n9: notes: not found\" still maps to 404. The 400 for truncated JSON never repeats the decoder message. The 422 carries the field list from ValidationError, the one error type written for clients. The 500 shows the split: the log line has the full driver message, including user and host, while the body says only Internal Server Error. The last line is an unregistered path, which Gin routes through global middleware and the NoRoute handler, so it is a problem document rather than Gin's plain-text default."},{"body":"RFC 9457, which obsoletes RFC 7807, defines a JSON object served as application/problem+json. type is a URI reference that identifies the problem type and is what clients should branch on; when it is absent it means about:blank, and then title should be the standard phrase for the status code. title is a short summary of the type that should not change between occurrences except for localization. status is advisory and must match the real response status. detail explains this occurrence and should help the client correct the request, not debug the server. instance identifies the occurrence. Extension members such as errors are allowed, and clients must ignore extensions they do not understand.","code":"{\n  \"type\": \"https://example.com/problems/validation\",\n  \"title\": \"Invalid note\",\n  \"status\": 422,\n  \"detail\": \"One or more fields are invalid.\",\n  \"instance\": \"/notes\",\n  \"errors\": [\n    {\"field\": \"title\", \"reason\": \"must not be blank\"}\n  ]\n}","language":"json","title":"The problem document, member by member","walkthrough":"This is the 422 body from the program, pretty-printed. The type URI is a stable identifier under your control and can resolve to human documentation; example.com is a placeholder. title stays the same for every validation failure, while detail and the errors extension describe this request. instance here is the request path; a request ID or a urn:uuid value is also acceptable if support tooling needs to find the matching log line."},{"body":"The text of an arbitrary error is written for developers: it contains SQL fragments, hostnames, user names, file paths and library versions. Public text therefore comes only from the mapping table or from error types designed to be public, such as ValidationError; an unrecognized error becomes a 500 with about:blank and no detail. Log the cause with a request ID and return that ID as an extension member if support needs to correlate. Choose between 403 and 404 deliberately: when the caller may not even know a note exists, answer 404 so the status does not confirm it; use 403 when the caller can see the note but may not perform this action. Two Gin details make the middleware work. Setting Content-Type before c.JSON is preserved, because Gin's JSON renderer only sets the header when it is absent. And when a handler has already written, the middleware must only log, because a second write cannot change a status that is already on the wire.","title":"What must never reach the body"},{"body":"For each member of the taxonomy and for one unknown error, send a request through ServeHTTP and assert the status, the Content-Type and the decoded body; the API-tests lesson builds this table. Add one test that fails when an exported sentinel has no mapping, so a new error kind cannot silently become a 500. Assert that 500 bodies contain no detail at all, since that is the regression that leaks credentials. Clients should branch on type, so changing a type URI is a breaking change; changing title wording is not.","title":"Test the envelope as a contract"}],"takeaway":"Let handlers call c.Error with domain errors, map them in one middleware with errors.Is and errors.AsType to application/problem+json, and never copy an unrecognized error's text into the body.","title":"One error envelope: RFC 9457 problem details mapped from domain errors in one middleware","unitID":"gin-project","wrongAnswers":["In each handler, so every route chooses its own status","In the notes service, which returns the HTTP status code"]},{"conceptTag":"gin.idempotency-keys","designGuide":{"cautions":["A separate idempotency store leaves a crash window; prefer one transaction with the effect.","Unscoped keys can replay one tenant's response to another."],"cost":"One record per write request for the retention period, a lease for pending entries and an extra read and write on every POST.","family":"gin","flow":["Read key and fingerprint","Reserve key atomically","Run and capture response","Replay until expiry"],"ratings":[],"strengths":["Clients can retry ambiguous POSTs without creating duplicates.","Changed payloads and concurrent duplicates are rejected explicitly.","Replays return the identical status, headers and body."]},"hint":"The key promises one effect for one request; ask whether this is still the same request.","id":"gin.idempotency-keys","introduction":"A mobile client sends POST /notes, the connection drops before the 201 arrives, and the client retries. Without help the server creates a second note. HTTP defines PUT and DELETE as idempotent; POST is not, so the client supplies a unique key and the server promises that one key yields at most one effect and one stored response. This lesson adds that promise to the notes API.","nuance":"Replaying would hand back a note the client did not ask for and hide its bug; running it would allow a second effect. Rejecting with 422 keeps one key bound to one request.","objective":"Add Idempotency-Key handling to POST /notes so retries replay the original response, conflicting reuse is rejected and in-flight duplicates wait.","question":"A client reuses Idempotency-Key k1 with a different JSON body after the first request succeeded. What should the server do?","references":["https://www.rfc-editor.org/rfc/rfc9110#section-9.2.2","https://pkg.go.dev/crypto/sha256#Sum256","https://pkg.go.dev/github.com/gin-gonic/gin#ResponseWriter","https://developer.mozilla.org/en-US/docs/Glossary/Idempotent"],"reviewAnswer":"422: the key is bound to the first request's fingerprint","reviewPrompt":"Same key, different body: status?","sections":[{"body":"A timeout is ambiguous: the request may have failed before the handler ran, or succeeded with only the response lost. The client cannot tell, so a safe retry needs the server to remember. The client generates a random key, typically a UUID, for each logical operation and reuses it only when retrying that operation. The server keeps one record per caller and key with a fingerprint of the request, its state and, once finished, the response. Each arrival then has exactly one outcome: a new key runs the handler; a finished identical request is replayed; an identical request still running gets 409; the same key with a different request gets 422; a missing key gets 400. These choices follow the IETF HTTPAPI working group's Idempotency-Key header draft, which is still a draft, so document them in your API contract.","title":"Why a retry duplicates, and what the key promises"},{"body":"Idempotent runs before the create handler. It reads and restores the body, fingerprints the request, and calls Begin, which checks and reserves the key in one critical section. On a fresh reservation it swaps c.Writer for a captureWriter that copies everything written, runs the handler with c.Next, and stores the status, Location and body. A deferred function releases the reservation when the handler ends in a 5xx or panics. The program holds one request open with channels so the in-progress case is deterministic.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"crypto/sha256\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// ---- the idempotency record store ----\n\ntype record struct {\n\tfingerprint [32]byte\n\tdone        bool\n\tstatus      int\n\tlocation    string\n\tbody        []byte\n\texpires     time.Time\n}\n\ntype outcome int\n\nconst (\n\tstarted    outcome = iota // key reserved; run the handler\n\treplay                    // same request finished before; return the stored response\n\tmismatch                  // same key, different request\n\tinProgress                // same request is still running\n)\n\ntype IdempotencyStore struct {\n\tmu      sync.Mutex\n\trecords map[string]*record\n\tnow     func() time.Time\n\tttl     time.Duration\n}\n\n// Begin checks and reserves a key in one critical section.\nfunc (s *IdempotencyStore) Begin(key string, fp [32]byte) (outcome, record) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif r, ok := s.records[key]; ok && s.now().Before(r.expires) {\n\t\tswitch {\n\t\tcase r.fingerprint != fp:\n\t\t\treturn mismatch, record{}\n\t\tcase !r.done:\n\t\t\treturn inProgress, record{}\n\t\tdefault:\n\t\t\treturn replay, *r\n\t\t}\n\t}\n\ts.records[key] = &record{fingerprint: fp, expires: s.now().Add(s.ttl)}\n\treturn started, record{}\n}\n\nfunc (s *IdempotencyStore) Finish(key string, status int, location string, body []byte) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif r, ok := s.records[key]; ok {\n\t\tr.done, r.status, r.location, r.body = true, status, location, body\n\t}\n}\n\nfunc (s *IdempotencyStore) Release(key string) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tdelete(s.records, key)\n}\n\n// ---- the Gin middleware ----\n\ntype captureWriter struct {\n\tgin.ResponseWriter\n\tbody bytes.Buffer\n}\n\nfunc (w *captureWriter) Write(b []byte) (int, error) {\n\tw.body.Write(b)\n\treturn w.ResponseWriter.Write(b)\n}\n\nfunc (w *captureWriter) WriteString(s string) (int, error) {\n\tw.body.WriteString(s)\n\treturn w.ResponseWriter.WriteString(s)\n}\n\nfunc problem(c *gin.Context, status int, title string) {\n\tc.Header(\"Content-Type\", \"application/problem+json\")\n\tc.AbortWithStatusJSON(status, gin.H{\"title\": title, \"status\": status})\n}\n\nfunc Idempotent(store *IdempotencyStore) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tkey := c.GetHeader(\"Idempotency-Key\")\n\t\tif key == \"\" || len(key) > 64 {\n\t\t\tproblem(c, http.StatusBadRequest, \"Idempotency-Key header is required\")\n\t\t\treturn\n\t\t}\n\t\tbody, err := io.ReadAll(c.Request.Body) // already bounded by MaxBytesReader upstream\n\t\tif err != nil {\n\t\t\tproblem(c, http.StatusBadRequest, \"Unreadable body\")\n\t\t\treturn\n\t\t}\n\t\tc.Request.Body = io.NopCloser(bytes.NewReader(body))\n\n\t\tscope := c.GetString(\"principal\") + \"\\x00\" + key\n\t\tfp := sha256.Sum256(append([]byte(c.Request.Method+\" \"+c.FullPath()+\"\\n\"), body...))\n\n\t\tswitch result, rec := store.Begin(scope, fp); result {\n\t\tcase replay:\n\t\t\tc.Header(\"Location\", rec.location)\n\t\t\tc.Header(\"Idempotent-Replayed\", \"true\")\n\t\t\tc.Data(rec.status, \"application/json; charset=utf-8\", rec.body)\n\t\t\tc.Abort()\n\t\t\treturn\n\t\tcase mismatch:\n\t\t\tproblem(c, http.StatusUnprocessableEntity, \"Idempotency-Key was used with a different request\")\n\t\t\treturn\n\t\tcase inProgress:\n\t\t\tc.Header(\"Retry-After\", \"1\")\n\t\t\tproblem(c, http.StatusConflict, \"A request with this Idempotency-Key is in progress\")\n\t\t\treturn\n\t\t}\n\n\t\tfinished := false\n\t\tdefer func() {\n\t\t\tif !finished {\n\t\t\t\tstore.Release(scope) // 5xx or panic: let the client retry\n\t\t\t}\n\t\t}()\n\t\tcw := &captureWriter{ResponseWriter: c.Writer}\n\t\tc.Writer = cw\n\t\tc.Next()\n\t\tif status := cw.Status(); status < http.StatusInternalServerError {\n\t\t\tstore.Finish(scope, status, cw.Header().Get(\"Location\"), bytes.Clone(cw.body.Bytes()))\n\t\t\tfinished = true\n\t\t}\n\t}\n}\n\n// ---- the resource ----\n\ntype Note struct {\n\tID    string `json:\"id\"`\n\tTitle string `json:\"title\"`\n}\n\ntype Notes struct {\n\tmu       sync.Mutex\n\titems    []Note\n\tonCreate func(title string) // demo hook to hold a request open\n}\n\nfunc (n *Notes) Create(title string) Note {\n\tif n.onCreate != nil {\n\t\tn.onCreate(title)\n\t}\n\tn.mu.Lock()\n\tdefer n.mu.Unlock()\n\tnote := Note{ID: fmt.Sprintf(\"n%d\", len(n.items)+1), Title: title}\n\tn.items = append(n.items, note)\n\treturn note\n}\n\nfunc newRouter(store *IdempotencyStore, notes *Notes) *gin.Engine {\n\tr := gin.New()\n\tr.Use(func(c *gin.Context) { c.Set(\"principal\", \"u1\") }) // stand-in for real authentication\n\tr.POST(\"/notes\", Idempotent(store), func(c *gin.Context) {\n\t\tvar in struct {\n\t\t\tTitle string `json:\"title\" binding:\"required\"`\n\t\t}\n\t\tif err := c.ShouldBindJSON(&in); err != nil {\n\t\t\tproblem(c, http.StatusBadRequest, \"Malformed note\")\n\t\t\treturn\n\t\t}\n\t\tnote := notes.Create(in.Title)\n\t\tc.Header(\"Location\", \"/notes/\"+note.ID)\n\t\tc.JSON(http.StatusCreated, note)\n\t})\n\treturn r\n}\n\nfunc post(r http.Handler, key, body string) string {\n\treq := httptest.NewRequest(http.MethodPost, \"/notes\", strings.NewReader(body))\n\tif key != \"\" {\n\t\treq.Header.Set(\"Idempotency-Key\", key)\n\t}\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, req)\n\tline := fmt.Sprint(w.Code)\n\tfor _, h := range []string{\"Location\", \"Idempotent-Replayed\", \"Retry-After\"} {\n\t\tif v := w.Header().Get(h); v != \"\" {\n\t\t\tline += \" \" + h + \"=\" + v\n\t\t}\n\t}\n\tif w.Code >= 400 {\n\t\tline += \" \" + w.Body.String()\n\t}\n\treturn line\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tclock := time.Date(2026, 5, 1, 12, 0, 0, 0, time.UTC)\n\tstore := &IdempotencyStore{records: map[string]*record{}, ttl: 24 * time.Hour,\n\t\tnow: func() time.Time { return clock }}\n\n\tentered, release := make(chan struct{}), make(chan struct{})\n\tnotes := &Notes{onCreate: func(title string) {\n\t\tif title == \"Slow report\" {\n\t\t\tentered <- struct{}{}\n\t\t\t<-release\n\t\t}\n\t}}\n\tr := newRouter(store, notes)\n\n\tfmt.Println(\"first k1:  \", post(r, \"k1\", `{\"title\":\"Groceries\"}`))\n\tfmt.Println(\"retry k1:  \", post(r, \"k1\", `{\"title\":\"Groceries\"}`))\n\tfmt.Println(\"reuse k1:  \", post(r, \"k1\", `{\"title\":\"Errands\"}`))\n\tfmt.Println(\"no key:    \", post(r, \"\", `{\"title\":\"Errands\"}`))\n\n\tfirst := make(chan string)\n\tgo func() { first <- post(r, \"k2\", `{\"title\":\"Slow report\"}`) }()\n\t<-entered // the first k2 request now holds the reservation\n\tfmt.Println(\"second k2: \", post(r, \"k2\", `{\"title\":\"Slow report\"}`))\n\tclose(release)\n\tfmt.Println(\"first k2:  \", <-first)\n\n\tclock = clock.Add(25 * time.Hour) // past the 24h retention window\n\tfmt.Println(\"late k1:   \", post(r, \"k1\", `{\"title\":\"Groceries\"}`))\n\tfmt.Println(\"notes created:\", len(notes.items))\n}","language":"go","title":"A middleware that reserves, captures and replays","walkthrough":"The first k1 creates n1. The retry with the same body never reaches the handler: it gets the stored 201, the same Location and Idempotent-Replayed=true. Reusing k1 with a different title is 422, and a request without a key is 400. For k2, a goroutine starts the slow request, and main waits on entered until the handler is inside Create, so the reservation certainly exists; the second k2 then gets 409 with Retry-After. Closing release lets the first k2 finish with 201 for n2. Finally the fake clock moves 25 hours forward, past the 24-hour retention, and the old k1 creates n3: an expired key is a new request. Three notes exist, not five."},{"body":"The fingerprint is SHA-256 over the method, the route pattern from c.FullPath and the raw body bytes. Byte equality is strict: a client that re-serializes the same JSON with different key order or spacing gets 422. Most APIs accept that and tell clients to resend the identical bytes; canonicalizing JSON before hashing is possible but easy to get subtly wrong. Scope every key by the authenticated principal. Without scope, two tenants that happen to choose the same key would see each other's responses, a data leak rather than a duplicate. Bound the key length and the body size before reading; the binding-limits lesson covers MaxBytesReader. Store whatever the client needs to treat a replay as the original, here status, Location and body. The Idempotent-Replayed header is a convention some APIs use, not a standard, but it makes replays visible in logs and client debugging.","title":"Fingerprints, scope and what gets stored"},{"body":"Begin must check and reserve atomically or two concurrent first attempts both run. The mutex does it here; in PostgreSQL use INSERT ... ON CONFLICT DO NOTHING and check the affected row count, and in Redis use SET with NX and an expiry. A pending record also needs a lease: if the process dies mid-request, nothing releases it, and every retry gets 409 until the record expires. Give pending records a short lock expiry separate from the retention TTL, and make the retention longer than any client's retry window. The deeper gap is that the note and the idempotency record live in different stores. A crash after the note is committed but before Finish loses the stored response, and a retry after the lease runs out creates a duplicate; releasing on a 5xx has the same hole if the effect committed before the error. The robust design writes the idempotency record in the same database transaction as the note, so the effect and the response commit together.","title":"In progress, expiry and the crash window"},{"body":"Cover each branch through ServeHTTP: a fresh key, an identical replay that leaves exactly one note in the store, a changed body that returns 422, a missing key, an in-progress duplicate held open with channels as the program does, expiry driven by an injected clock and a 5xx that releases the key so the retry runs again. Add a test that fires many identical requests from goroutines and asserts that the handler ran once, and run the suite with -race. Assert the replayed body byte for byte, because the promise is the same response, not a similar one.","title":"Test every outcome, including the concurrent one"}],"takeaway":"Reserve each principal-scoped key atomically with a request fingerprint, replay the stored response for identical retries, answer 422 for a changed payload and 409 while in progress, and retain records longer than clients retry.","title":"Make POST safe to retry with Idempotency-Key: fingerprint, reserve, replay and expire","unitID":"gin-project","wrongAnswers":["Replay the first response, because the key matches","Run the new request and overwrite the stored response"]},{"conceptTag":"gin.optimistic-concurrency","designGuide":{"cautions":["A check in the handler followed by an unconditional write still races.","Weak ETags never satisfy If-Match, so writes need strong validators."],"cost":"A version column, a conditional UPDATE and client code that handles 412 by re-reading and merging.","family":"gin","flow":["Version every write","Return strong ETag","Require If-Match","Compare-and-swap in store"],"ratings":[],"strengths":["Concurrent edits are detected instead of silently overwritten.","No locks are held while clients read or think.","Uses standard HTTP headers and statuses that clients and proxies understand."]},"hint":"One status means a condition was evaluated and failed; another means no condition was sent.","id":"gin.optimistic-concurrency","introduction":"Two people open the same note. One adds a line; the other fixes the title from the copy loaded earlier, and that second save quietly erases the first edit. Each request was valid on its own. The bug is that the server never asked which version the client was editing. HTTP already has the vocabulary for that question: ETag, If-Match, 412 Precondition Failed and 428 Precondition Required.","nuance":"412 reports a precondition that was present and false. RFC 6585 defines 428 for a server that requires a precondition the request did not include.","objective":"Version the notes resource, expose the version as an ETag and require If-Match on writes so a stale client cannot overwrite a newer edit.","question":"The notes API requires conditional writes. A client sends PUT /notes/n1 without an If-Match header. Which response is correct?","references":["https://www.rfc-editor.org/rfc/rfc9110#section-13.1.1","https://www.rfc-editor.org/rfc/rfc6585#section-3","https://www.rfc-editor.org/rfc/rfc9110#section-8.8.3","https://martinfowler.com/eaaCatalog/optimisticOfflineLock.html"],"reviewAnswer":"428 Precondition Required","reviewPrompt":"Write without If-Match: status?","sections":[{"body":"The store's mutex from the CRUD lesson makes each write atomic, but the dangerous gap is not inside a request. It is between one client's GET and its later PUT, while another client writes. A lock cannot cover that gap without holding it across user think time, and abandoned locks are worse than the original bug. Optimistic concurrency accepts that conflicts are rare and detects them at write time instead: every note carries a version, every successful write increments it, and a write names the version it was based on. If the stored version has moved, the write is refused and the client decides what to do. Nothing is locked while people read.","title":"A lost update spans two requests"},{"body":"GET returns the version as a strong ETag such as \"1\". The guarded PUT requires If-Match, compares it with the current version and asks the store to replace the note only if the version is still the one it checked. The naive route with no checks runs first to reproduce the bug, then the guarded route replays the same two edits.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype Note struct {\n\tID      string `json:\"id\"`\n\tTitle   string `json:\"title\"`\n\tBody    string `json:\"body\"`\n\tVersion int    `json:\"version\"`\n}\n\nvar (\n\tErrNotFound        = errors.New(\"notes: not found\")\n\tErrVersionMismatch = errors.New(\"notes: version mismatch\")\n)\n\ntype MemoryStore struct {\n\tmu    sync.Mutex\n\tnotes map[string]Note\n}\n\n// Replace is a compare-and-swap: it writes only if the stored version still\n// equals expected (-1 means \"skip the check\", used by the naive route).\nfunc (m *MemoryStore) Replace(id string, expected int, title, body string) (Note, error) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tn, ok := m.notes[id]\n\tif !ok {\n\t\treturn Note{}, ErrNotFound\n\t}\n\tif expected >= 0 && n.Version != expected {\n\t\treturn Note{}, ErrVersionMismatch\n\t}\n\tn.Title, n.Body, n.Version = title, body, n.Version+1\n\tm.notes[id] = n\n\treturn n, nil\n}\n\nfunc (m *MemoryStore) Get(id string) (Note, error) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\tn, ok := m.notes[id]\n\tif !ok {\n\t\treturn Note{}, ErrNotFound\n\t}\n\treturn n, nil\n}\n\nfunc etag(version int) string { return `\"` + strconv.Itoa(version) + `\"` }\n\n// matchVersion reads If-Match with strong comparison. Weak tags (W/\"...\") never match.\nfunc matchVersion(header string, current int) bool {\n\tfor _, tag := range strings.Split(header, \",\") {\n\t\ttag = strings.TrimSpace(tag)\n\t\tif tag == \"*\" || tag == etag(current) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\ntype noteBody struct {\n\tTitle string `json:\"title\" binding:\"required\"`\n\tBody  string `json:\"body\"`\n}\n\nfunc newRouter(st *MemoryStore) *gin.Engine {\n\tr := gin.New()\n\tr.GET(\"/notes/:id\", func(c *gin.Context) {\n\t\tn, err := st.Get(c.Param(\"id\"))\n\t\tif err != nil {\n\t\t\tc.Status(http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\t\tc.Header(\"ETag\", etag(n.Version))\n\t\tc.JSON(http.StatusOK, n)\n\t})\n\t// The naive route: last write wins.\n\tr.PUT(\"/naive/notes/:id\", func(c *gin.Context) {\n\t\tvar in noteBody\n\t\tif c.ShouldBindJSON(&in) != nil {\n\t\t\tc.Status(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tn, _ := st.Replace(c.Param(\"id\"), -1, in.Title, in.Body)\n\t\tc.JSON(http.StatusOK, n)\n\t})\n\t// The guarded route: the client must prove which version it edited.\n\tr.PUT(\"/notes/:id\", func(c *gin.Context) {\n\t\tifMatch := c.GetHeader(\"If-Match\")\n\t\tif ifMatch == \"\" {\n\t\t\tc.JSON(http.StatusPreconditionRequired, gin.H{\"title\": \"If-Match header is required\"})\n\t\t\treturn\n\t\t}\n\t\tvar in noteBody\n\t\tif c.ShouldBindJSON(&in) != nil {\n\t\t\tc.Status(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tcur, err := st.Get(c.Param(\"id\"))\n\t\tif err != nil {\n\t\t\tc.Status(http.StatusNotFound)\n\t\t\treturn\n\t\t}\n\t\tif !matchVersion(ifMatch, cur.Version) {\n\t\t\tc.JSON(http.StatusPreconditionFailed, gin.H{\"title\": \"Note was changed by someone else\"})\n\t\t\treturn\n\t\t}\n\t\t// The store re-checks atomically: another writer may have won since Get.\n\t\tn, err := st.Replace(cur.ID, cur.Version, in.Title, in.Body)\n\t\tif errors.Is(err, ErrVersionMismatch) {\n\t\t\tc.JSON(http.StatusPreconditionFailed, gin.H{\"title\": \"Note was changed by someone else\"})\n\t\t\treturn\n\t\t}\n\t\tc.Header(\"ETag\", etag(n.Version))\n\t\tc.JSON(http.StatusOK, n)\n\t})\n\treturn r\n}\n\nfunc do(r http.Handler, method, path, ifMatch, body string) *httptest.ResponseRecorder {\n\treq := httptest.NewRequest(method, path, strings.NewReader(body))\n\tif ifMatch != \"\" {\n\t\treq.Header.Set(\"If-Match\", ifMatch)\n\t}\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, req)\n\treturn w\n}\n\nfunc seed() *MemoryStore {\n\treturn &MemoryStore{notes: map[string]Note{\n\t\t\"n1\": {ID: \"n1\", Title: \"Trip\", Body: \"flights\", Version: 1},\n\t}}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\n\t// Lost update: both clients read version 1, both write, the second silently wins.\n\tst := seed()\n\tr := newRouter(st)\n\tdo(r, \"PUT\", \"/naive/notes/n1\", \"\", `{\"title\":\"Trip\",\"body\":\"flights, hotel\"}`)  // client A adds the hotel\n\tdo(r, \"PUT\", \"/naive/notes/n1\", \"\", `{\"title\":\"Trip to Rome\",\"body\":\"flights\"}`) // client B renames from a stale copy\n\tn, _ := st.Get(\"n1\")\n\tfmt.Printf(\"naive final: title=%q body=%q\\n\", n.Title, n.Body)\n\n\t// The same race with ETag and If-Match.\n\tst = seed()\n\tr = newRouter(st)\n\ttag := do(r, \"GET\", \"/notes/n1\", \"\", \"\").Header().Get(\"ETag\")\n\tfmt.Println(\"A and B read ETag\", tag)\n\tw := do(r, \"PUT\", \"/notes/n1\", tag, `{\"title\":\"Trip\",\"body\":\"flights, hotel\"}`)\n\tfmt.Println(\"A PUT If-Match\", tag, \"->\", w.Code, \"ETag\", w.Header().Get(\"ETag\"))\n\tw = do(r, \"PUT\", \"/notes/n1\", tag, `{\"title\":\"Trip to Rome\",\"body\":\"flights\"}`)\n\tfmt.Println(\"B PUT If-Match\", tag, \"->\", w.Code, w.Body.String())\n\tw = do(r, \"PUT\", \"/notes/n1\", \"\", `{\"title\":\"Trip to Rome\",\"body\":\"flights\"}`)\n\tfmt.Println(\"B PUT without If-Match ->\", w.Code, w.Body.String())\n\tw = do(r, \"PUT\", \"/notes/n1\", `W/\"2\"`, `{\"title\":\"Trip to Rome\",\"body\":\"flights, hotel\"}`)\n\tfmt.Println(`B PUT If-Match W/\"2\" ->`, w.Code)\n\n\tg := do(r, \"GET\", \"/notes/n1\", \"\", \"\")\n\tfresh := g.Header().Get(\"ETag\")\n\tw = do(r, \"PUT\", \"/notes/n1\", fresh, `{\"title\":\"Trip to Rome\",\"body\":\"flights, hotel\"}`)\n\tfmt.Println(\"B re-reads\", fresh, \"and retries ->\", w.Code, \"ETag\", w.Header().Get(\"ETag\"))\n\tfmt.Println(\"final:\", w.Body.String())\n}","language":"go","title":"ETag out, If-Match in, compare-and-swap in the store","walkthrough":"On the naive route both writes succeed and the final body is \"flights\": client A's hotel is gone and nobody was told. On the guarded route both clients read ETag \"1\". A writes with If-Match \"1\" and gets 200 with ETag \"2\". B writes from the stale copy with If-Match \"1\" and gets 412. Without If-Match B gets 428, so skipping the header is not a way around the check. W/\"2\" names the current version but is weak, and If-Match uses strong comparison, so it fails too. B re-reads, gets \"2\", reapplies the title change onto the current body and receives ETag \"3\"; the final note keeps both edits. Replace re-checks the version under its own lock because another writer can win between the handler's Get and the write."},{"body":"RFC 9110 defines an entity tag as a quoted string, optionally prefixed with W/ to mark it weak. If-Match is evaluated with strong comparison, so a weak tag can never satisfy it, and the asterisk matches any current representation, which is useful to say \"update only if it exists\". When the condition is false the server must not perform the method; the usual answer is 412, and RFC 9110 also permits a 2xx when the server can verify that the requested change is already reflected in the current state. RFC 6585 adds 428 for a server that requires conditional requests and receives one without a condition. Send the new ETag with every successful write so the client does not need an extra GET. PATCH needs exactly the same guard as PUT: a partial update made from stale assumptions is still a lost update. In the full service, 412 and 428 go through the problems middleware as two more problem types.","title":"The rules HTTP already defines"},{"body":"The version check and the increment must be one operation in the store. A handler that reads the version, compares it and then issues an unconditional write has a race between the compare and the write. In SQL the condition goes into the UPDATE itself, and a statement that matched no rows tells you the condition failed. Do not use updated_at as the version: clock resolution and skew make two writes look simultaneous. Increment the version on every change that alters the representation, and if the representation includes data from elsewhere, such as an author name from another table, either include that in the version or derive the ETag from a hash of the representation.","code":"const replaceNote = `\nUPDATE notes\n   SET title = $1, body = $2, version = version + 1\n WHERE id = $3 AND owner_id = $4 AND version = $5\nRETURNING version`\n\nfunc (s *Postgres) Replace(ctx context.Context, owner, id string, expected int, title, body string) (int, error) {\n\tvar v int\n\terr := s.db.QueryRowContext(ctx, replaceNote, title, body, id, owner, expected).Scan(&v)\n\tif !errors.Is(err, sql.ErrNoRows) {\n\t\treturn v, err // success, or a real database error\n\t}\n\t// No row matched: the note is gone, or another writer moved the version on.\n\tvar exists bool\n\tif err := s.db.QueryRowContext(ctx,\n\t\t`SELECT EXISTS (SELECT 1 FROM notes WHERE id = $1 AND owner_id = $2)`, id, owner).Scan(&exists); err != nil {\n\t\treturn 0, err\n\t}\n\tif !exists {\n\t\treturn 0, ErrNotFound\n\t}\n\treturn 0, ErrVersionMismatch\n}","language":"go","title":"Make the check atomic where the data lives","walkthrough":"This fragment is the PostgreSQL adapter for the same Replace contract; run it against your own database. The WHERE clause checks ID, owner and version in the same statement that increments the version, so two writers holding version 5 cannot both succeed; the second matches zero rows. RETURNING gives the new version for the ETag. On sql.ErrNoRows a second query distinguishes a deleted note, which maps to 404, from a version that moved on, which maps to 412."},{"body":"On 412 a client re-reads, merges or shows the conflict to the person, and retries with the fresh ETag. Automatically resending the same body with the new ETag is just last-write-wins with extra steps. Conditional writes also interact with retries: if a PUT succeeded but the response was lost, the retry with the old If-Match gets 412 from this implementation, and the client should re-read and notice its change is already there. Test the contract through ServeHTTP: missing header is 428, a stale tag is 412, a weak tag is 412, a fresh tag is 200 with the next ETag, and two goroutines writing with the same tag produce exactly one 200.","title":"What clients and tests must do"}],"takeaway":"Expose a version as a strong ETag, require If-Match on PUT and PATCH with 428 when it is absent, and let the store compare and increment the version atomically, answering 412 on mismatch.","title":"Stop lost updates with versions, ETag and If-Match: 428 when missing, 412 when stale","unitID":"gin-project","wrongAnswers":["412 Precondition Failed, because no version matched","200 OK, applying the write as last-write-wins"]},{"conceptTag":"gin.api-tests","designGuide":{"cautions":["float64 decoding loses precision for integers above 2^53.","Fakes do not prove the real store works; keep separate integration tests."],"cost":"A fake per dependency, a test helper and the discipline to inject time and IDs everywhere.","family":"gin","flow":["Build router with fakes","Send table row requests","Assert status and headers","Compare decoded bodies"],"ratings":[],"strengths":["Tests the real middleware chain and error mapping in milliseconds.","Whole-body comparison catches leaks and accidental fields.","New cases are one table row, so regressions get reproduced cheaply."]},"hint":"Consider what changes in the bytes when the same object is encoded twice.","id":"gin.api-tests","introduction":"Tests that call a handler function directly miss the bugs that live between handlers: middleware order, error mapping, headers and the exact JSON a client parses. Sending requests through the router production uses, with a fake store behind it, tests the API contract in milliseconds. A table turns the next case into a few lines, and asserting whole bodies is what catches the regression that a status check waves through.","nuance":"Two encodings of one object can differ in key order and spacing. Decoding compares values, and because DeepEqual still sees every member, an unexpected detail field fails the test.","objective":"Write table-driven tests that send requests through the real Gin router with fakes and assert status, contract headers and semantically compared JSON bodies.","question":"Why does assertJSONEqual decode both the expected and the actual body into any before comparing them?","references":["https://go.dev/wiki/TableDrivenTests","https://pkg.go.dev/net/http/httptest#NewRecorder","https://pkg.go.dev/testing#T.Run","https://pkg.go.dev/reflect#DeepEqual"],"reviewAnswer":"Key order and whitespace are not part of the contract","reviewPrompt":"Why decode JSON before comparing?","sections":[{"body":"In these tests everything a request touches in production is real except the outermost dependencies. The engine, the problems middleware, the handlers and the notes service are the production code, built through the same constructors main uses. The store, the clock and the ID source are fakes injected as the dependencies lesson showed, which makes every body deterministic. Each case builds its own fake and router, so cases share nothing and can run in parallel. Assert three things per response: the status, every header that is part of the contract such as Location, Content-Type, ETag or Retry-After, and the entire body as a JSON value. A storage adapter gets its own integration tests against a real database; mixing the two makes API tests slow and flaky.","title":"Test the router, fake only the edges"},{"body":"The test file lives next to the handlers but uses the external package httpapi_test, so it can only call what main can call: NewRouter, NewHandler and the notes constructors. That keeps the tests honest about the public wiring. TestMain sets Gin's mode once, because SetMode writes a process-wide variable and parallel subtests must not race on it.","code":"package httpapi_test\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n\n\t\"example.com/notes-api/internal/httpapi\"\n\t\"example.com/notes-api/internal/notes\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgin.SetMode(gin.TestMode) // process-wide: set once, before any test builds an engine\n\tos.Exit(m.Run())\n}\n\nfunc TestNotesAPI(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\tmethod     string\n\t\tpath       string\n\t\tbody       string\n\t\tstoreErr   error\n\t\twantStatus int\n\t\twantHeader map[string]string\n\t\twantBody   string\n\t}{\n\t\t{\n\t\t\tname: \"create returns 201 and Location\", method: \"POST\", path: \"/notes\", body: `{\"title\":\" Review PR \"}`,\n\t\t\twantStatus: 201,\n\t\t\twantHeader: map[string]string{\"Location\": \"/notes/n1\", \"Content-Type\": \"application/json; charset=utf-8\"},\n\t\t\twantBody:   `{\"title\": \"Review PR\", \"id\": \"n1\", \"createdAt\": \"2026-01-02T03:04:05Z\"}`,\n\t\t},\n\t\t{\n\t\t\tname: \"missing note is a problem document\", method: \"GET\", path: \"/notes/n9\",\n\t\t\twantStatus: 404,\n\t\t\twantHeader: map[string]string{\"Content-Type\": \"application/problem+json\"},\n\t\t\twantBody:   `{\"type\": \"https://example.com/problems/not-found\", \"title\": \"Note not found\", \"status\": 404, \"instance\": \"/notes/n9\"}`,\n\t\t},\n\t\t{\n\t\t\tname: \"blank title is rejected with a reason\", method: \"POST\", path: \"/notes\", body: `{\"title\":\"   \"}`,\n\t\t\twantStatus: 422,\n\t\t\twantHeader: map[string]string{\"Content-Type\": \"application/problem+json\"},\n\t\t\twantBody:   `{\"type\": \"https://example.com/problems/validation\", \"title\": \"Invalid note\", \"status\": 422, \"detail\": \"title must not be blank\", \"instance\": \"/notes\"}`,\n\t\t},\n\t\t{\n\t\t\tname: \"store failure hides the cause\", method: \"GET\", path: \"/notes/n1\",\n\t\t\tstoreErr:   errors.New(\"dial tcp 192.0.2.10:5432: connection refused\"),\n\t\t\twantStatus: 500,\n\t\t\twantHeader: map[string]string{\"Content-Type\": \"application/problem+json\"},\n\t\t\twantBody:   `{\"type\": \"about:blank\", \"title\": \"Internal Server Error\", \"status\": 500, \"instance\": \"/notes/n1\"}`,\n\t\t},\n\t}\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\t\t\tr := newTestRouter(t, tc.storeErr)\n\t\t\treq := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))\n\t\t\tif tc.body != \"\" {\n\t\t\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\t\t}\n\t\t\tw := httptest.NewRecorder()\n\t\t\tr.ServeHTTP(w, req)\n\n\t\t\tif w.Code != tc.wantStatus {\n\t\t\t\tt.Errorf(\"status = %d, want %d\", w.Code, tc.wantStatus)\n\t\t\t}\n\t\t\tfor k, want := range tc.wantHeader {\n\t\t\t\tif got := w.Header().Get(k); got != want {\n\t\t\t\t\tt.Errorf(\"header %s = %q, want %q\", k, got, want)\n\t\t\t\t}\n\t\t\t}\n\t\t\tassertJSONEqual(t, tc.wantBody, w.Body.Bytes())\n\t\t})\n\t}\n}\n\nfunc newTestRouter(t *testing.T, storeErr error) http.Handler {\n\tt.Helper()\n\tfake := newFakeStore()\n\tfake.err = storeErr\n\tseq := 0\n\tids := func() string { seq++; return fmt.Sprintf(\"n%d\", seq) }\n\tclock := func() time.Time { return time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) }\n\tsvc, err := notes.NewService(fake, clock, ids)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tr, err := httpapi.NewRouter(httpapi.NewHandler(svc, slog.New(slog.DiscardHandler)), httpapi.Options{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn r\n}\n\nfunc assertJSONEqual(t *testing.T, want string, got []byte) {\n\tt.Helper()\n\tvar w, g any\n\tif err := json.Unmarshal([]byte(want), &w); err != nil {\n\t\tt.Fatalf(\"test table has invalid JSON: %v\", err)\n\t}\n\tif err := json.Unmarshal(got, &g); err != nil {\n\t\tt.Fatalf(\"response is not JSON: %v\\n%s\", err, got)\n\t}\n\tif !reflect.DeepEqual(w, g) {\n\t\tt.Errorf(\"body mismatch\\n got: %s\\nwant: %s\", got, want)\n\t}\n}","language":"go","title":"handler_test.go: the table and the assertions","walkthrough":"This fragment belongs in internal/httpapi of the module from the layout lesson and runs there with go test -race ./internal/httpapi. Each table row names the request and the expected contract. t.Run gives every case its own name in the output, and t.Parallel is safe because the router and fake are per case; since Go 1.22 the loop variable tc is a fresh variable on each iteration, so the closure needs no copy. newTestRouter uses t.Helper and t.Fatal for wiring errors. assertJSONEqual decodes both sides into any and compares them with reflect.DeepEqual, reporting the full actual body on mismatch. fakeStore, with a mutex and an err field, lives in fake_test.go in the same package."},{"body":"The runnable model condenses the notes and httpapi packages into one file and runs the same four cases three times: against the current build, against a regressed build with status-only checks, and against the regressed build with full checks. The regression is a plausible \"debugging aid\": the problems middleware copies err.Error() into detail for unexpected errors.","code":"package main\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"reflect\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// ---- condensed code under test: notes + httpapi from earlier lessons ----\n\ntype Note struct {\n\tID        string    `json:\"id\"`\n\tTitle     string    `json:\"title\"`\n\tCreatedAt time.Time `json:\"createdAt\"`\n}\n\nvar (\n\tErrNotFound = errors.New(\"notes: not found\")\n\tErrInvalid  = errors.New(\"notes: title must not be blank\")\n)\n\ntype Store interface {\n\tInsert(ctx context.Context, n Note) error\n\tGet(ctx context.Context, id string) (Note, error)\n}\n\ntype Handler struct {\n\tstore  Store\n\tnow    func() time.Time\n\tnextID func() string\n}\n\ntype Problem struct {\n\tType     string `json:\"type\"`\n\tTitle    string `json:\"title\"`\n\tStatus   int    `json:\"status\"`\n\tDetail   string `json:\"detail,omitempty\"`\n\tInstance string `json:\"instance,omitempty\"`\n}\n\nfunc problems(exposeCause bool) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tc.Next()\n\t\tif len(c.Errors) == 0 || c.Writer.Written() {\n\t\t\treturn\n\t\t}\n\t\terr := c.Errors.Last().Err\n\t\tp := Problem{Type: \"about:blank\", Title: \"Internal Server Error\", Status: 500}\n\t\tswitch {\n\t\tcase errors.Is(err, ErrNotFound):\n\t\t\tp = Problem{Type: \"https://example.com/problems/not-found\", Title: \"Note not found\", Status: 404}\n\t\tcase errors.Is(err, ErrInvalid):\n\t\t\tp = Problem{Type: \"https://example.com/problems/validation\", Title: \"Invalid note\", Status: 422,\n\t\t\t\tDetail: \"title must not be blank\"}\n\t\tcase exposeCause:\n\t\t\tp.Detail = err.Error() // the \"helpful\" regression\n\t\t}\n\t\tp.Instance = c.Request.URL.Path\n\t\tc.Header(\"Content-Type\", \"application/problem+json\")\n\t\tc.JSON(p.Status, p)\n\t}\n}\n\nfunc NewRouter(h *Handler, exposeCause bool) *gin.Engine {\n\tr := gin.New()\n\tr.Use(problems(exposeCause))\n\tr.POST(\"/notes\", func(c *gin.Context) {\n\t\tvar in struct {\n\t\t\tTitle string `json:\"title\"`\n\t\t}\n\t\tif err := c.ShouldBindJSON(&in); err != nil || strings.TrimSpace(in.Title) == \"\" {\n\t\t\t_ = c.Error(ErrInvalid)\n\t\t\treturn\n\t\t}\n\t\tn := Note{ID: h.nextID(), Title: strings.TrimSpace(in.Title), CreatedAt: h.now()}\n\t\tif err := h.store.Insert(c.Request.Context(), n); err != nil {\n\t\t\t_ = c.Error(fmt.Errorf(\"insert %s: %w\", n.ID, err))\n\t\t\treturn\n\t\t}\n\t\tc.Header(\"Location\", \"/notes/\"+n.ID)\n\t\tc.JSON(http.StatusCreated, n)\n\t})\n\tr.GET(\"/notes/:id\", func(c *gin.Context) {\n\t\tn, err := h.store.Get(c.Request.Context(), c.Param(\"id\"))\n\t\tif err != nil {\n\t\t\t_ = c.Error(fmt.Errorf(\"get %s: %w\", c.Param(\"id\"), err))\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusOK, n)\n\t})\n\treturn r\n}\n\n// ---- test support: a fake store and a semantic JSON comparison ----\n\ntype fakeStore struct {\n\tnotes map[string]Note\n\terr   error\n}\n\nfunc (f *fakeStore) Insert(_ context.Context, n Note) error {\n\tif f.err != nil {\n\t\treturn f.err\n\t}\n\tf.notes[n.ID] = n\n\treturn nil\n}\n\nfunc (f *fakeStore) Get(_ context.Context, id string) (Note, error) {\n\tif f.err != nil {\n\t\treturn Note{}, f.err\n\t}\n\tn, ok := f.notes[id]\n\tif !ok {\n\t\treturn Note{}, ErrNotFound\n\t}\n\treturn n, nil\n}\n\nfunc jsonEqual(want string, got []byte) bool {\n\tvar w, g any\n\tif json.Unmarshal([]byte(want), &w) != nil || json.Unmarshal(got, &g) != nil {\n\t\treturn false\n\t}\n\treturn reflect.DeepEqual(w, g)\n}\n\n// ---- the table: the same one handler_test.go runs with t.Run ----\n\ntype apiCase struct {\n\tname       string\n\tmethod     string\n\tpath       string\n\tbody       string\n\tstoreErr   error\n\twantStatus int\n\twantHeader map[string]string\n\twantBody   string\n}\n\nvar cases = []apiCase{\n\t{\n\t\tname: \"create returns 201 and Location\", method: \"POST\", path: \"/notes\", body: `{\"title\":\" Review PR \"}`,\n\t\twantStatus: 201,\n\t\twantHeader: map[string]string{\"Location\": \"/notes/n1\", \"Content-Type\": \"application/json; charset=utf-8\"},\n\t\twantBody:   `{\"title\": \"Review PR\", \"id\": \"n1\", \"createdAt\": \"2026-01-02T03:04:05Z\"}`,\n\t},\n\t{\n\t\tname: \"missing note is a problem document\", method: \"GET\", path: \"/notes/n9\",\n\t\twantStatus: 404,\n\t\twantHeader: map[string]string{\"Content-Type\": \"application/problem+json\"},\n\t\twantBody:   `{\"type\": \"https://example.com/problems/not-found\", \"title\": \"Note not found\", \"status\": 404, \"instance\": \"/notes/n9\"}`,\n\t},\n\t{\n\t\tname: \"blank title is rejected with a reason\", method: \"POST\", path: \"/notes\", body: `{\"title\":\"   \"}`,\n\t\twantStatus: 422,\n\t\twantHeader: map[string]string{\"Content-Type\": \"application/problem+json\"},\n\t\twantBody:   `{\"type\": \"https://example.com/problems/validation\", \"title\": \"Invalid note\", \"status\": 422, \"detail\": \"title must not be blank\", \"instance\": \"/notes\"}`,\n\t},\n\t{\n\t\tname: \"store failure hides the cause\", method: \"GET\", path: \"/notes/n1\",\n\t\tstoreErr:   errors.New(\"dial tcp 192.0.2.10:5432: connection refused\"),\n\t\twantStatus: 500,\n\t\twantHeader: map[string]string{\"Content-Type\": \"application/problem+json\"},\n\t\twantBody:   `{\"type\": \"about:blank\", \"title\": \"Internal Server Error\", \"status\": 500, \"instance\": \"/notes/n1\"}`,\n\t},\n}\n\nfunc newRouterFor(tc apiCase, exposeCause bool) http.Handler {\n\tseq := 0\n\th := &Handler{\n\t\tstore:  &fakeStore{notes: map[string]Note{}, err: tc.storeErr},\n\t\tnow:    func() time.Time { return time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) },\n\t\tnextID: func() string { seq++; return fmt.Sprintf(\"n%d\", seq) },\n\t}\n\treturn NewRouter(h, exposeCause)\n}\n\nfunc check(r http.Handler, tc apiCase, statusOnly bool) []string {\n\treq := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))\n\tif tc.body != \"\" {\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t}\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, req)\n\n\tvar fails []string\n\tif w.Code != tc.wantStatus {\n\t\tfails = append(fails, fmt.Sprintf(\"status %d, want %d\", w.Code, tc.wantStatus))\n\t}\n\tif statusOnly {\n\t\treturn fails\n\t}\n\tfor _, k := range slices.Sorted(maps.Keys(tc.wantHeader)) {\n\t\tif got := w.Header().Get(k); got != tc.wantHeader[k] {\n\t\t\tfails = append(fails, fmt.Sprintf(\"%s %q, want %q\", k, got, tc.wantHeader[k]))\n\t\t}\n\t}\n\tif !jsonEqual(tc.wantBody, w.Body.Bytes()) {\n\t\tfails = append(fails, \"body \"+w.Body.String())\n\t}\n\treturn fails\n}\n\nfunc run(label string, exposeCause, statusOnly bool) {\n\tfmt.Println(label)\n\tfor _, tc := range cases {\n\t\tif fails := check(newRouterFor(tc, exposeCause), tc, statusOnly); len(fails) > 0 {\n\t\t\tfmt.Printf(\"  FAIL %s: %s\\n\", tc.name, strings.Join(fails, \"; \"))\n\t\t} else {\n\t\t\tfmt.Printf(\"  PASS %s\\n\", tc.name)\n\t\t}\n\t}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\trun(\"current build, full checks:\", false, false)\n\trun(\"regressed build, status-only checks:\", true, true)\n\trun(\"regressed build, full checks:\", true, false)\n}","language":"go","title":"The same table, runnable, against a regression","walkthrough":"check sends one request and collects failures instead of calling t.Errorf, so main can print a PASS or FAIL line per case. Header names are checked in sorted order to keep output stable. The current build passes everything; note that the expected create body lists keys in a different order and with spaces, and still matches. On the regressed build, status-only checks pass all four cases, because a leaking 500 is still a 500. Full checks fail the store-failure case and print the body that would have reached clients, with the database address in detail."},{"body":"Byte comparison breaks for reasons that are not part of the contract: key order in maps, field order after a struct refactor, whitespace, and HTML escaping, since encoding/json escapes <, > and & by default and Gin's c.PureJSON does not. Decoding both sides into any and comparing with reflect.DeepEqual compares values instead. It is still strict in the useful direction: an extra member, a missing member and a null where a string was expected all fail, which is exactly how the leaked detail was caught. Two caveats remain. Numbers decode to float64, so integers above 2^53 lose precision; decode with json.Decoder.UseNumber when IDs or amounts are large. And volatile fields should be made deterministic by injecting the clock and ID source rather than deleted before comparing, because deleted fields are untested fields.","title":"Compare JSON by meaning, and know the limits"},{"body":"For each route, include the success path with its headers, every error kind the problems middleware maps and one failing store that must produce a bare 500. Add middleware-level rows: an unknown route, an oversized body, a missing Idempotency-Key, a missing or stale If-Match. Where a request has side effects, inspect the fake afterwards; a replayed idempotent POST must leave exactly one note. Run with -race and -count=1, and occasionally with -shuffle=on to surface hidden ordering between cases. When a bug escapes, its reproduction becomes a new row before the fix.","title":"What the table should cover"}],"takeaway":"Drive tests through the production router with fakes for the store, clock and IDs, and assert status, contract headers and the whole JSON body compared semantically, so a leaked detail fails the build.","title":"Table-driven API tests through the real router: status, headers and JSON compared by meaning","unitID":"gin-project","wrongAnswers":["httptest cannot expose the body until it is decoded","It ignores extra members, so tests survive new fields"]},{"conceptTag":"gin.config-startup","designGuide":{"cautions":["URL.Redacted masks only the password; tokens in query strings still leak.","Using the signal context as BaseContext cancels draining requests."],"cost":"A config package with a test table and a slightly longer main; both are cheaper than one misconfigured production start.","family":"gin","flow":["Load and validate config","Wire store to engine","Bind listener, serve","Signal, drain, exit"],"ratings":[],"strengths":["Bad deployments fail before serving, with every problem listed.","All wiring is in one short function that names every dependency.","Shutdown has one owner and one budget taken from configuration."]},"hint":"Follow the signal context down to each request's r.Context().","id":"gin.config-startup","introduction":"The last piece of the notes API is the code that runs first. A typo in an environment variable should stop a deploy with a clear message, not start a server with a default timeout, a debug-mode router or a proxy list that trusts the whole internet. This lesson builds the configuration loader, then assembles every package from the earlier lessons in cmd/api/main.go.","nuance":"Every request context derives from BaseContext, so cancelling it on SIGTERM aborts the in-flight requests that a graceful Shutdown is meant to let finish.","objective":"Load and validate configuration from the environment, fail fast with every problem listed, and wire store, service, handlers, engine and http.Server with signal-driven shutdown.","question":"Why should run not set http.Server.BaseContext to return the signal.NotifyContext context?","references":["https://pkg.go.dev/os/signal#NotifyContext","https://pkg.go.dev/net/http#Server.Shutdown","https://pkg.go.dev/errors#Join","https://pkg.go.dev/net/url#URL.Redacted"],"reviewAnswer":"No: SIGTERM would cancel requests that are draining","reviewPrompt":"Signal context as BaseContext?","sections":[{"body":"Environment variables are untyped strings set by people and deployment templates, so they fail in predictable ways. A duration written as 5 without a unit does not parse. A misspelled name is silently ignored and the default applies. A value can parse correctly and still be dangerous, such as a shutdown budget longer than the platform waits before killing the process, or a trusted-proxy range of 0.0.0.0/0. And a database URL printed at startup leaks its password into logs. The loader answers each one: typed fields, explicit ranges, an error for unknown names under the application prefix, defaults that are safe in production, and a String method that redacts secrets. It also collects every problem before returning, so one failed deploy shows the whole list instead of one error per attempt.","title":"Configuration is input: parse it, bound it, reject it"},{"body":"Load takes the environment as a slice of KEY=value strings, the shape os.Environ returns, rather than calling os.Getenv itself. That keeps it a pure function: tests pass literal slices, and main passes the real environment. Small closures parse each kind of value and append to a shared error list, cross-field rules run at the end, and errors.Join combines everything into one error whose message has one line per problem.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/netip\"\n\t\"net/url\"\n\t\"slices\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n)\n\ntype Config struct {\n\tAddr              string\n\tMode              string // gin mode: release or debug\n\tStore             string // memory or postgres\n\tDatabaseURL       *url.URL\n\tReadHeaderTimeout time.Duration\n\tShutdownTimeout   time.Duration\n\tMaxBodyBytes      int64\n\tIdempotencyTTL    time.Duration\n\tTrustedProxies    []netip.Prefix\n}\n\nvar known = []string{\n\t\"NOTES_ADDR\", \"NOTES_MODE\", \"NOTES_STORE\", \"NOTES_DATABASE_URL\", \"NOTES_READ_HEADER_TIMEOUT\",\n\t\"NOTES_SHUTDOWN_TIMEOUT\", \"NOTES_MAX_BODY_BYTES\", \"NOTES_IDEMPOTENCY_TTL\", \"NOTES_TRUSTED_PROXIES\",\n}\n\n// Load reads KEY=value pairs (os.Environ() in production) and reports every problem at once.\nfunc Load(environ []string) (Config, error) {\n\tenv := map[string]string{}\n\tvar errs []error\n\tfor _, kv := range environ {\n\t\tk, v, _ := strings.Cut(kv, \"=\")\n\t\tif strings.HasPrefix(k, \"NOTES_\") && !slices.Contains(known, k) {\n\t\t\terrs = append(errs, fmt.Errorf(\"%s: unknown setting\", k))\n\t\t}\n\t\tenv[k] = v\n\t}\n\tstr := func(key, def string, allowed ...string) string {\n\t\tv, ok := env[key]\n\t\tif !ok {\n\t\t\treturn def\n\t\t}\n\t\tif len(allowed) > 0 && !slices.Contains(allowed, v) {\n\t\t\terrs = append(errs, fmt.Errorf(\"%s: %q is not one of %s\", key, v, strings.Join(allowed, \", \")))\n\t\t}\n\t\treturn v\n\t}\n\tdur := func(key string, def, lo, hi time.Duration) time.Duration {\n\t\tv, ok := env[key]\n\t\tif !ok {\n\t\t\treturn def\n\t\t}\n\t\td, err := time.ParseDuration(v)\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\terrs = append(errs, fmt.Errorf(\"%s: %q is not a duration such as 5s\", key, v))\n\t\tcase d < lo || d > hi:\n\t\t\terrs = append(errs, fmt.Errorf(\"%s: %s is outside %s..%s\", key, d, lo, hi))\n\t\t}\n\t\treturn d\n\t}\n\n\tc := Config{\n\t\tAddr:              str(\"NOTES_ADDR\", \":8080\"),\n\t\tMode:              str(\"NOTES_MODE\", \"release\", \"release\", \"debug\"),\n\t\tStore:             str(\"NOTES_STORE\", \"memory\", \"memory\", \"postgres\"),\n\t\tReadHeaderTimeout: dur(\"NOTES_READ_HEADER_TIMEOUT\", 5*time.Second, time.Second, 30*time.Second),\n\t\tShutdownTimeout:   dur(\"NOTES_SHUTDOWN_TIMEOUT\", 20*time.Second, time.Second, 25*time.Second),\n\t\tIdempotencyTTL:    dur(\"NOTES_IDEMPOTENCY_TTL\", 24*time.Hour, time.Hour, 7*24*time.Hour),\n\t\tMaxBodyBytes:      1 << 20,\n\t}\n\tif v, ok := env[\"NOTES_MAX_BODY_BYTES\"]; ok {\n\t\tn, err := strconv.ParseInt(v, 10, 64)\n\t\tif err != nil || n < 1024 || n > 10<<20 {\n\t\t\terrs = append(errs, fmt.Errorf(\"NOTES_MAX_BODY_BYTES: %q must be an integer in 1024..%d\", v, 10<<20))\n\t\t}\n\t\tc.MaxBodyBytes = n\n\t}\n\tif _, _, err := net.SplitHostPort(c.Addr); err != nil {\n\t\terrs = append(errs, fmt.Errorf(\"NOTES_ADDR: %q is not host:port\", c.Addr))\n\t}\n\tif v := env[\"NOTES_TRUSTED_PROXIES\"]; v != \"\" {\n\t\tfor _, s := range strings.Split(v, \",\") {\n\t\t\tp, err := parseProxy(strings.TrimSpace(s))\n\t\t\tswitch {\n\t\t\tcase err != nil:\n\t\t\t\terrs = append(errs, fmt.Errorf(\"NOTES_TRUSTED_PROXIES: %q is not an IP or CIDR prefix\", s))\n\t\t\tcase p.Bits() == 0:\n\t\t\t\terrs = append(errs, fmt.Errorf(\"NOTES_TRUSTED_PROXIES: %s would trust every client\", p))\n\t\t\tdefault:\n\t\t\t\tc.TrustedProxies = append(c.TrustedProxies, p)\n\t\t\t}\n\t\t}\n\t}\n\tif raw, ok := env[\"NOTES_DATABASE_URL\"]; ok {\n\t\tu, err := url.Parse(raw)\n\t\tif err != nil || u.Scheme != \"postgres\" || u.Host == \"\" {\n\t\t\terrs = append(errs, errors.New(\"NOTES_DATABASE_URL: must be a postgres:// URL with a host\"))\n\t\t}\n\t\tc.DatabaseURL = u\n\t}\n\tif c.Store == \"postgres\" && c.DatabaseURL == nil {\n\t\terrs = append(errs, errors.New(\"NOTES_DATABASE_URL: required when NOTES_STORE=postgres\"))\n\t}\n\treturn c, errors.Join(errs...)\n}\n\nfunc parseProxy(s string) (netip.Prefix, error) {\n\tif p, err := netip.ParsePrefix(s); err == nil {\n\t\treturn p.Masked(), nil\n\t}\n\ta, err := netip.ParseAddr(s)\n\tif err != nil {\n\t\treturn netip.Prefix{}, err\n\t}\n\treturn netip.PrefixFrom(a, a.BitLen()), nil\n}\n\n// String is what startup logs print: every effective value, secrets redacted.\nfunc (c Config) String() string {\n\tdb := \"none\"\n\tif c.DatabaseURL != nil {\n\t\tdb = c.DatabaseURL.Redacted()\n\t}\n\treturn fmt.Sprintf(\"addr=%s mode=%s store=%s db=%s read_header=%s shutdown=%s max_body=%d idem_ttl=%s proxies=%v\",\n\t\tc.Addr, c.Mode, c.Store, db, c.ReadHeaderTimeout, c.ShutdownTimeout, c.MaxBodyBytes, c.IdempotencyTTL, c.TrustedProxies)\n}\n\nfunc main() {\n\tgood := []string{\n\t\t\"HOME=/home/app\",\n\t\t\"NOTES_STORE=postgres\",\n\t\t\"NOTES_DATABASE_URL=postgres://notes_rw:s3cret@db.internal:5432/notes\",\n\t\t\"NOTES_TRUSTED_PROXIES=10.0.0.0/8, 192.0.2.10\",\n\t}\n\tif c, err := Load(good); err == nil {\n\t\tfmt.Println(\"config ok:\", c)\n\t}\n\n\tif c, err := Load(nil); err == nil {\n\t\tfmt.Println(\"defaults:\", c)\n\t}\n\n\tbad := []string{\n\t\t\"NOTES_STORE=postgres\",\n\t\t\"NOTES_READ_HEADER_TIMEOUT=5\",\n\t\t\"NOTES_SHUTDOWN_TIMEOUT=45s\",\n\t\t\"NOTES_SHUTDOWN_TIMOUT=10s\",\n\t\t\"NOTES_ADDR=8080\",\n\t\t\"NOTES_TRUSTED_PROXIES=0.0.0.0/0\",\n\t}\n\tif _, err := Load(bad); err != nil {\n\t\tfmt.Println(\"refusing to start:\")\n\t\tfor _, line := range strings.Split(err.Error(), \"\\n\") {\n\t\t\tfmt.Println(\"  \" + line)\n\t\t}\n\t}\n}","language":"go","title":"Load, validate and print the effective settings","walkthrough":"The first configuration is valid: the database URL prints with its password replaced by xxxxx, because URL.Redacted masks only the password component, and the single proxy address becomes a /32 prefix. HOME is ignored because only the NOTES_ prefix is checked. With no variables at all the defaults are complete and conservative: release mode, bounded timeouts and no trusted proxies; the memory store default suits development, and a production deploy sets NOTES_STORE=postgres. The bad configuration reports six problems at once: a misspelled name, a duration without a unit, a shutdown budget above the 25-second ceiling, an address without a colon, a proxy range that would trust every client and a missing database URL that the postgres store requires."},{"body":"main does nothing but call run and translate its error into an exit status. run loads configuration, creates the signal context, builds the graph from the inside out, binds the listener, serves, and on a signal drains with a budget. Every constructor from the earlier lessons appears exactly once here, and no other package names a concrete type from another package.","code":"// cmd/api/main.go, package main\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/signal\"\n\t\"syscall\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n\n\t\"example.com/notes-api/internal/config\"\n\t\"example.com/notes-api/internal/httpapi\"\n\t\"example.com/notes-api/internal/notes\"\n\t\"example.com/notes-api/internal/store\"\n)\n\nfunc main() {\n\tif err := run(os.Environ()); err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"notes-api:\", err)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc run(environ []string) error {\n\tcfg, err := config.Load(environ)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid configuration:\\n%w\", err)\n\t}\n\tlog := slog.New(slog.NewJSONHandler(os.Stderr, nil))\n\tlog.Info(\"config\", \"effective\", cfg.String())\n\n\tctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)\n\tdefer stop()\n\n\t// Wire from the inside out: store -> service -> handlers -> engine -> server.\n\tst := store.NewMemory() // a Postgres adapter would be opened here and closed after Shutdown\n\tsvc, err := notes.NewService(st, time.Now, notes.RandomIDs)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgin.SetMode(cfg.Mode) // before gin.New; GIN_MODE is ignored from here on\n\tengine, err := httpapi.NewRouter(httpapi.NewHandler(svc, log), httpapi.Options{\n\t\tMaxBodyBytes:   cfg.MaxBodyBytes,\n\t\tIdempotencyTTL: cfg.IdempotencyTTL,\n\t\tTrustedProxies: cfg.TrustedProxyStrings(),\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\tsrv := &http.Server{\n\t\tHandler:           engine,\n\t\tReadHeaderTimeout: cfg.ReadHeaderTimeout,\n\t\tIdleTimeout:       time.Minute,\n\t\t// No BaseContext(ctx): a signal must not cancel requests that are draining.\n\t}\n\n\tln, err := net.Listen(\"tcp\", cfg.Addr) // a busy port fails here, before \"listening\" is logged\n\tif err != nil {\n\t\treturn err\n\t}\n\tserveErr := make(chan error, 1)\n\tgo func() { serveErr <- srv.Serve(ln) }()\n\tlog.Info(\"listening\", \"addr\", ln.Addr().String())\n\n\tselect {\n\tcase err := <-serveErr:\n\t\treturn fmt.Errorf(\"serve: %w\", err)\n\tcase <-ctx.Done():\n\t\tlog.Info(\"shutting down\", \"cause\", context.Cause(ctx).Error())\n\t}\n\tstop() // restore default handling: a second Ctrl-C ends the process at once\n\n\tshutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.ShutdownTimeout)\n\tdefer cancel()\n\tif err := srv.Shutdown(shutdownCtx); err != nil {\n\t\t_ = srv.Close() // budget spent: drop what is left rather than hang\n\t\treturn fmt.Errorf(\"shutdown: %w\", err)\n\t}\n\tif err := <-serveErr; !errors.Is(err, http.ErrServerClosed) {\n\t\treturn err\n\t}\n\tlog.Info(\"stopped\")\n\treturn nil\n}","language":"go","title":"The composition root","walkthrough":"Run this fragment in your own environment; it opens a real socket. Because run returns errors instead of exiting, its deferred calls always execute before os.Exit. gin.SetMode runs before NewRouter calls gin.New, and NewRouter returns the error from SetTrustedProxies, so a bad list stops startup. net.Listen binds before the serving goroutine starts, so a busy port is an immediate error rather than a log line from a goroutine. On SIGTERM the context is cancelled and context.Cause reports \"terminated signal received\". stop restores default signal handling, Shutdown drains within cfg.ShutdownTimeout using a fresh context, Close drops whatever remains if the budget runs out, and ErrServerClosed from Serve is the normal result."},{"body":"Do not pass the signal context to http.Server.BaseContext. Every request context derives from it, so the first SIGTERM would cancel the very requests Shutdown is trying to let finish. Gin reads GIN_MODE once, in its package init, and the fragment then overrides it with SetMode; pick one source of truth, here the validated config, so two settings cannot disagree. The 25-second ceiling on the shutdown budget exists to fit under a platform grace period such as the Kubernetes default of 30 seconds, leaving time for the remaining teardown. Readiness withdrawal, header and idle timeouts, and joining background workers are covered in the server-lifecycle lesson; this root only has to give them one owner and one budget. If a Postgres adapter replaces the memory store, open it before the listener and close it after Shutdown returns, so no request runs against a closed pool.","title":"Startup and shutdown details that bite"},{"body":"Load is a pure function of a slice, so a table test covers every rule: each default, each range edge, each unknown name, the redacted String output and the combined error text. The composition root is harder to unit test, which is why it should stay thin. A useful refactor is run(ctx, environ) with the signal context created in main: an integration test can then start the service on 127.0.0.1:0, send one request, cancel the context and assert a clean return within the budget, without sending real signals. Log the effective configuration once at startup; when an incident starts with \"which timeout was this pod running with?\", that line answers it.","title":"Test startup like any other code"}],"takeaway":"Parse configuration into a typed, bounded struct that reports every error at once and redacts secrets, then wire store, service, handlers, engine and server in main, with signal.NotifyContext starting a budgeted Shutdown.","title":"Start from validated configuration and wire the whole service in one composition root","unitID":"gin-project","wrongAnswers":["Shutdown would then wait forever for that context","BaseContext applies only to HTTP/2 connections"]},{"conceptTag":"gin.context-fallback","designGuide":{"cautions":["Never use c or c.Writer after the handler returns; the pool hands it to the next request.","context.WithoutCancel also drops the deadline, so add your own timeout and shutdown hook."],"cost":"Threading ctx through every service signature and typing c.Request.Context() at each call site; detached work needs its own lifetime management.","family":"gin","flow":["Take c.Request.Context()","Pass ctx to every store","Copy data, never keep c","Detach with WithoutCancel"],"ratings":[],"strengths":["Cancellation, deadlines and trace values reach every store call regardless of engine flags.","Background work has an explicit owner, budget and shutdown path."]},"hint":"Look at what Done and Err check before they delegate to c.Request.","id":"gin.context-fallback","introduction":"store.Query(c) compiles because *gin.Context implements context.Context, and in a default Gin engine it quietly throws away cancellation, deadlines and tracing values. The context passed to data access decides whether a query stops when its client leaves and whether background work outlives the response. Gin hands you two candidates, and only one of them is a real request context.","nuance":"Deadline, Done and Err delegate to c.Request.Context() only when engine.ContextWithFallback is true, and gin.New leaves it false, so the store never learns the client left. Passing c.Request.Context() works under either setting.","objective":"Predict what *gin.Context returns as a context.Context under each ContextWithFallback setting and give stores and background work a context that is actually canceled, or deliberately not.","question":"In Gin v1.12.0 with gin.New() defaults, a handler calls store.Query(c) and the client disconnects mid-query. What does the store see through that context?","references":["https://pkg.go.dev/github.com/gin-gonic/gin#Context.Done","https://pkg.go.dev/github.com/gin-gonic/gin#Context.Copy","https://pkg.go.dev/net/http#Request.Context","https://pkg.go.dev/context#WithoutCancel"],"reviewAnswer":"Never canceled: Done is nil and Err stays nil","reviewPrompt":"c as a context under gin.New()?","sections":[{"body":"c.Request.Context() belongs to net/http. The server cancels it when the client's connection closes, when an HTTP/2 stream is reset, or when ServeHTTP returns, and middleware derives deadlines and values from it with WithTimeout and WithValue. *gin.Context is something else: a mutable struct that the engine takes from a sync.Pool for each request, fills with the request, route params and keys, and puts back when the chain returns. It implements Deadline, Done, Err and Value so that it can be passed where a context.Context is expected, but those four methods are an adapter whose behavior depends on an engine flag. The request-deadlines lesson showed what happens when a hung store is given c. This lesson takes the adapter apart, follows c back into the pool and works out what c.Copy is actually for.","title":"Two contexts travel with every Gin request"},{"body":"In context.go, Deadline, Done and Err first call hasRequestContext, which is true only when engine.ContextWithFallback is set and c.Request has a context. Otherwise Deadline reports ok=false, Done returns nil and Err returns nil. A nil channel is never ready, so a select on c.Done() waits forever, and a driver that checks ctx.Err() before each round trip never finds a reason to stop. Value has a fixed lookup order. The key gin.ContextRequestKey, the constant 0 of type gin.ContextKeyType, returns c.Request. The string gin.ContextKey returns c itself. Any other string key is looked up in c.Keys. Only after that, and only with fallback on, does the lookup reach c.Request.Context(). Typed keys, which context.WithValue users and tracing libraries rely on, therefore return nil by default. A typed key stored with c.Set is never found through Value at all, because only string keys consult c.Keys; the middleware-basics lesson met the same gap from the other side. Both gin.New() and gin.Default() leave ContextWithFallback false.","title":"Read the adapter in the v1.12.0 source"},{"body":"The program models a driver that refuses work for a finished context and reads a trace ID the way an instrumented client would. A middleware stores the trace ID in the request context and a tenant in c.Keys. The same routes run on two engines, fallback off and on, with a request whose context carries a deadline and whose client has already gone. The last request starts work that runs after the handler has returned and the request context has been canceled, which is what net/http does when ServeHTTP returns.","code":"package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// traceKey is a typed context key, the way tracing libraries store spans.\ntype traceKey struct{}\n\n// Store models a database driver: it refuses work for a finished context\n// and reads request-scoped values from the context it is given.\ntype Store struct{ queries int }\n\nfunc (s *Store) Query(ctx context.Context) string {\n\tif err := ctx.Err(); err != nil {\n\t\treturn \"skipped: \" + err.Error()\n\t}\n\ts.queries++\n\ttrace, _ := ctx.Value(traceKey{}).(string)\n\treturn fmt.Sprintf(\"ran query %d, trace=%q\", s.queries, trace)\n}\n\n// tracing stores a trace ID in the request context and a tenant in c.Keys.\nfunc tracing(c *gin.Context) {\n\tctx := context.WithValue(c.Request.Context(), traceKey{}, \"t-42\")\n\tc.Request = c.Request.WithContext(ctx)\n\tc.Set(\"tenant\", \"acme\")\n\tc.Next()\n}\n\nfunc newRouter(fallback bool, store *Store, later *[]func()) *gin.Engine {\n\tr := gin.New()\n\tr.ContextWithFallback = fallback\n\tr.Use(tracing)\n\tr.GET(\"/inspect\", func(c *gin.Context) {\n\t\t_, hasDeadline := c.Deadline()\n\t\tc.String(http.StatusOK, \"Deadline ok=%t, Done nil=%t, Err=%v, trace=%v, tenant=%v\",\n\t\t\thasDeadline, c.Done() == nil, c.Err(), c.Value(traceKey{}), c.Value(\"tenant\"))\n\t})\n\tr.GET(\"/via-gin\", func(c *gin.Context) {\n\t\tc.String(http.StatusOK, \"%s\", store.Query(c)) // compiles: *gin.Context is a context.Context\n\t})\n\tr.GET(\"/via-request\", func(c *gin.Context) {\n\t\tc.String(http.StatusOK, \"%s\", store.Query(c.Request.Context()))\n\t})\n\tr.GET(\"/after\", func(c *gin.Context) {\n\t\treq, cp := c.Request, c.Copy()\n\t\tdetached := context.WithoutCancel(c.Request.Context())\n\t\tc.Set(\"tenant\", \"changed after Copy\")\n\t\t*later = append(*later,\n\t\t\tfunc() { fmt.Println(\"  copy shares the request:\", cp.Request == req) },\n\t\t\tfunc() { fmt.Println(\"  copy keeps its own Keys: tenant =\", cp.Value(\"tenant\")) },\n\t\t\tfunc() { fmt.Println(\"  store(cp.Request.Context()):\", store.Query(cp.Request.Context())) },\n\t\t\tfunc() { fmt.Println(\"  store(WithoutCancel):\", store.Query(detached)) },\n\t\t)\n\t\tc.Status(http.StatusAccepted)\n\t})\n\treturn r\n}\n\n// call sends one request whose context carries a deadline and, if gone is\n// true, has already been canceled, as when a client disconnects.\nfunc call(r http.Handler, path string, gone bool) string {\n\tctx, cancel := context.WithDeadline(context.Background(), time.Date(2100, 1, 1, 0, 0, 0, 0, time.UTC))\n\tdefer cancel()\n\tif gone {\n\t\tcancel()\n\t}\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil).WithContext(ctx))\n\treturn w.Body.String()\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tstore := &Store{}\n\tvar later []func()\n\toff := newRouter(false, store, &later)\n\ton := newRouter(true, store, &later)\n\n\tfmt.Println(\"c as context.Context, client gone:\")\n\tfmt.Println(\"  fallback off:\", call(off, \"/inspect\", true))\n\tfmt.Println(\"  fallback on: \", call(on, \"/inspect\", true))\n\n\tfmt.Println(\"store calls when the client is gone:\")\n\tfmt.Println(\"  store(c), fallback off:\", call(off, \"/via-gin\", true))\n\tfmt.Println(\"  store(c.Request.Context()):\", call(off, \"/via-request\", true))\n\tfmt.Println(\"  store(c), fallback on:\", call(on, \"/via-gin\", true))\n\tfmt.Println(\"store(c.Request.Context()), client still here:\", call(off, \"/via-request\", false))\n\n\tfmt.Println(\"work that runs after the handler returned:\")\n\tctx, cancel := context.WithCancel(context.Background())\n\tw := httptest.NewRecorder()\n\toff.ServeHTTP(w, httptest.NewRequest(http.MethodGet, \"/after\", nil).WithContext(ctx))\n\tcancel() // net/http cancels the request context once ServeHTTP returns\n\tfor _, f := range later {\n\t\tf()\n\t}\n}","language":"go","title":"Hand the same store both contexts","walkthrough":"With fallback off, c reports no deadline, a nil Done channel and a nil Err for a request whose context is both deadlined and canceled. Only the string key tenant survives, because Value finds it in c.Keys, while the typed trace key comes back nil. store(c) therefore runs a query for a client that left and loses the trace ID, and store(c.Request.Context()) sees context.Canceled on either engine. With fallback on, c delegates and behaves like the request context. In the /after handler, c.Copy shares the *http.Request, so the copy's request context is canceled as soon as the request ends, while its Keys are a snapshot: the c.Set after Copy does not reach it. context.WithoutCancel keeps the trace value and drops the cancellation. The deferred closures capture req, cp and detached, never c."},{"body":"engine.ServeHTTP takes a *gin.Context from engine.pool, points it at the new writer and request, resets its params, keys, errors and query cache, runs the chain and puts it back. Identity therefore belongs to a pool slot, not to a request. A goroutine that kept c after the handler returned holds a pointer that the next request will fill: c.Param returns another caller's ID, c.Keys holds another principal or nothing, c.Request is a stranger's request, and with fallback on c.Done becomes the stranger's cancellation, so your background work stops when someone else disconnects. Every one of those reads is a data race with the reset in the next ServeHTTP. ContextWithFallback fixes none of it, and even c.Request.Context(), captured honestly before returning, is canceled right after ServeHTTP returns. The race detector reports the bug only when a test actually reuses the context while the goroutine still reads it, so drive handlers that start goroutines with a burst of requests under go test -race.","title":"The handler returns and the pool takes c back"},{"body":"Copy builds a new Context that shares the same *http.Request, clones Keys with maps.Clone, copies Params and keeps the full path and the engine. It detaches the writer: the copy's underlying ResponseWriter is nil, so a write through cp.Writer panics instead of corrupting a recycled response, and its handler index is set to the abort value, so cp.Next does nothing. maps.Clone is shallow, so a pointer or slice stored in Keys is still shared with the handler. Errors and Accepted are not copied, and no lifetime is extended. Use Copy when a goroutine needs request data such as params, keys or c.FullPath() after the handler returns. Use neither c nor the copy as the goroutine's context: with fallback off it is never canceled, and with fallback on it is canceled the moment the response is done. Build the work's input as a value and give it a context you own.","code":"func (h *Handlers) publish(c *gin.Context) {\n\tev := AuditEvent{Route: c.FullPath(), NoteID: c.Param(\"id\"), Tenant: tenantFrom(c)}\n\tbase := context.WithoutCancel(c.Request.Context()) // keeps trace values, drops cancellation\n\th.wg.Add(1)\n\tgo func() {\n\t\tdefer h.wg.Done()\n\t\tctx, cancel := context.WithTimeout(base, 5*time.Second)\n\t\tdefer cancel()\n\t\tstop := context.AfterFunc(h.shutdown, cancel) // also stop when the process drains\n\t\tdefer stop()\n\t\tif err := h.audit.Write(ctx, ev); err != nil {\n\t\t\th.log.ErrorContext(ctx, \"audit write failed\", \"err\", err)\n\t\t}\n\t}()\n\tc.Status(http.StatusAccepted)\n}","language":"go","title":"What c.Copy hands a goroutine, and what it does not","walkthrough":"This fragment belongs to a real service and runs in your own environment; Handlers, AuditEvent and tenantFrom are your types. The event is a plain value built before the goroutine starts, so the goroutine never touches c. WithoutCancel also drops the deadline, so the goroutine sets its own five-second budget, and context.AfterFunc cancels it when the service's shutdown context ends; shutdown then waits on h.wg. The log call still carries the trace values from the request. Work that must survive a crash belongs in a durable queue instead, as the context-workers lesson explains."},{"body":"Make one rule for the codebase: functions below the HTTP layer take ctx context.Context as their first parameter, and handlers pass c.Request.Context(). The rule works with any engine and is obvious in review. Turning ContextWithFallback on is still a reasonable safety net, because helpers that accept a context.Context then receive cancellation and tracing values when someone passes c by mistake. Set it once while building the engine; it is a plain field read on every call, so changing it while serving is a data race. Expect behavior to change when you flip it: code that was silently never canceled starts returning context.Canceled, which usually exposes a goroutine that kept c. Neither setting rescues retention, and typed keys stored with c.Set still never reach Value. The compiler accepts c wherever a context is expected, so add a small go/analysis check that reports a *gin.Context passed to a context.Context parameter, and keep a test like the program's that sends a canceled request and asserts the store saw it.","title":"Decide on ContextWithFallback once, then review for c"}],"takeaway":"Pass c.Request.Context() to stores and goroutines. *gin.Context is a pooled struct whose context methods go dead unless ContextWithFallback is set, c.Copy copies request data rather than a lifetime, and detached work needs WithoutCancel plus a deadline you own.","title":"*gin.Context is a pooled struct, not your request context: pass c.Request.Context() to stores and goroutines","unitID":"gin-data","wrongAnswers":["context.Canceled, because c wraps the request context","context.DeadlineExceeded once WriteTimeout expires"]},{"conceptTag":"gin.patch-merge","designGuide":{"cautions":["Arrays are replaced whole and null cannot be stored as a value; use JSON Patch when that matters.","Read, merge and write still need If-Match or a version check across replicas."],"cost":"A generic decode, a merge and a second strict decode per request, plus media-type checks and error mapping that plain struct binding does not need.","family":"gin","flow":["Require merge-patch type","Decode to a generic map","Merge into current doc","Decode strictly, validate"],"ratings":[],"strengths":["Clients can leave, clear or replace each member exactly as RFC 7396 defines.","Validation sees the resource the store will hold, not a fragment of it."]},"hint":"Compare the field after decoding {} with the field after decoding {\"due\":null}.","id":"gin.patch-merge","introduction":"A client that wants to clear a due date sends {\"due\": null}; a client that only renames a note leaves due out entirely. If the server cannot tell those requests apart, it either ignores the clear or wipes a field nobody mentioned. JSON Merge Patch gives the three cases exact meanings, and Gin's struct binding cannot see one of them.","nuance":"encoding/json sets a pointer to nil for JSON null, which is also what an absent member leaves behind, so the handler cannot tell \"clear it\" from \"leave it alone\". A map of json.RawMessage or a tri-state type keeps the two apart.","objective":"Implement an RFC 7396 merge-patch endpoint in Gin that distinguishes absent from null, enforces application/merge-patch+json with 415, and validates the merged result before storing it.","question":"A PATCH handler binds {\"due\": null} with ShouldBindJSON into a struct whose Due field is *string. Why can it not clear the due date correctly?","references":["https://www.rfc-editor.org/rfc/rfc7396","https://www.rfc-editor.org/rfc/rfc5789","https://pkg.go.dev/encoding/json#Unmarshal","https://pkg.go.dev/github.com/gin-gonic/gin/binding#Default"],"reviewAnswer":"null and absent both leave the pointer nil","reviewPrompt":"Why can't *string mark JSON null?","sections":[{"body":"RFC 7396 defines a merge patch as a JSON document that mirrors the target. For each member of a patch object, an absent member leaves the target alone, null removes the member, an object merges recursively, and any other value, arrays included, replaces the member whole. A patch that is not an object replaces the entire target. The media type is application/merge-patch+json, and claiming merge-patch semantics means honoring all of these rules, not just the convenient ones. The crud-resource lesson used pointer fields for PATCH and noted that they cannot express removal; this lesson builds the full version, including nested objects, strict decoding and the error statuses a client can program against.","title":"Three meanings in one small document"},{"body":"encoding/json sets a pointer field to nil when the member is null, and nil is also what an absent member leaves behind, so {} and {\"due\":null} bind to identical structs. ShouldBindJSON adds nothing that helps here: in v1.12.0 it runs a json.Decoder over the body and then the validator, and it never looks at Content-Type. c.ShouldBind is worse for this route, because it picks a binding from Content-Type through binding.Default, and application/merge-patch+json is not in that table, so it falls back to form binding and never decodes the JSON body at all. Two representations keep the information. A map[string]json.RawMessage records presence as a key and null as the four raw bytes null. A small tri-state type with an UnmarshalJSON method works too, because encoding/json calls UnmarshalJSON for a present null but not for an absent member.","title":"Why struct binding cannot hear null"},{"body":"The program first decodes the same three bodies into a pointer field and into a raw map, so the difference is visible. The handler then checks the media type, decodes the patch generically, refuses members a client may not change, and merges the patch into the current note represented as a generic JSON document. It turns the merged document back into a Note with unknown fields disallowed and validates that Note with Gin's validator before storing it.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"mime\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/gin-gonic/gin/binding\"\n\t\"github.com/go-playground/validator/v10\"\n)\n\ntype Settings struct {\n\tColor  string `json:\"color,omitempty\" binding:\"omitempty,oneof=red blue green\"`\n\tPinned bool   `json:\"pinned\"`\n}\n\ntype Note struct {\n\tID       int      `json:\"id\"`\n\tTitle    string   `json:\"title\" binding:\"required,max=40\"`\n\tDue      string   `json:\"due,omitempty\" binding:\"omitempty,datetime=2006-01-02\"`\n\tTags     []string `json:\"tags,omitempty\" binding:\"max=3,dive,min=1,max=12\"`\n\tSettings Settings `json:\"settings\"`\n}\n\n// patchable lists the top-level members a client may change; id is read-only.\nvar patchable = map[string]bool{\"title\": true, \"due\": true, \"tags\": true, \"settings\": true}\n\n// mergePatch is the algorithm of RFC 7396, section 2: objects merge member by\n// member, null removes a member, and anything else replaces the target.\nfunc mergePatch(target, patch any) any {\n\tp, ok := patch.(map[string]any)\n\tif !ok {\n\t\treturn patch\n\t}\n\tt, ok := target.(map[string]any)\n\tif !ok {\n\t\tt = map[string]any{}\n\t}\n\tfor k, v := range p {\n\t\tif v == nil {\n\t\t\tdelete(t, k)\n\t\t} else {\n\t\t\tt[k] = mergePatch(t[k], v)\n\t\t}\n\t}\n\treturn t\n}\n\n// decodeOne reads exactly one JSON value and keeps numbers exact.\nfunc decodeOne(r io.Reader, v any) error {\n\tdec := json.NewDecoder(r)\n\tdec.UseNumber()\n\tif err := dec.Decode(v); err != nil {\n\t\treturn err\n\t}\n\tif err := dec.Decode(new(any)); err != io.EOF {\n\t\treturn errors.New(\"trailing data after the JSON value\")\n\t}\n\treturn nil\n}\n\nfunc apply(current Note, patch any) (Note, error) {\n\tdoc, _ := json.Marshal(current)\n\tvar target any\n\tif err := decodeOne(bytes.NewReader(doc), &target); err != nil {\n\t\treturn Note{}, err\n\t}\n\tmerged, _ := json.Marshal(mergePatch(target, patch))\n\tdec := json.NewDecoder(bytes.NewReader(merged))\n\tdec.DisallowUnknownFields()\n\tvar next Note\n\tif err := dec.Decode(&next); err != nil {\n\t\treturn Note{}, err\n\t}\n\treturn next, binding.Validator.ValidateStruct(&next) // validate the result, not the patch\n}\n\nfunc newRouter() *gin.Engine {\n\tvar mu sync.Mutex\n\tnotes := map[int]Note{7: {ID: 7, Title: \"Ship v2\", Due: \"2026-12-01\",\n\t\tTags: []string{\"go\", \"api\"}, Settings: Settings{Color: \"blue\", Pinned: true}}}\n\n\tr := gin.New()\n\tr.PATCH(\"/notes/7\", func(c *gin.Context) {\n\t\tmt, _, err := mime.ParseMediaType(c.GetHeader(\"Content-Type\"))\n\t\tif err != nil || mt != \"application/merge-patch+json\" {\n\t\t\tc.Header(\"Accept-Patch\", \"application/merge-patch+json\")\n\t\t\tc.AbortWithStatusJSON(http.StatusUnsupportedMediaType, gin.H{\"error\": \"use application/merge-patch+json\"})\n\t\t\treturn\n\t\t}\n\t\tvar patch any\n\t\tif err := decodeOne(http.MaxBytesReader(c.Writer, c.Request.Body, 16<<10), &patch); err != nil {\n\t\t\tc.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\"error\": \"malformed JSON\"})\n\t\t\treturn\n\t\t}\n\t\tobj, ok := patch.(map[string]any)\n\t\tif !ok {\n\t\t\tc.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{\"error\": \"patch must be a JSON object\"})\n\t\t\treturn\n\t\t}\n\t\tfor k := range obj {\n\t\t\tif !patchable[k] {\n\t\t\t\tc.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{\"error\": \"member not patchable: \" + k})\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tmu.Lock()\n\t\tdefer mu.Unlock()\n\t\tnext, err := apply(notes[7], patch)\n\t\tvar invalid validator.ValidationErrors\n\t\tswitch {\n\t\tcase errors.As(err, &invalid):\n\t\t\tfields := make([]string, len(invalid))\n\t\t\tfor i, fe := range invalid {\n\t\t\t\tfields[i] = fe.Namespace() + \" \" + fe.Tag()\n\t\t\t}\n\t\t\tc.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{\"error\": \"invalid result\", \"fields\": fields})\n\t\t\treturn\n\t\tcase err != nil:\n\t\t\tc.AbortWithStatusJSON(http.StatusUnprocessableEntity, gin.H{\"error\": err.Error()})\n\t\t\treturn\n\t\t}\n\t\tnotes[7] = next\n\t\tc.JSON(http.StatusOK, next)\n\t})\n\treturn r\n}\n\ntype pointerDTO struct {\n\tTitle *string `json:\"title\"`\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\n\tfmt.Println(\"what each decoding target can see:\")\n\tfor _, body := range []string{`{}`, `{\"title\":null}`, `{\"title\":\"x\"}`} {\n\t\tvar dto pointerDTO\n\t\t_ = json.Unmarshal([]byte(body), &dto)\n\t\tvar raw map[string]json.RawMessage\n\t\t_ = json.Unmarshal([]byte(body), &raw)\n\t\tpointer, member := \"nil\", \"absent\"\n\t\tif dto.Title != nil {\n\t\t\tpointer = fmt.Sprintf(\"%q\", *dto.Title)\n\t\t}\n\t\tif m, ok := raw[\"title\"]; ok {\n\t\t\tmember = string(m)\n\t\t}\n\t\tfmt.Printf(\"  %-16s pointer field: %-5s map member: %s\\n\", body, pointer, member)\n\t}\n\n\tr := newRouter()\n\tsend := func(contentType, body string) {\n\t\treq := httptest.NewRequest(http.MethodPatch, \"/notes/7\", strings.NewReader(body))\n\t\treq.Header.Set(\"Content-Type\", contentType)\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tfmt.Printf(\"PATCH %s\\n  %d %s\\n\", body, w.Code, w.Body.String())\n\t\tif v := w.Header().Get(\"Accept-Patch\"); v != \"\" {\n\t\t\tfmt.Println(\"  Accept-Patch:\", v)\n\t\t}\n\t}\n\tconst mp = \"application/merge-patch+json\"\n\tsend(mp, `{\"due\":null,\"tags\":[\"go\"]}`)\n\tsend(\"Application/Merge-Patch+JSON\", `{\"title\":\"Ship v2.1\",\"settings\":{\"color\":null}}`)\n\tsend(mp, `{\"title\":null}`)\n\tsend(mp, `{\"id\":8}`)\n\tsend(mp, `{\"settings\":{\"colour\":\"red\"}}`)\n\tsend(mp, `{\"tags\":[\"go\"]} {\"tags\":[]}`)\n\tsend(\"application/json\", `{\"title\":\"Ship v3\"}`)\n}","language":"go","title":"Merge, decode strictly, validate","walkthrough":"The pointer is nil for both {} and null, while the map distinguishes absent from null. mime.ParseMediaType lowercases the type and drops parameters, so Application/Merge-Patch+JSON is accepted; c.ContentType() only strips parameters, so comparing its result to a lowercase constant would reject that client. decodeOne reads one value, keeps numbers as json.Number so large integers survive the round trip, and rejects trailing data, which is why the body with two objects is a 400. mergePatch is the RFC 7396 algorithm. Decoding the merged document with DisallowUnknownFields refuses a misspelled nested member such as colour instead of dropping it. Removing due makes it absent, and omitempty keeps it absent on output. {\"title\":null} removes a required member, so validating the merged note gives 422 naming the field. The 415 carries Accept-Patch, as RFC 5789 recommends."},{"body":"Whether a patch is acceptable depends on the state it lands on. {\"title\":null} is a perfectly formed patch that removes a required member, and a tag limit applies to the merged list, not to the members a client happened to send. So the rules live on the resource struct and run on the merged value through binding.Validator.ValidateStruct, the same validator ShouldBindJSON would have used. Read-only members such as id are refused before merging, because a merge would otherwise apply them. Pick statuses clients can act on: 415 with Accept-Patch for the wrong media type, 400 for malformed JSON, 422 for a well-formed patch that is not allowed or produces an invalid resource. The mutex makes read, merge and write one step inside this process. Across replicas the same read-modify-write needs a version check, and the optimistic-concurrency lesson adds If-Match for exactly this endpoint.","title":"Validate the result, not the patch"},{"body":"A generic merge suits resources whose JSON shape matches the stored model. When the public shape differs, or only a few members are patchable, a typed patch DTO reads better. Optional records presence and null separately, and ShouldBindJSON can still decode it because it simply runs encoding/json. Apply the DTO to a copy of the stored resource, then validate the copy exactly as before.","code":"// Optional records whether a member was present and whether it was null.\ntype Optional[T any] struct {\n\tSet   bool // the member appeared in the patch\n\tNull  bool // it appeared as JSON null\n\tValue T    // the zero value when Null is true\n}\n\nfunc (o *Optional[T]) UnmarshalJSON(b []byte) error {\n\to.Set = true // encoding/json calls this only for members that are present\n\tif string(b) == \"null\" {\n\t\to.Null = true\n\t\treturn nil\n\t}\n\treturn json.Unmarshal(b, &o.Value)\n}\n\ntype notePatch struct {\n\tTitle Optional[string] `json:\"title\"`\n\tDue   Optional[string] `json:\"due\"`\n}\n\n// applyTo edits a copy of the stored note; validate the result afterwards.\nfunc (p notePatch) applyTo(n Note) Note {\n\tif p.Title.Set {\n\t\tn.Title = p.Title.Value // null gives \"\", which the required rule rejects\n\t}\n\tif p.Due.Set {\n\t\tn.Due = p.Due.Value // null clears the due date\n\t}\n\treturn n\n}","language":"go","title":"A tri-state field when you prefer a typed DTO","walkthrough":"This fragment plugs into the program's Note type; compile it inside your own service. UnmarshalJSON is never called for an absent member, so Set stays false and applyTo leaves the field alone. For a present null, encoding/json passes the literal bytes null, so Null is set and Value keeps its zero value. Validator tags cannot see inside Optional, which is one more reason to validate the patched Note rather than the DTO. Nested objects need their own Optional fields, or a map, to keep merge semantics below the top level."},{"body":"Go's decoder matches member names to struct fields case-insensitively, so {\"Title\":\"x\"} binds to Title even though the allow-list map checks exact names; decide which behavior is your contract and test it. For duplicate names, encoding/json keeps the last one, and another parser in front of you may keep the first, so a proxy that inspects patches can see a different document from the one you apply. Merge patch also has two semantic gaps: an array can only be replaced whole, so appending one tag means sending the full list, and null can never be stored as a value. When clients need either, use JSON Patch (RFC 6902) or a sub-resource such as POST /notes/7/tags. Cap the body with http.MaxBytesReader, as the binding-limits lesson explains. The test table writes itself: absent, null, value, nested null, a non-object patch, an unknown member, an invalid result and the wrong media type.","title":"What a reviewer should still look for"}],"takeaway":"Accept only application/merge-patch+json, decode the patch into a representation that keeps absent and null apart, merge it into the current resource, and validate the merged result before storing it.","title":"PATCH with JSON Merge Patch in Gin: keep absent, null and value apart, then validate the merged resource","unitID":"gin-data","wrongAnswers":["ShouldBindJSON rejects null members with a 400","null decodes to a pointer to an empty string"]},{"conceptTag":"gin.safe-filters","designGuide":{"cautions":["Each IN list length is a new statement text; prefer = ANY($n) on PostgreSQL.","Leading-wildcard LIKE cannot use a B-tree index, however well it is escaped."],"cost":"A builder type, explicit validation for every parameter and an index for each allowed sort combination.","family":"gin","flow":["Parse RawQuery strictly","Validate, sort, dedupe","Bind every value","Order by constants + id"],"ratings":[],"strengths":["The whole query is a pure function that table tests can pin exactly.","Equivalent requests produce identical SQL and arguments."]},"hint":"Look at what URL.Query does with the error returned by url.ParseQuery.","id":"gin.safe-filters","introduction":"List endpoints accumulate filters one release at a time: a status here, a search box there, a second sort key for the dashboard. Each one is a chance to splice a value into SQL text, to let a percent sign widen a search, or to send IN () to the database. Build the query in one function that owns every placeholder, and test that function without a database.","nuance":"URL.Query discards ParseQuery's error and keeps only the pairs it could parse. A semicolon is no longer a separator, so the whole pair is dropped and the query loses its filter. Parse RawQuery yourself and answer 400.","objective":"Write a pure function that turns a Gin list request into SQL text and arguments, with allow-listed sorts, a placeholder for every value, escaped LIKE patterns, bounded IN lists and a unique tiebreaker.","question":"A Gin handler reads filters with c.QueryArray(\"status\"). In Go 1.17 and later, what happens to the request ?status=open;closed?","references":["https://pkg.go.dev/net/url#ParseQuery","https://pkg.go.dev/github.com/gin-gonic/gin#Context.QueryArray","https://www.postgresql.org/docs/current/functions-matching.html","https://www.postgresql.org/docs/current/queries-order.html"],"reviewAnswer":"The pair is dropped silently: no status filter at all","reviewPrompt":"?status=open;closed via c.Query?","sections":[{"body":"The security.sql-injection lesson explains why statement text and values must reach the driver separately, and the pagination-filtering lesson covers cursors and why sort names go through an allow-list. What remains is the code in between: a function that takes the parsed query string plus the scope from the path or the authenticated principal and returns SQL text and an argument slice. Keeping it free of *gin.Context makes it a pure function, so a table test can assert the exact statement for each request. Keeping every filter in it gives a reviewer one place to check the invariant that matters: SQL text is assembled only from constants your code owns and placeholder numbers the builder generates.","title":"One function between url.Values and QueryContext"},{"body":"c.Query, c.QueryArray and c.ShouldBindQuery all read c.Request.URL.Query(), which ignores the error from url.ParseQuery and keeps only the pairs it could parse. Since Go 1.17 a semicolon is not a separator, so ?status=open;closed loses its only pair and the client silently receives every status. Current Go releases also refuse a query with more than 10,000 pairs as a whole, controlled by the urlmaxqueryparams GODEBUG setting, so the handler sees no parameters at all. Parse c.Request.URL.RawQuery with url.ParseQuery yourself and answer 400 on error, then reject unknown names. Accept lists both as repeated keys and as comma-separated values, validate every element, and only then sort and dedupe. Canonical input means that equivalent requests produce byte-identical SQL and arguments, which keeps statement caches and query statistics small and lets a response cache keyed by the query reuse entries. The project scope comes from the path and is added first and unconditionally; it is not a filter the client may drop.","title":"Parse the raw query strictly, then canonicalize"},{"body":"buildQuery validates each parameter, adds a predicate per filter through a builder whose bind method is the only way to add a value, then appends the allow-listed ORDER BY, the tiebreaker and a bound LIMIT. The handler returns the SQL and arguments as text so the output shows exactly what a driver would receive. No database is involved.","code":"package main\n\nimport (\n\t\"cmp\"\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"slices\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\t\"unicode/utf8\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// sortable maps a public sort key to a column. Only these strings reach SQL.\nvar sortable = map[string]struct {\n\tcolumn   string\n\tnullable bool\n}{\n\t\"created\":  {column: \"created_at\"},\n\t\"priority\": {column: \"priority\"},\n\t\"due\":      {column: \"due_at\", nullable: true},\n}\n\nvar statuses = []string{\"closed\", \"open\", \"triaged\"}\n\nvar allowedParams = []string{\"assignee\", \"created_after\", \"limit\", \"q\", \"sort\", \"status\"}\n\nconst maxAssignees = 20\n\n// likeEscaper makes %, _ and the escape character literal inside a pattern.\nvar likeEscaper = strings.NewReplacer(\"!\", \"!!\", \"%\", \"!%\", \"_\", \"!_\")\n\n// builder collects predicates and arguments; bind is the only way to add a value.\ntype builder struct {\n\twhere []string\n\targs  []any\n}\n\nfunc (b *builder) bind(v any) string {\n\tb.args = append(b.args, v)\n\treturn \"$\" + strconv.Itoa(len(b.args))\n}\n\nfunc (b *builder) in(column string, values []any) {\n\tph := make([]string, len(values))\n\tfor i, v := range values {\n\t\tph[i] = b.bind(v)\n\t}\n\tb.where = append(b.where, column+\" IN (\"+strings.Join(ph, \", \")+\")\")\n}\n\n// list accepts both ?status=a&status=b and ?status=a,b.\nfunc list(values []string) []string {\n\tvar out []string\n\tfor _, v := range values {\n\t\tout = append(out, strings.Split(v, \",\")...)\n\t}\n\treturn out\n}\n\n// canonical sorts and dedupes, so equivalent requests produce the same SQL\n// text and the same arguments.\nfunc canonical[T cmp.Ordered](values []T) []any {\n\tslices.Sort(values)\n\tvalues = slices.Compact(values)\n\tout := make([]any, len(values))\n\tfor i, v := range values {\n\t\tout[i] = v\n\t}\n\treturn out\n}\n\nfunc buildQuery(projectID int64, q url.Values) (string, []any, error) {\n\tfor _, name := range slices.Sorted(maps.Keys(q)) { // sorted: the same error every time\n\t\tif !slices.Contains(allowedParams, name) {\n\t\t\treturn \"\", nil, fmt.Errorf(\"unknown parameter %q\", name)\n\t\t}\n\t}\n\tb := &builder{}\n\tb.where = append(b.where, \"project_id = \"+b.bind(projectID)) // scope first, from the path\n\n\tif values := list(q[\"status\"]); len(values) > 0 {\n\t\tfor _, s := range values {\n\t\t\tif !slices.Contains(statuses, s) {\n\t\t\t\treturn \"\", nil, fmt.Errorf(\"status %q is not one of %v\", s, statuses)\n\t\t\t}\n\t\t}\n\t\tb.in(\"status\", canonical(values))\n\t}\n\tif values := list(q[\"assignee\"]); len(values) > 0 {\n\t\tif len(values) > maxAssignees { // bound the raw input before any work\n\t\t\treturn \"\", nil, fmt.Errorf(\"at most %d assignees\", maxAssignees)\n\t\t}\n\t\tids := make([]int64, len(values))\n\t\tfor i, s := range values {\n\t\t\tid, err := strconv.ParseInt(s, 10, 64)\n\t\t\tif err != nil || id <= 0 {\n\t\t\t\treturn \"\", nil, fmt.Errorf(\"assignee %q is not a positive ID\", s)\n\t\t\t}\n\t\t\tids[i] = id\n\t\t}\n\t\tb.in(\"assignee_id\", canonical(ids))\n\t}\n\tif text := strings.TrimSpace(q.Get(\"q\")); text != \"\" {\n\t\tif utf8.RuneCountInString(text) > 100 {\n\t\t\treturn \"\", nil, errors.New(\"q is longer than 100 characters\")\n\t\t}\n\t\tpattern := \"%\" + likeEscaper.Replace(text) + \"%\"\n\t\tb.where = append(b.where, \"title ILIKE \"+b.bind(pattern)+\" ESCAPE '!'\")\n\t}\n\tif raw := q.Get(\"created_after\"); raw != \"\" {\n\t\tt, err := time.Parse(time.RFC3339, raw)\n\t\tif err != nil {\n\t\t\treturn \"\", nil, errors.New(\"created_after must be RFC 3339\")\n\t\t}\n\t\tb.where = append(b.where, \"created_at > \"+b.bind(t.UTC()))\n\t}\n\n\tvar order []string\n\tseen := map[string]bool{}\n\tfor key := range strings.SplitSeq(q.Get(\"sort\"), \",\") {\n\t\tif key == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tdir, name := \"ASC\", key\n\t\tif rest, ok := strings.CutPrefix(key, \"-\"); ok {\n\t\t\tdir, name = \"DESC\", rest\n\t\t}\n\t\tcol, ok := sortable[name]\n\t\tif !ok || seen[name] || len(seen) == 3 {\n\t\t\treturn \"\", nil, fmt.Errorf(\"bad sort key %q\", key)\n\t\t}\n\t\tseen[name] = true\n\t\tterm := col.column + \" \" + dir\n\t\tif col.nullable {\n\t\t\tterm += \" NULLS LAST\" // the same place for NULL in both directions\n\t\t}\n\t\torder = append(order, term)\n\t}\n\tif len(order) == 0 {\n\t\torder = append(order, \"created_at DESC\")\n\t}\n\torder = append(order, \"id ASC\") // unique tiebreaker: a total, repeatable order\n\n\tlimit := 25\n\tif raw := q.Get(\"limit\"); raw != \"\" {\n\t\tn, err := strconv.Atoi(raw)\n\t\tif err != nil || n < 1 || n > 100 {\n\t\t\treturn \"\", nil, errors.New(\"limit must be 1..100\")\n\t\t}\n\t\tlimit = n\n\t}\n\tsql := \"SELECT id, title, status, priority FROM issues WHERE \" + strings.Join(b.where, \" AND \") +\n\t\t\" ORDER BY \" + strings.Join(order, \", \") + \" LIMIT \" + b.bind(limit)\n\treturn sql, b.args, nil\n}\n\nfunc formatArgs(args []any) string {\n\tparts := make([]string, len(args))\n\tfor i, a := range args {\n\t\tswitch v := a.(type) {\n\t\tcase string:\n\t\t\tparts[i] = strconv.Quote(v)\n\t\tcase time.Time:\n\t\t\tparts[i] = v.Format(time.RFC3339)\n\t\tdefault:\n\t\t\tparts[i] = fmt.Sprint(v)\n\t\t}\n\t}\n\treturn \"[\" + strings.Join(parts, \" \") + \"]\"\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := gin.New()\n\tr.GET(\"/projects/:project/issues\", func(c *gin.Context) {\n\t\tprojectID, err := strconv.ParseInt(c.Param(\"project\"), 10, 64)\n\t\tif err != nil || projectID <= 0 {\n\t\t\tc.AbortWithStatusJSON(http.StatusNotFound, gin.H{\"error\": \"no such project\"})\n\t\t\treturn\n\t\t}\n\t\tquery, err := url.ParseQuery(c.Request.URL.RawQuery) // strict: c.Request.URL.Query drops errors\n\t\tif err != nil {\n\t\t\tc.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\"error\": \"malformed query string\"})\n\t\t\treturn\n\t\t}\n\t\tsql, args, err := buildQuery(projectID, query)\n\t\tif err != nil {\n\t\t\tc.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\t\treturn\n\t\t}\n\t\tc.String(http.StatusOK, \"%s\\n  args: %s\", sql, formatArgs(args))\n\t})\n\n\tfor _, target := range []string{\n\t\t\"/projects/7/issues\",\n\t\t\"/projects/7/issues?status=triaged,open&assignee=42&assignee=9,42&q=100%25_done&sort=-priority,due\",\n\t\t\"/projects/7/issues?status=open&status=triaged&created_after=2026-11-01T09:00:00%2B02:00&limit=50\",\n\t\t\"/projects/7/issues?sort=created%3BDROP+TABLE+issues\",\n\t\t\"/projects/7/issues?status=open;closed\",\n\t\t\"/projects/7/issues?status=open&status=archived\",\n\t\t\"/projects/7/issues?sort=priority,-priority\",\n\t\t\"/projects/7/issues?state=open\",\n\t} {\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil))\n\t\tfmt.Printf(\"GET %s\\n  %d %s\\n\", target, w.Code, w.Body.String())\n\t}\n}","language":"go","title":"Build the statement and print it","walkthrough":"bind appends the value and returns its placeholder, so numbering follows argument order across WHERE, ORDER BY and LIMIT. In the second request triaged,open becomes the sorted pair open, triaged, and the assignee list 42, 9, 42 becomes 9 and 42 after parsing as integers; the raw count is bounded before any parsing. q=100%25_done decodes to 100%_done, and the escaper turns it into the pattern %100!%!_done%, matched literally under ESCAPE '!'; ILIKE is PostgreSQL's case-insensitive LIKE. created_after is parsed as RFC 3339 and passed as a UTC time.Time, never as text. A sort key containing an encoded semicolon is simply not in the map. An unencoded semicolon makes url.ParseQuery fail, which is a 400 here and would have been a missing filter with c.QueryArray. Unknown names are checked in sorted order so the error is deterministic."},{"body":"A placeholder stops injection; it does not make a value mean what the user intended. LIKE treats % and _ in the bound value as wildcards, so escape them and name the escape character in the statement, as the security lesson shows, and cap the length. A pattern with a leading % cannot use an ordinary B-tree index, so contains-search over a large table needs a trigram index or full-text search, not a bigger timeout. IN lists need three guards: bound the raw count before doing work, refuse empty elements, and never emit IN (), which is a syntax error. Every distinct list length is also a distinct statement text, which multiplies prepared statements and plan-cache entries. PostgreSQL can take the whole list as one array argument instead.","code":"// One placeholder per element: the statement text changes with the count.\n//   status IN ($2, $3)\n// One array argument: the statement text is the same for 1 or 20 values.\n//   status = ANY($2)\nfunc (b *builder) anyOf(column string, values any) {\n\tb.where = append(b.where, column+\" = ANY(\"+b.bind(values)+\")\")\n}\n\n// With pgx, a []string or []int64 argument is sent as a PostgreSQL array.\n// With lib/pq, wrap it: b.anyOf(\"assignee_id\", pq.Array(ids)).\nb.anyOf(\"assignee_id\", ids)","language":"go","title":"Lists and patterns are where bound values still go wrong","walkthrough":"This fragment extends the program's builder for PostgreSQL; run it against a real driver in your own environment. = ANY($2) compares the column with each element of one array parameter, so the statement text stays constant whatever the list length, and the bound on the list still applies because it limits the work and the size of the argument. pgx encodes Go slices as PostgreSQL arrays directly, while lib/pq needs the pq.Array wrapper. Keep the canonical sort and dedupe so equal requests still send equal arguments."},{"body":"The client chooses among names; the server owns the SQL. A leading minus selects DESC, and the column, direction and NULL placement all come from constants. Refuse a repeated key and cap the number of keys, because every allowed combination is an index you either build or a sort the database performs on every request. PostgreSQL sorts NULL as larger than any value, so NULLs come last ascending and first descending; writing NULLS LAST for nullable columns keeps undated issues at the end in both directions. An index serves the query without a separate sort only when its columns, directions and NULL placement match the ORDER BY or its exact reverse. Always append the unique id, so the order is total and a page boundary is a single row, which the pagination lesson relies on for cursors. Choose a default order when the client sends none rather than leaving it to the planner.","title":"Sort keys, directions and the tiebreaker"},{"body":"Because buildQuery takes url.Values and returns a string and a slice, its tests need no database and no HTTP server. For each case, assert the full SQL text and the full argument list, not a substring. Include equivalence cases that must produce identical output, such as reordered and repeated list values, and hostile cases that must produce 400: an unencoded semicolon, an unknown parameter, an unknown or repeated sort key, an out-of-range limit, twenty-one assignees and an over-long search term. Then add a small integration suite against a disposable PostgreSQL that checks rows rather than strings: a title containing a literal percent sign, NULL placement in both directions, and EXPLAIN for each allowed sort combination to confirm the index you expect is used.","title":"Test the builder as a pure function"}],"takeaway":"Parse RawQuery strictly, canonicalize and bound every list, let a builder generate every placeholder, take sort SQL only from constants and always end the order with a unique tiebreaker.","title":"Gin list filters to parameterized SQL: parse strictly, bound IN lists, escape LIKE, end with a tiebreaker","unitID":"gin-data","wrongAnswers":["Gin splits it into the two values open and closed","Gin answers 400 before the handler runs"]},{"conceptTag":"gin.batched-includes","designGuide":{"cautions":["errgroup v0.24.0 does not recover panics, and gin.Recovery cannot catch a loader panic.","The errgroup context is canceled once Wait returns; never reuse it."],"cost":"A batch method per relation in the store, an include registry, and per-request concurrency that claims pool connections.","family":"gin","flow":["Allow-list includes","Collect the page's IDs","Batch load, bounded","Assemble in list order"],"ratings":[],"strengths":["Round trips stay constant as the page grows.","Unknown includes fail loudly instead of silently returning less data."]},"hint":"Count how often each loader runs, not how many IDs it receives.","id":"gin.batched-includes","introduction":"A client asks for /posts?include=author,tags so that it can render a feed in one request. The obvious implementation looks up each post's author inside the loop that builds the response, and a page of fifty posts quietly becomes a hundred and one queries. The cost should depend on how many relations were requested, never on how many rows the page holds.","nuance":"Each loader receives every ID on the page and makes a single round trip, so the cost is one plus the number of includes whatever the page size; the N+1 shape grows with the page.","objective":"Serve optional related data on a Gin list endpoint with one batched lookup per relation, bounded concurrent loads and deterministic output, and prove the query count by counting store calls.","question":"A client requests a page of 50 posts with ?include=author,tags. With batched loaders, how many store calls should the request make?","references":["https://pkg.go.dev/golang.org/x/sync/errgroup#Group.SetLimit","https://pkg.go.dev/golang.org/x/sync/errgroup#WithContext","https://pkg.go.dev/github.com/gin-gonic/gin#Context.QueryArray","https://www.postgresql.org/docs/current/functions-comparisons.html"],"reviewAnswer":"One list query plus one batch per include","reviewPrompt":"Cost of ?include=author,tags?","sections":[{"body":"In the N+1 shape, one query loads the list and then one more query runs per row for each relation. Each extra round trip adds latency in series and holds a pool connection while it waits, so under load the request spends most of its time queuing for connections, as the SQL pool lesson describes. Batching reverses the dependency. Collect the IDs the page refers to, load each relation for all of them in one query, and join the results in memory. The cost becomes one list query plus one query per requested include, whatever the page size. Independent relations can also load concurrently, which turns their latencies from a sum into a maximum, provided the concurrency is bounded.","title":"N+1 grows with the page, batching grows with the request"},{"body":"Map each public include name to a loader that fetches one relation for the whole page and writes only its own field of a page struct. That map is the allow-list. An unknown name answers 400 and lists the valid ones, because a typo that silently returns less data is a bug nobody reports. Accept repeated and comma-separated forms through c.QueryArray and drop duplicates; the safe-filters lesson explains when to parse the raw query strictly instead. A loader is also an authorization boundary: an included author must expose exactly the fields a direct read of that author would, for the same caller. Nested includes such as author.organization multiply the work and the data exposed, so support them only deliberately, with a depth limit.","title":"Includes are an allow-list of loaders"},{"body":"The store is an in-memory model that counts every method call. The naive route looks up authors one post at a time; the batched route parses the includes, loads the posts, runs the requested loaders through an errgroup limited to two at a time, and assembles the response in post order. A last request makes the tags store fail.","code":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"slices\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"golang.org/x/sync/errgroup\"\n)\n\ntype Post struct {\n\tID       int\n\tAuthorID int\n\tTitle    string\n}\n\ntype Author struct {\n\tID   int    `json:\"id\"`\n\tName string `json:\"name\"`\n}\n\n// Store is an in-memory model of a database. It counts every call so the\n// program can show how many round trips one request costs.\ntype Store struct {\n\tmu       sync.Mutex\n\tcalls    map[string]int\n\tfailTags bool\n}\n\nfunc (s *Store) count(name string) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.calls[name]++\n}\n\nfunc (s *Store) Calls() string {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tvar parts []string\n\tfor _, name := range slices.Sorted(maps.Keys(s.calls)) {\n\t\tparts = append(parts, fmt.Sprintf(\"%s=%d\", name, s.calls[name]))\n\t}\n\tclear(s.calls)\n\tif len(parts) == 0 {\n\t\treturn \"none\"\n\t}\n\treturn strings.Join(parts, \" \")\n}\n\nvar authors = map[int]Author{7: {7, \"kestrel\"}, 9: {9, \"heron\"}}\nvar tags = map[int][]string{1: {\"go\", \"concurrency\"}, 3: {\"sql\"}}\n\nfunc (s *Store) ListPosts(ctx context.Context) ([]Post, error) {\n\ts.count(\"ListPosts\")\n\treturn []Post{{1, 7, \"Channels\"}, {2, 9, \"Interfaces\"}, {3, 7, \"database/sql\"}, {4, 9, \"Generics\"}}, ctx.Err()\n}\n\n// AuthorByID is what a naive include calls once per post.\nfunc (s *Store) AuthorByID(ctx context.Context, id int) (Author, error) {\n\ts.count(\"AuthorByID\")\n\treturn authors[id], ctx.Err()\n}\n\n// AuthorsByIDs is one round trip for a whole page: WHERE id = ANY($1).\nfunc (s *Store) AuthorsByIDs(ctx context.Context, ids []int) (map[int]Author, error) {\n\ts.count(\"AuthorsByIDs\")\n\tout := map[int]Author{}\n\tfor _, id := range ids {\n\t\tif a, ok := authors[id]; ok {\n\t\t\tout[id] = a\n\t\t}\n\t}\n\treturn out, ctx.Err()\n}\n\nfunc (s *Store) TagsByPostIDs(ctx context.Context, ids []int) (map[int][]string, error) {\n\ts.count(\"TagsByPostIDs\")\n\tif s.failTags {\n\t\treturn nil, errors.New(\"tags replica unavailable\")\n\t}\n\tout := map[int][]string{}\n\tfor _, id := range ids {\n\t\tout[id] = slices.Sorted(slices.Values(tags[id]))\n\t}\n\treturn out, ctx.Err()\n}\n\ntype postDTO struct {\n\tID     int      `json:\"id\"`\n\tTitle  string   `json:\"title\"`\n\tAuthor *Author  `json:\"author,omitzero\"`\n\tTags   []string `json:\"tags,omitzero\"`\n}\n\n// relations is the allow-list: each include names one batched loader that\n// fills only its own field of the page.\ntype page struct {\n\tposts   []Post\n\tauthors map[int]Author\n\ttags    map[int][]string\n}\n\nvar relations = map[string]func(context.Context, *Store, *page) error{\n\t\"author\": func(ctx context.Context, s *Store, p *page) error {\n\t\tids := make([]int, 0, len(p.posts))\n\t\tfor _, post := range p.posts {\n\t\t\tids = append(ids, post.AuthorID)\n\t\t}\n\t\tslices.Sort(ids)\n\t\tvar err error\n\t\tp.authors, err = s.AuthorsByIDs(ctx, slices.Compact(ids))\n\t\treturn err\n\t},\n\t\"tags\": func(ctx context.Context, s *Store, p *page) error {\n\t\tids := make([]int, len(p.posts))\n\t\tfor i, post := range p.posts {\n\t\t\tids[i] = post.ID\n\t\t}\n\t\tvar err error\n\t\tp.tags, err = s.TagsByPostIDs(ctx, ids)\n\t\treturn err\n\t},\n}\n\nfunc parseIncludes(raw []string) ([]string, error) {\n\tvar out []string\n\tfor _, v := range raw {\n\t\tfor name := range strings.SplitSeq(v, \",\") {\n\t\t\tif _, ok := relations[name]; !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unknown include %q\", name)\n\t\t\t}\n\t\t\tif !slices.Contains(out, name) {\n\t\t\t\tout = append(out, name)\n\t\t\t}\n\t\t}\n\t}\n\treturn out, nil\n}\n\nfunc listPosts(s *Store) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tincludes, err := parseIncludes(c.QueryArray(\"include\"))\n\t\tif err != nil {\n\t\t\tc.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\"error\": err.Error(),\n\t\t\t\t\"allowed\": slices.Sorted(maps.Keys(relations))})\n\t\t\treturn\n\t\t}\n\t\tctx := c.Request.Context() // goroutines get this, never c\n\t\tposts, err := s.ListPosts(ctx)\n\t\tif err != nil {\n\t\t\tc.AbortWithStatus(http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tp := &page{posts: posts}\n\t\tg, gctx := errgroup.WithContext(ctx)\n\t\tg.SetLimit(2) // at most two relation queries hold pool connections at once\n\t\tfor _, name := range includes {\n\t\t\tload := relations[name]\n\t\t\tg.Go(func() error { return load(gctx, s, p) })\n\t\t}\n\t\tif err := g.Wait(); err != nil { // gctx is canceled from here on\n\t\t\tc.AbortWithStatusJSON(http.StatusServiceUnavailable, gin.H{\"error\": \"related data unavailable\"})\n\t\t\treturn\n\t\t}\n\t\tout := make([]postDTO, len(posts)) // response order is the order of posts\n\t\tfor i, post := range posts {\n\t\t\tout[i] = postDTO{ID: post.ID, Title: post.Title}\n\t\t\tif a, ok := p.authors[post.AuthorID]; ok {\n\t\t\t\tout[i].Author = &a\n\t\t\t}\n\t\t\tif p.tags != nil {\n\t\t\t\tout[i].Tags = append([]string{}, p.tags[post.ID]...) // [] when included but empty\n\t\t\t}\n\t\t}\n\t\tc.JSON(http.StatusOK, gin.H{\"posts\": out})\n\t}\n}\n\n// naiveAuthors is the N+1 shape: one query for the list, one per row.\nfunc naiveAuthors(s *Store) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tctx := c.Request.Context()\n\t\tposts, _ := s.ListPosts(ctx)\n\t\tnames := make([]string, len(posts))\n\t\tfor i, post := range posts {\n\t\t\ta, _ := s.AuthorByID(ctx, post.AuthorID)\n\t\t\tnames[i] = a.Name\n\t\t}\n\t\tc.JSON(http.StatusOK, gin.H{\"authors\": names})\n\t}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\ts := &Store{calls: map[string]int{}}\n\tr := gin.New()\n\tr.GET(\"/posts\", listPosts(s))\n\tr.GET(\"/naive/posts\", naiveAuthors(s))\n\n\tget := func(target string, showBody bool) {\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil))\n\t\tfmt.Printf(\"GET %s -> %d, store calls: %s\\n\", target, w.Code, s.Calls())\n\t\tif showBody {\n\t\t\tfmt.Println(\" \", w.Body.String())\n\t\t}\n\t}\n\tget(\"/naive/posts\", false)\n\tget(\"/posts\", false)\n\tget(\"/posts?include=author\", false)\n\tget(\"/posts?include=author,tags&include=author\", true)\n\tget(\"/posts?include=author,reviews\", true)\n\n\ts.failTags = true\n\tw := httptest.NewRecorder()\n\tr.ServeHTTP(w, httptest.NewRequest(http.MethodGet, \"/posts?include=tags\", nil))\n\tfmt.Println(\"tags store failing ->\", w.Code, w.Body.String())\n}","language":"go","title":"Count the calls: naive versus batched","walkthrough":"The naive route makes one AuthorByID call per post, four for four posts, and that number grows with the page. The batched route makes one ListPosts call and one call per requested relation: AuthorsByIDs receives the deduplicated, sorted author IDs 7 and 9, and TagsByPostIDs receives every post ID. include=author,tags&include=author shows repeated and comma-separated forms merged with duplicates dropped. Each loader writes only its own field of page, so the goroutines never write the same memory, and they receive gctx rather than c. The response is built after Wait, in post order. A post without tags renders [] because the slice is non-nil, while a relation that was not requested is omitted by omitzero. An unknown include fails before any store call, and a failing loader turns into 503 with no partial body."},{"body":"errgroup.WithContext(c.Request.Context()) gives the loaders a context that is canceled when the client leaves and, through context.WithCancelCause in x/sync v0.24.0, the first time a loader returns an error, so the other loaders can stop early. Wait returns that first error. SetLimit(2) must be called before the first Go, because changing the limit while goroutines are active panics; once the limit is reached, Go blocks the handler until a slot frees. Size the limit against the connection pool: concurrent requests times loaders per request is how many connections includes can claim. Two traps are specific to running this inside Gin. The derived context is canceled as soon as Wait returns, so rendering or a follow-up query must use the request context, not gctx. And in v0.24.0, Go does not recover panics: a panic in a loader goroutine crashes the process, because gin.Recovery only protects the goroutine running the handler chain.","title":"Bounded concurrency with errgroup, and what it does not cover"},{"body":"In PostgreSQL each loader becomes a single statement over an array of IDs. Let the database order the rows so that each slice arrives sorted, and build the response from the primary list, never by ranging over a map. Decide explicitly what a missing related row means: a deleted author can render as null, drop the post or fail the request, and each choice belongs in the API contract. Bound the ID list through the page limit; a page of at most 100 rows can never send more than 100 IDs to a loader.","code":"// TagsByPostIDs is one round trip for the whole page, ordered by the database.\nfunc (s *PG) TagsByPostIDs(ctx context.Context, ids []int64) (map[int64][]string, error) {\n\trows, err := s.db.QueryContext(ctx,\n\t\t`SELECT post_id, tag FROM post_tags WHERE post_id = ANY($1) ORDER BY post_id, tag`, ids)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\tout := make(map[int64][]string, len(ids))\n\tfor rows.Next() {\n\t\tvar id int64\n\t\tvar tag string\n\t\tif err := rows.Scan(&id, &tag); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tout[id] = append(out[id], tag)\n\t}\n\treturn out, rows.Err()\n}","language":"go","title":"One query per relation in SQL, ordered by the database","walkthrough":"This fragment runs against a real PostgreSQL database in your own environment; PG wraps a *sql.DB. post_id = ANY($1) takes the whole ID list as one array parameter. With the pgx stdlib driver a []int64 argument is encoded as an array directly, while lib/pq needs pq.Array(ids). ORDER BY post_id, tag makes every slice deterministic without sorting in Go. rows.Err is checked after the loop because iteration can fail midway, as the SQL rows lesson explains."},{"body":"Latency tests rarely catch an N+1 regression on a laptop with ten rows. A call count does. Run the list handler against a counting store with page sizes of 1, 10 and 50 and assert that the number of calls per relation is identical and equal to one. Add cases for an unknown include, a duplicated include, an included relation with no rows, a loader that fails and a client that cancels mid-request, and run the suite under go test -race so a loader that touches c or shares a map is reported. In production, record the number of queries per request as a span attribute or histogram, keyed by route template, so a regression shows up as a step in a graph rather than as a slow page.","title":"Make the call count a test assertion"}],"takeaway":"Map each include to one batched loader keyed by the page's IDs, run the loaders through a bounded errgroup on the request context, and build the response in list order after Wait.","title":"?include= without N+1 in Gin: one batched loader per relation, a bounded errgroup and list-order output","unitID":"gin-data","wrongAnswers":["One list query plus one lookup per post per include","One list query plus one query per distinct author"]},{"conceptTag":"gin.response-cache","designGuide":{"cautions":["Invalidation is per process; other replicas serve old entries until their TTL ends.","A follower keeps waiting for the leader even after its own client has gone."],"cost":"Memory for stored bodies, a capture writer, per-route allow-lists that must track what handlers read, and an invalidation call in every write path.","family":"gin","flow":["Bypass identity, unknowns","Key route + canonical query","Coalesce the miss","Store only public 200s"],"ratings":[],"strengths":["A popular public page costs one handler run per TTL per process.","Concurrent misses collapse into one fill, and 304s are answered from the entry."]},"hint":"Ask whether the key captures every input the handler can read.","id":"gin.response-cache","introduction":"A popular public endpoint renders the same page of articles thousands of times a minute, and each render costs a query and a JSON encode. Caching the finished response inside the service removes that work, but only if the cache never answers differently from the handler: not for another user, not for another query string and not after a write.","nuance":"The key holds only the route, its params and the allow-listed query. A handler that reads Authorization can return per-user data, and caching it would serve one caller's response to the next, so the request must bypass the cache.","objective":"Build a Gin middleware that caches public GET responses under a route-template key, never stores per-user responses, coalesces concurrent misses with singleflight and stays correct across writes, TTLs and conditional requests.","question":"A response-cache middleware keys entries by c.FullPath(), the path params and the allow-listed query. What should it do with a GET that carries an Authorization header?","references":["https://pkg.go.dev/golang.org/x/sync/singleflight#Group.Do","https://pkg.go.dev/github.com/gin-gonic/gin#Context.FullPath","https://pkg.go.dev/net/url#Values.Encode","https://www.rfc-editor.org/rfc/rfc9111"],"reviewAnswer":"No, bypass: the response may depend on the caller","reviewPrompt":"Cache a GET with Authorization?","sections":[{"body":"One invariant drives every decision: the cache may answer only when the stored response is exactly what the handler would produce for this request. The key must therefore capture every input the handler reads, a request that carries identity must bypass the cache, and only a response that declares itself public may be stored. The conditional-requests lesson set Cache-Control and ETags for browsers and CDNs, which saves bandwidth. A server-side cache saves the handler's own work, the query and the render, and it lives inside your process, where you control the key, the lifetime and invalidation. The stampede and cache-aside lessons explain why concurrent misses are dangerous; this lesson builds the Gin middleware that handles them.","title":"The cache must never change the answer"},{"body":"c.FullPath() returns the route template, such as /articles/:id, so the set of keys and the unit of invalidation follow routes rather than raw paths, and an unmatched request has an empty template and is never cached. Add the values from c.Params, then the query parsed with url.ParseQuery and re-encoded with Values.Encode, which sorts parameter names, so ?sort=new&page=1 and ?page=1&sort=new share an entry. Encode keeps the order of repeated values, because that order can be meaningful. Each route lists the parameters its handler reads. A request with any other parameter bypasses the cache instead of having the parameter dropped: dropping utm_source would be harmless, but dropping a parameter the handler does read would serve the wrong page. If you know some tracking parameters are ignored, strip them through a named list. Requests with Authorization or Cookie bypass, and a stored response must not carry Set-Cookie or Vary, because the key does not include the request headers it would vary on.","title":"Key by what the handler reads"},{"body":"The program wraps one list route in the cache. A fake clock decides expiry. The handler counts its calls, reads the data version before doing slow work, and can be held at a gate so that misses overlap deterministically. The sequence covers a hit through a reordered query, three bypasses, a 304 served from the entry, a write, expiry, a write that lands during a fill, and two bursts of five concurrent misses, with and without coalescing.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"maps\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"slices\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"golang.org/x/sync/singleflight\"\n)\n\n// Clock is injected so that tests, not the wall clock, decide when entries expire.\ntype Clock struct {\n\tmu  sync.Mutex\n\tnow time.Time\n}\n\nfunc (c *Clock) Now() time.Time {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\treturn c.now\n}\n\nfunc (c *Clock) Advance(d time.Duration) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tc.now = c.now.Add(d)\n}\n\n// entry is everything needed to replay a response. It is shared by\n// concurrent readers, so it is never modified after it is stored.\ntype entry struct {\n\tstatus int\n\theader http.Header\n\tbody   []byte\n\tstored time.Time\n}\n\ntype ResponseCache struct {\n\tnow      func() time.Time\n\tttl      time.Duration\n\tallowed  map[string][]string // route template -> query parameters it reads\n\tcoalesce bool\n\tgroup    singleflight.Group\n\n\tmu      sync.Mutex\n\tentries map[string]entry\n\tgen     map[string]uint64 // bumped per route template on every invalidation\n}\n\nfunc (rc *ResponseCache) get(key string) (entry, bool) {\n\trc.mu.Lock()\n\tdefer rc.mu.Unlock()\n\te, ok := rc.entries[key]\n\tif ok && rc.now().Sub(e.stored) >= rc.ttl {\n\t\tdelete(rc.entries, key)\n\t\treturn entry{}, false\n\t}\n\treturn e, ok\n}\n\nfunc (rc *ResponseCache) generation(route string) uint64 {\n\trc.mu.Lock()\n\tdefer rc.mu.Unlock()\n\treturn rc.gen[route]\n}\n\n// put stores e unless the route was invalidated after the fill started.\nfunc (rc *ResponseCache) put(route, key string, gen uint64, e entry) {\n\trc.mu.Lock()\n\tdefer rc.mu.Unlock()\n\tif rc.gen[route] == gen {\n\t\trc.entries[key] = e\n\t}\n}\n\nfunc (rc *ResponseCache) Invalidate(routes ...string) {\n\trc.mu.Lock()\n\tdefer rc.mu.Unlock()\n\tfor _, route := range routes {\n\t\trc.gen[route]++\n\t}\n\tfor key := range rc.entries {\n\t\troute, _, _ := strings.Cut(key, \" \")\n\t\tif slices.Contains(routes, route) {\n\t\t\tdelete(rc.entries, key)\n\t\t}\n\t}\n}\n\n// key returns false when the request must bypass the cache.\nfunc (rc *ResponseCache) key(c *gin.Context) (route, key string, ok bool) {\n\troute = c.FullPath()\n\tparams, listed := rc.allowed[route]\n\tif c.Request.Method != http.MethodGet || !listed {\n\t\treturn \"\", \"\", false\n\t}\n\tif c.GetHeader(\"Authorization\") != \"\" || c.GetHeader(\"Cookie\") != \"\" {\n\t\treturn \"\", \"\", false // the response may depend on who is asking\n\t}\n\tq, err := url.ParseQuery(c.Request.URL.RawQuery)\n\tif err != nil {\n\t\treturn \"\", \"\", false\n\t}\n\tfor name := range q {\n\t\tif !slices.Contains(params, name) {\n\t\t\treturn \"\", \"\", false // an input the key would not capture\n\t\t}\n\t}\n\tkey = route\n\tfor _, p := range c.Params {\n\t\tkey += \" \" + p.Key + \"=\" + url.QueryEscape(p.Value)\n\t}\n\treturn route, key + \" ?\" + q.Encode(), true // Encode sorts by name\n}\n\n// capture buffers the handler's response instead of sending it.\ntype capture struct {\n\tgin.ResponseWriter\n\theader http.Header\n\tstatus int\n\tbody   bytes.Buffer\n}\n\nfunc (w *capture) Header() http.Header               { return w.header }\nfunc (w *capture) WriteHeader(code int)              { w.status = code }\nfunc (w *capture) WriteHeaderNow()                   {}\nfunc (w *capture) Write(b []byte) (int, error)       { return w.body.Write(b) }\nfunc (w *capture) WriteString(s string) (int, error) { return w.body.WriteString(s) }\nfunc (w *capture) Status() int                       { return w.status }\nfunc (w *capture) Size() int                         { return w.body.Len() }\nfunc (w *capture) Written() bool                     { return w.body.Len() > 0 }\nfunc (w *capture) Flush()                            {}\n\n// record runs the rest of the chain for a full, unconditional response.\nfunc (rc *ResponseCache) record(c *gin.Context) entry {\n\tw := &capture{ResponseWriter: c.Writer, header: http.Header{}, status: http.StatusOK}\n\twriter, req := c.Writer, c.Request\n\tdefer func() { c.Writer, c.Request = writer, req }() // also when a handler panics\n\tc.Writer, c.Request = w, req.Clone(req.Context())\n\tc.Request.Header.Del(\"If-None-Match\") // never store a 304 meant for one client\n\tc.Request.Header.Del(\"If-Modified-Since\")\n\tc.Next()\n\treturn entry{status: w.status, header: w.header, body: bytes.Clone(w.body.Bytes()), stored: rc.now()}\n}\n\nfunc storable(e entry) bool {\n\tvar cc []string\n\tfor d := range strings.SplitSeq(strings.ToLower(e.header.Get(\"Cache-Control\")), \",\") {\n\t\tcc = append(cc, strings.TrimSpace(d))\n\t}\n\treturn e.status == http.StatusOK && e.header.Get(\"Set-Cookie\") == \"\" && e.header.Get(\"Vary\") == \"\" &&\n\t\tslices.Contains(cc, \"public\") && !slices.Contains(cc, \"private\") && !slices.Contains(cc, \"no-store\")\n}\n\nfunc matches(ifNoneMatch, etag string) bool {\n\tfor candidate := range strings.SplitSeq(ifNoneMatch, \",\") {\n\t\tif t := strings.TrimSpace(candidate); t == \"*\" || strings.TrimPrefix(t, \"W/\") == etag {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc (rc *ResponseCache) replay(c *gin.Context, e entry, state string) {\n\th := c.Writer.Header()\n\th.Set(\"X-Cache\", state)\n\th.Set(\"Age\", strconv.Itoa(int(rc.now().Sub(e.stored)/time.Second)))\n\tif etag := e.header.Get(\"ETag\"); etag != \"\" && matches(c.GetHeader(\"If-None-Match\"), etag) {\n\t\th.Set(\"ETag\", etag)\n\t\th.Set(\"Cache-Control\", e.header.Get(\"Cache-Control\"))\n\t\tc.AbortWithStatus(http.StatusNotModified)\n\t\treturn\n\t}\n\tmaps.Copy(h, e.header.Clone()) // copies: outer middleware may append to these slices\n\tc.Status(e.status)\n\t_, _ = c.Writer.Write(e.body)\n\tc.Abort()\n}\n\nfunc (rc *ResponseCache) Middleware(c *gin.Context) {\n\troute, key, ok := rc.key(c)\n\tif !ok {\n\t\tc.Header(\"X-Cache\", \"BYPASS\")\n\t\tc.Next()\n\t\treturn\n\t}\n\tif e, ok := rc.get(key); ok {\n\t\trc.replay(c, e, \"HIT\")\n\t\treturn\n\t}\n\tgen := rc.generation(route)\n\tfill := func() (any, error) {\n\t\tif e, ok := rc.get(key); ok {\n\t\t\treturn e, nil // a flight that ended a moment ago already stored it\n\t\t}\n\t\te := rc.record(c)\n\t\tif storable(e) {\n\t\t\trc.put(route, key, gen, e)\n\t\t}\n\t\treturn e, nil\n\t}\n\tvar v any\n\tif rc.coalesce {\n\t\tv, _, _ = rc.group.Do(key+\" #\"+strconv.FormatUint(gen, 10), fill)\n\t} else {\n\t\tv, _ = fill()\n\t}\n\trc.replay(c, v.(entry), \"MISS\")\n}\n\n// articles is the origin handler with counters the demo can read.\ntype articles struct {\n\tversion atomic.Int64\n\tcalls   atomic.Int64\n\tgate    chan struct{} // when set, the handler waits so misses overlap\n\tentered chan struct{}\n}\n\nfunc (a *articles) list(c *gin.Context) {\n\ta.calls.Add(1)\n\tversion := a.version.Load() // read the data first, as a query would\n\tif a.gate != nil {\n\t\ta.entered <- struct{}{}\n\t\t<-a.gate\n\t}\n\tbody := fmt.Sprintf(`{\"page\":%q,\"sort\":%q,\"version\":%d}`, c.DefaultQuery(\"page\", \"1\"),\n\t\tc.DefaultQuery(\"sort\", \"new\"), version)\n\tsum := sha256.Sum256([]byte(body))\n\tc.Header(\"ETag\", `\"`+hex.EncodeToString(sum[:8])+`\"`)\n\tc.Header(\"Cache-Control\", \"public, max-age=60\")\n\tc.Data(http.StatusOK, \"application/json\", []byte(body))\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tclock := &Clock{now: time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)}\n\trc := &ResponseCache{now: clock.Now, ttl: time.Minute, coalesce: true,\n\t\tallowed: map[string][]string{\"/articles\": {\"page\", \"sort\"}},\n\t\tentries: map[string]entry{}, gen: map[string]uint64{}}\n\ta := &articles{}\n\ta.version.Store(1)\n\n\tr := gin.New()\n\tr.Use(rc.Middleware)\n\tr.GET(\"/articles\", a.list)\n\tr.POST(\"/articles\", func(c *gin.Context) {\n\t\ta.version.Add(1) // the write commits first,\n\t\trc.Invalidate(\"/articles\")\n\t\tc.Status(http.StatusCreated) // then the cache forgets\n\t})\n\n\tdo := func(method, target string, header ...string) *httptest.ResponseRecorder {\n\t\treq := httptest.NewRequest(method, target, nil)\n\t\tfor i := 0; i+1 < len(header); i += 2 {\n\t\t\treq.Header.Set(header[i], header[i+1])\n\t\t}\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\treturn w\n\t}\n\tshow := func(label, method, target string, header ...string) *httptest.ResponseRecorder {\n\t\tw := do(method, target, header...)\n\t\tage := w.Header().Get(\"Age\")\n\t\tif age == \"\" {\n\t\t\tage = \"-\"\n\t\t}\n\t\tfmt.Printf(\"%-13s %d %-6s age=%-2s handler calls=%d\\n\", label, w.Code, w.Header().Get(\"X-Cache\"), age, a.calls.Load())\n\t\treturn w\n\t}\n\n\tfirst := show(\"first\", \"GET\", \"/articles?page=1&sort=new\")\n\tclock.Advance(10 * time.Second)\n\tshow(\"reordered\", \"GET\", \"/articles?sort=new&page=1\")\n\tshow(\"bearer\", \"GET\", \"/articles?page=1&sort=new\", \"Authorization\", \"Bearer t-1\")\n\tshow(\"cookie\", \"GET\", \"/articles?page=1&sort=new\", \"Cookie\", \"session=s-1\")\n\tshow(\"utm param\", \"GET\", \"/articles?page=1&sort=new&utm_source=mail\")\n\tshow(\"If-None-Match\", \"GET\", \"/articles?page=1&sort=new\", \"If-None-Match\", first.Header().Get(\"ETag\"))\n\tfmt.Println(\"POST /articles\", do(\"POST\", \"/articles\").Code)\n\tafter := show(\"after write\", \"GET\", \"/articles?page=1&sort=new\")\n\tfmt.Println(\"  new body:\", after.Body.String())\n\tclock.Advance(time.Minute)\n\tshow(\"after TTL\", \"GET\", \"/articles?page=1&sort=new\")\n\n\ta.gate, a.entered = make(chan struct{}), make(chan struct{}, 1)\n\tslow := make(chan string)\n\tgo func() { slow <- do(\"GET\", \"/articles?page=4\").Body.String() }()\n\t<-a.entered // this fill has read version 2 and is still running\n\tdo(\"POST\", \"/articles\")\n\tclose(a.gate)\n\tinflight := <-slow\n\ta.gate = nil\n\tnext := do(\"GET\", \"/articles?page=4\")\n\tfmt.Println(\"write during a fill: in-flight\", inflight)\n\tfmt.Println(\"  next GET\", next.Header().Get(\"X-Cache\"), next.Body.String())\n\n\tburst := func(target string, wait int) (calls int64, identical bool) {\n\t\ta.gate, a.entered = make(chan struct{}), make(chan struct{}, 5)\n\t\tbefore := a.calls.Load()\n\t\tbodies := make([]string, 5)\n\t\tvar wg sync.WaitGroup\n\t\tfor i := range bodies {\n\t\t\twg.Go(func() { bodies[i] = do(\"GET\", target).Body.String() })\n\t\t}\n\t\tfor range wait {\n\t\t\t<-a.entered // these handler calls are now in flight together\n\t\t}\n\t\tclose(a.gate)\n\t\twg.Wait()\n\t\ta.gate = nil\n\t\tidentical = true\n\t\tfor _, b := range bodies {\n\t\t\tidentical = identical && b == bodies[0]\n\t\t}\n\t\treturn a.calls.Load() - before, identical\n\t}\n\tcalls, same := burst(\"/articles?page=2\", 1)\n\tfmt.Printf(\"5 concurrent misses, singleflight: handler calls=%d identical bodies=%t\\n\", calls, same)\n\trc.coalesce = false\n\tcalls, same = burst(\"/articles?page=3\", 5)\n\tfmt.Printf(\"5 concurrent misses, no coalescing: handler calls=%d identical bodies=%t\\n\", calls, same)\n}","language":"go","title":"The middleware, a fake clock and a gated handler","walkthrough":"The first request misses and stores the response; ten seconds later the reordered query hits and Age reports 10. The bearer, cookie and utm requests bypass and each runs the handler. If-None-Match is answered 304 from the stored entry without a handler call. The POST bumps the version and invalidates /articles, so the next GET misses, and after the clock passes the 60 second TTL it misses again. In the write-during-a-fill step, the fill reads version 2 and waits; the POST invalidates the route meanwhile, so put discards the result and the next GET sees version 3 instead of a stale page for a minute. In the singleflight burst the gated leader is the only handler run: the other requests wait for it or hit the entry it stored. capture keeps its own header map, so headers that outer middleware set, such as a request ID, are never stored and replayed."},{"body":"group.Do runs the fill function on the calling goroutine, so the leader runs its own c.Next and no other goroutine ever touches its *gin.Context, as the context-fallback lesson requires. Followers block until the leader finishes and replay the same immutable entry onto their own writers, then Abort so their chains do not run. The fill re-checks the cache first, because a request that missed just before the previous flight ended would otherwise start a second fill. The flight key includes the route's generation, so a request that arrives after an invalidation never joins a flight that started before it. The limits are real. Do has no context, so a follower keeps waiting after its own client has gone; DoChan could select on cancellation, but it runs the function on a new goroutine, where calling c.Next would break the one-owner rule. If the leader's client disconnects and the handler fails, every follower receives that failed response, which at least is not stored. singleflight re-panics in the leader and in every follower; record restores the real writer in a defer so an outer Recovery can still answer 500, and registering Recovery inside the cache turns a panic into an ordinary 500 that is never stored. Coalescing is per process, so ten replicas still make ten fills.","title":"Coalescing misses inside Gin with singleflight"},{"body":"A write handler commits and then invalidates the route templates whose responses it changed. Invalidating before the commit opens a window in which a read refills the entry with the old data. Even after the commit, a fill that read the old data before the write can finish afterwards and store it, which is the race the cache-aside lesson warns about. The per-route generation closes it: the fill captures the generation before running the handler, and put stores only if it is unchanged. Per-route invalidation is coarse but easy to verify; tagging entries by resource ID is finer and costs bookkeeping in every handler. This cache lives in one process, so other replicas keep their entries until the TTL ends unless you broadcast invalidations or move to a shared cache, which makes the TTL your honest bound on staleness. The model also lacks two things a real service adds: a cap on entry count and body size with eviction, and metrics for hit ratio and bypass reasons.","title":"Invalidate after the commit, and guard fills in flight"},{"body":"The handler from the conditional-requests lesson derives its ETag from the response bytes, so a stored body and its validator always travel together. Before filling, the cache removes If-None-Match and If-Modified-Since from its copy of the request, so a leader that sent a validator cannot produce a bodiless 304 that would be stored or replayed to followers. On replay the cache compares If-None-Match with the stored ETag and answers 304 itself, carrying ETag and Cache-Control, without running the handler. The Age header tells downstream caches how old the copy already is, so public, max-age=60 still means sixty seconds in total rather than sixty more on top of the time it spent in your cache. Responses marked private or no-store are never stored. Test the X-Cache sequence for each rule above, use the fake clock instead of sleeping, hold the handler at a gate to make concurrent misses reproducible, race a write against a fill, and run the suite under go test -race.","title":"Stay consistent with ETags, Age and Cache-Control"}],"takeaway":"Cache only public GETs whose every input is in the key: route template, path params and allow-listed query. Bypass identity, coalesce misses with singleflight on the request goroutine, and guard invalidation with a generation so in-flight fills cannot store stale data.","title":"Cache public GETs in Gin: key by route template, bypass identity, coalesce misses, invalidate on write","unitID":"gin-data","wrongAnswers":["Cache it: the route template already identifies the content","Strip the header, then fill the cache as usual"]},{"conceptTag":"gin.streaming-import","designGuide":{"cautions":["One transaction per upload holds a pooled connection at the client's pace.","Partial mode needs idempotent rows so a resend does not duplicate."],"cost":"A line reader, a per-row report and a transaction that stays open for the upload; large files usually graduate to an asynchronous job.","family":"gin","flow":["Cap the body","Read one bounded line","Decode, validate the row","Commit or roll back"],"ratings":[],"strengths":["Memory is bounded by one line, not by the file.","Clients get a line number and reason for every rejected row."]},"hint":"Count how many times binding.JSON calls Decode before it validates.","id":"gin.streaming-import","introduction":"A bulk import receives the largest bodies your service will ever see, from clients that may have produced part of the file wrong. Reading it whole turns file size into memory, and one bad row into an unexplained 400. Newline-delimited JSON lets the handler work one record at a time: bound the request, bound each line, judge each row on its own, and tell the client exactly which lines were written.","nuance":"Gin's decodeJSON makes one Decode call and never checks for more input, so the remaining lines are never read. A per-line reader with a trailing-data check is what sees every record.","objective":"Build an NDJSON import endpoint that bounds the body and each line, validates rows one at a time and returns a per-line report whose status matches what was written.","question":"In Gin v1.12.0, what does c.ShouldBindJSON(&p) do when the request body is NDJSON holding many valid records?","references":["https://pkg.go.dev/net/http#MaxBytesReader","https://pkg.go.dev/bufio#Reader.ReadSlice","https://pkg.go.dev/github.com/gin-gonic/gin/binding#StructValidator","https://github.com/ndjson/ndjson-spec"],"reviewAnswer":"Binds the first line, returns nil, ignores the rest","reviewPrompt":"ShouldBindJSON on an NDJSON body?","sections":[{"body":"In Gin v1.12.0, c.ShouldBindJSON hands the body to binding.JSON, which makes a single Decode call and then validates. On an NDJSON body it binds the first record, returns nil and never reads the other lines; the last line of the program below shows exactly that. Binding a []Product from a JSON array works, but it holds the whole file as Go values before validation starts, and one type error fails the entire decode without a line number. io.ReadAll followed by a split has the same memory profile. One json.Decoder over the whole stream is closer, but it accepts records that span lines or share one, reports byte offsets instead of line numbers, buffers each value whole however large it is, and after a syntax error it keeps returning that error, so one broken line ends the import. NDJSON offers a framing to exploit: one JSON value per line, so each line can be read, decoded and judged on its own.","title":"Why ShouldBindJSON and io.ReadAll fail on a file"},{"body":"The handler wraps the body in http.MaxBytesReader, reads it through a bufio.Reader whose buffer is exactly the line limit, and stops after maxRows rows. ReadSlice returns bufio.ErrBufferFull when a line does not fit; the loop then discards the rest of that line chunk by chunk, so an oversized record costs one buffer of memory and becomes a rejected row instead of a failed request. Each valid row goes into a transaction, and the mode decides whether it commits. main sends the same file in both modes, then a body over the cap, then the file to ShouldBindJSON.","code":"package main\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/gin-gonic/gin/binding\"\n\t\"github.com/go-playground/validator/v10\"\n)\n\nconst (\n\tmaxBody = 1 << 10 // whole request; a real service allows megabytes\n\tmaxLine = 120     // one record, newline included\n\tmaxRows = 1000    // bounds the transaction and the report\n)\n\ntype Product struct {\n\tSKU        string `json:\"sku\" binding:\"required,alphanum,max=12\"`\n\tName       string `json:\"name\" binding:\"required,max=40\"`\n\tPriceCents int    `json:\"price_cents\" binding:\"gt=0\"`\n}\n\ntype Row struct {\n\tLine   int    `json:\"line\"`\n\tStatus string `json:\"status\"` // \"valid\" or \"rejected\"\n\tSKU    string `json:\"sku,omitempty\"`\n\tReason string `json:\"reason,omitempty\"`\n}\n\ntype Report struct {\n\tMode     string `json:\"mode\"`\n\tImported int    `json:\"imported\"`\n\tRows     []Row  `json:\"rows\"`\n}\n\n// Catalog models the database; Tx models one transaction.\ntype Catalog struct{ items map[string]Product }\ntype Tx struct {\n\tcat     *Catalog\n\tpending []Product\n}\n\nfunc (c *Catalog) Begin() *Tx { return &Tx{cat: c} }\nfunc (t *Tx) Put(p Product)   { t.pending = append(t.pending, p) }\nfunc (t *Tx) Rollback()       { t.pending = nil }\nfunc (t *Tx) Commit() (n int) {\n\tfor _, p := range t.pending {\n\t\tt.cat.items[p.SKU] = p\n\t}\n\tn, t.pending = len(t.pending), nil\n\treturn n\n}\n\nvar errTooManyRows = errors.New(\"too many rows\")\n\n// readLines calls fn once per non-blank line. A line longer than limit bytes is\n// reported with a nil slice and skipped without ever being held in memory.\nfunc readLines(r io.Reader, limit int, fn func(n int, line []byte) error) error {\n\tbr := bufio.NewReaderSize(r, limit)\n\tfor n := 1; ; n++ {\n\t\tline, err := br.ReadSlice('\\n')\n\t\ttooLong := errors.Is(err, bufio.ErrBufferFull)\n\t\tfor errors.Is(err, bufio.ErrBufferFull) {\n\t\t\t_, err = br.ReadSlice('\\n') // discard the rest of the line\n\t\t}\n\t\tif err != nil && err != io.EOF {\n\t\t\treturn err // *http.MaxBytesError or a broken connection\n\t\t}\n\t\tif tooLong {\n\t\t\tline = nil\n\t\t}\n\t\tif tooLong || len(bytes.TrimSpace(line)) > 0 { // blank lines count, but are skipped\n\t\t\tif ferr := fn(n, line); ferr != nil {\n\t\t\t\treturn ferr\n\t\t\t}\n\t\t}\n\t\tif err == io.EOF {\n\t\t\treturn nil\n\t\t}\n\t}\n}\n\n// decodeRow decodes exactly one JSON object and validates it with Gin's validator.\nfunc decodeRow(line []byte) (Product, string) {\n\tvar p Product\n\tdec := json.NewDecoder(bytes.NewReader(line))\n\tdec.DisallowUnknownFields()\n\tif err := dec.Decode(&p); err != nil {\n\t\tvar syn *json.SyntaxError\n\t\tvar typ *json.UnmarshalTypeError\n\t\tswitch {\n\t\tcase errors.As(err, &syn), errors.Is(err, io.ErrUnexpectedEOF):\n\t\t\treturn p, \"invalid JSON\"\n\t\tcase errors.As(err, &typ):\n\t\t\treturn p, typ.Field + \" has the wrong type\"\n\t\tdefault:\n\t\t\treturn p, strings.TrimPrefix(err.Error(), \"json: \")\n\t\t}\n\t}\n\tif dec.Decode(new(json.RawMessage)) != io.EOF {\n\t\treturn p, \"more than one JSON value on the line\"\n\t}\n\tif err := binding.Validator.ValidateStruct(&p); err != nil {\n\t\tvar ves validator.ValidationErrors\n\t\tif errors.As(err, &ves) {\n\t\t\treturn p, ves[0].Field() + \" fails \" + ves[0].Tag()\n\t\t}\n\t\treturn p, \"invalid\"\n\t}\n\treturn p, \"\"\n}\n\nfunc importProducts(cat *Catalog) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tif c.ContentType() != \"application/x-ndjson\" {\n\t\t\tc.JSON(http.StatusUnsupportedMediaType, gin.H{\"error\": \"send application/x-ndjson\"})\n\t\t\treturn\n\t\t}\n\t\tmode := c.DefaultQuery(\"mode\", \"all\")\n\t\tif mode != \"all\" && mode != \"partial\" {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"mode is all or partial\"})\n\t\t\treturn\n\t\t}\n\t\tbody := http.MaxBytesReader(c.Writer, c.Request.Body, maxBody)\n\t\ttx := cat.Begin()\n\t\trep := Report{Mode: mode, Rows: []Row{}}\n\t\tseen := map[string]int{} // sku -> first line, to catch duplicates in one file\n\t\tvalid := 0\n\t\terr := readLines(body, maxLine, func(n int, line []byte) error {\n\t\t\tif len(rep.Rows) == maxRows {\n\t\t\t\treturn errTooManyRows\n\t\t\t}\n\t\t\tif line == nil {\n\t\t\t\trep.Rows = append(rep.Rows, Row{Line: n, Status: \"rejected\", Reason: fmt.Sprintf(\"longer than %d bytes\", maxLine)})\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tp, reason := decodeRow(line)\n\t\t\tif first, dup := seen[p.SKU]; reason == \"\" && dup {\n\t\t\t\treason = fmt.Sprintf(\"duplicate sku %s, first on line %d\", p.SKU, first)\n\t\t\t}\n\t\t\tif reason != \"\" {\n\t\t\t\trep.Rows = append(rep.Rows, Row{Line: n, Status: \"rejected\", Reason: reason})\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\tseen[p.SKU] = n\n\t\t\ttx.Put(p) // the database holds pending rows, not the handler\n\t\t\tvalid++\n\t\t\trep.Rows = append(rep.Rows, Row{Line: n, Status: \"valid\", SKU: p.SKU})\n\t\t\treturn nil\n\t\t})\n\t\tvar tooBig *http.MaxBytesError\n\t\tswitch {\n\t\tcase errors.As(err, &tooBig):\n\t\t\ttx.Rollback()\n\t\t\tc.JSON(http.StatusRequestEntityTooLarge, gin.H{\"error\": fmt.Sprintf(\"body exceeds %d bytes\", tooBig.Limit)})\n\t\t\treturn\n\t\tcase errors.Is(err, errTooManyRows):\n\t\t\ttx.Rollback()\n\t\t\tc.JSON(http.StatusRequestEntityTooLarge, gin.H{\"error\": fmt.Sprintf(\"more than %d rows\", maxRows)})\n\t\t\treturn\n\t\tcase err != nil:\n\t\t\ttx.Rollback()\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"could not read body\"})\n\t\t\treturn\n\t\tcase len(rep.Rows) == 0:\n\t\t\ttx.Rollback()\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"no rows\"})\n\t\t\treturn\n\t\t}\n\t\tif valid == 0 || (mode == \"all\" && valid < len(rep.Rows)) {\n\t\t\ttx.Rollback() // 422 always means nothing was written\n\t\t\tc.JSON(http.StatusUnprocessableEntity, rep)\n\t\t\treturn\n\t\t}\n\t\trep.Imported = tx.Commit() // 200 means every row marked valid was written\n\t\tc.JSON(http.StatusOK, rep)\n\t}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tif v, ok := binding.Validator.Engine().(*validator.Validate); ok {\n\t\tv.RegisterTagNameFunc(func(f reflect.StructField) string {\n\t\t\tname, _, _ := strings.Cut(f.Tag.Get(\"json\"), \",\")\n\t\t\treturn name\n\t\t})\n\t}\n\tcat := &Catalog{items: map[string]Product{}}\n\tr := gin.New()\n\tr.POST(\"/products/import\", importProducts(cat))\n\n\tfile := strings.Join([]string{\n\t\t`{\"sku\":\"MUG1\",\"name\":\"Gopher mug\",\"price_cents\":1200}`,\n\t\t`{\"sku\":\"CAP2\",\"name\":\"Cap\",\"price_cents\":0}`,\n\t\t`{\"sku\":\"PIN3\",\"name\":\"Pin\",\"price_cents\":300,\"color\":\"red\"}`,\n\t\t`{\"sku\":\"HAT4\",\"name\":\"Hat\",`,\n\t\t`{\"sku\":\"TEE5\",\"name\":\"` + strings.Repeat(\"x\", 100) + `\",\"price_cents\":2500}`,\n\t\t`{\"sku\":\"MUG1\",\"name\":\"Mug again\",\"price_cents\":900}`,\n\t\t``,\n\t\t`{\"sku\":\"PIN3\",\"name\":\"Pin\",\"price_cents\":300}`,\n\t}, \"\\n\") + \"\\n\"\n\n\tsend := func(mode, body string) (int, Report, string) {\n\t\treq := httptest.NewRequest(\"POST\", \"/products/import?mode=\"+mode, strings.NewReader(body))\n\t\treq.Header.Set(\"Content-Type\", \"application/x-ndjson\")\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tvar rep Report\n\t\t_ = json.Unmarshal(w.Body.Bytes(), &rep)\n\t\treturn w.Code, rep, w.Body.String()\n\t}\n\n\tcode, rep, _ := send(\"all\", file)\n\tfmt.Println(\"mode=all:\", code, \"imported:\", rep.Imported, \"catalog:\", len(cat.items))\n\tfor _, row := range rep.Rows {\n\t\tif row.Status == \"valid\" {\n\t\t\tfmt.Printf(\"  line %d valid %s\\n\", row.Line, row.SKU)\n\t\t} else {\n\t\t\tfmt.Printf(\"  line %d rejected: %s\\n\", row.Line, row.Reason)\n\t\t}\n\t}\n\tcode, rep, _ = send(\"partial\", file)\n\tfmt.Println(\"mode=partial:\", code, \"imported:\", rep.Imported, \"catalog:\", len(cat.items))\n\n\tbig := strings.Repeat(`{\"sku\":\"MUG1\",\"name\":\"Gopher mug\",\"price_cents\":1200}`+\"\\n\", 25)\n\tcode, _, raw := send(\"partial\", big)\n\tfmt.Println(\"oversized body:\", code, raw, \"catalog:\", len(cat.items))\n\n\t// The usual binder on the same body: one Decode call, the rest is ignored.\n\tc, _ := gin.CreateTestContext(httptest.NewRecorder())\n\tc.Request = httptest.NewRequest(\"POST\", \"/\", strings.NewReader(file))\n\tvar first Product\n\terr := c.ShouldBindJSON(&first)\n\tfmt.Println(\"ShouldBindJSON on NDJSON: err =\", err, \"sku =\", first.SKU)\n}","language":"go","title":"Three bounds: the body, each line and the row count","walkthrough":"Line 2 fails the gt=0 rule from its binding tag, line 3 carries a field the struct does not declare, and line 4 is a record cut short, which the decoder reports as io.ErrUnexpectedEOF rather than a syntax error. Line 5 is over 120 bytes and is never decoded at all. Line 6 is valid JSON but repeats the SKU from line 1, a rule only the handler can check. Line 7 is blank: skipped, but still counted, so the report uses the numbers an editor shows. With mode=all one rejected row rolls the transaction back and the answer is 422; with mode=partial the two valid rows commit with 200. The 25-line body trips MaxBytesReader partway through, the handler rolls back the rows it had already staged, and the catalog stays at two items."},{"body":"decodeRow gives every line its own json.Decoder. DisallowUnknownFields is set on that decoder alone, so the strictness applies to this endpoint without flipping the process-wide binding.EnableDecoderDisallowUnknownFields; the binding-limits lesson discusses when strict input is the right contract. A second Decode must return io.EOF, which rejects two values on one line yet tolerates the trailing carriage return of CRLF files, because JSON treats it as whitespace. Validation reuses the binding tags a ShouldBindJSON handler would use: binding.Validator is the StructValidator Gin itself calls, and ValidateStruct runs it on one row. Registering a tag-name function, as in the custom-validators lesson, makes errors say price_cents rather than PriceCents. encoding/json has no typed error for an unknown field, so the program trims the json: prefix from the message; keep that mapping in one function so a reworded message in a future release is a one-line fix.","title":"Decode one line strictly and reuse Gin's validator"},{"body":"Decide what each status code promises and keep it true in both modes. 422 Unprocessable Content means nothing was written: in mode=all because at least one row was rejected, in mode=partial because no row was valid. 200 means every row the report marks valid was written. 413 means the request itself was too large, by bytes or by rows, and nothing was written in either mode, because a request-level failure must never leave half a file behind. 415 answers a body that is not application/x-ndjson, and 400 a bad mode or an empty file. Avoid 207 Multi-Status: it comes from WebDAV, whose body is an XML multistatus document, and generic clients attach no meaning to it in a JSON API. Default to all-or-nothing, because a client can retry it blindly. Partial mode suits large hand-edited files, but the client must read the report, and resending a corrected file has to be safe: make rows idempotent, for example an upsert keyed by SKU, and accept an Idempotency-Key for retries of the same request, as the idempotency-keys lesson describes.","title":"All-or-nothing or partial: give each status one meaning"},{"body":"Tx stands in for a database transaction: the handler streams rows into it and never holds the file itself, and rolling back on every request-level error is what keeps a 413 honest. With PostgreSQL that is an INSERT per row or per batch inside one transaction, or COPY into a staging table followed by a single INSERT ... SELECT. The systems.transaction-boundary lesson explains why a use case rather than the handler should own that transaction; the program opens it in the handler only to stay short. A transaction that lasts as long as an upload runs at the client's pace: a slow client keeps a pooled connection and its locks busy, and http.Server.ReadTimeout, which covers reading the whole body, may cut the request off. http.ResponseController.SetReadDeadline can extend it for this route only. Past a few megabytes, store the file and process it as a job behind 202, which the async-jobs lesson builds. One detail of MaxBytesReader under Gin: net/http marks the connection for closing when the limit is hit only if it receives its own response writer, through an unexported method that c.Writer cannot forward. With c.Writer the server applies its general rule when the 413 is written instead: it drains up to 256 KiB of unread body or closes the connection.","title":"Let the database hold the pending rows"},{"body":"Assert line numbers and reasons, not just counts. Cover a blank line, CRLF endings, a last line without a newline, a line exactly at the limit and one byte over, a record split across two lines, two records on one line, a UTF-8 byte order mark at the start, which makes line 1 invalid JSON unless you strip it deliberately, a body over the cap in each mode and a row count over maxRows. After every rejected request, assert that the store is unchanged. Wrap test bodies in testing/iotest.OneByteReader to prove the line reader copes with short reads, since a network delivers bytes in arbitrary chunks. From a shell, send files with --data-binary.","code":"curl -i -X POST 'http://localhost:8080/products/import?mode=partial' \\\n  -H 'Content-Type: application/x-ndjson' \\\n  --data-binary @products.ndjson","language":"bash","title":"Test the framing, not only a happy file","walkthrough":"Run this against the service in your own development environment. --data-binary sends the file byte for byte; -d @products.ndjson would strip carriage returns and newlines, so the server would see one long line, reject it as over the line limit and, with no valid row, answer 422. -i prints the status line before the JSON report, so you can check that the status follows the rules above."}],"takeaway":"Cap the body with http.MaxBytesReader, read NDJSON one bounded line at a time, decode each line strictly and validate it with Gin's validator, and let the status say what was written: 422 nothing, 200 every valid row, 413 nothing because the request was too large.","title":"NDJSON imports in Gin: cap the body, decode one bounded line at a time, report each row by its line number","unitID":"gin-data","wrongAnswers":["Returns an error because data follows the first value","Binds the last record, since each Decode overwrites p"]},{"conceptTag":"gin.streaming-export","designGuide":{"cautions":["Errors after the first byte cannot change the status code.","Pages read at different moments are not one snapshot."],"cost":"A keyset query per page, a deliberate middleware order and a client contract for spotting truncation; strict consistency needs a long read-only transaction or a pre-built file.","family":"gin","flow":["Check, fetch page one","Commit the headers","Write a page, flush twice","Abort on late failure"],"ratings":[],"strengths":["Memory and query cost stay at one page for any export size.","Bytes flow from the start, so idle timeouts do not fire."]},"hint":"Read how CustomRecoveryWithWriter classifies a recovered error before it decides whether to call the handle function.","id":"gin.streaming-export","introduction":"An export of a million rows should cost the server one page of rows at a time, not a million rows of memory and a long silence before the first byte. Writing CSV straight into c.Writer and flushing after every page achieves that. It also changes the error model: once the first page is on the wire the status line has gone, so a database failure on page forty can no longer become a 500, and the handler needs another way to tell the client the file is incomplete.","nuance":"Recovery treats ErrAbortHandler like a broken pipe: it records the error, aborts the chain and returns normally, so net/http completes the chunked body. Re-panic from a middleware registered before Recovery.","objective":"Stream a large CSV from a Gin handler page by page with a safe download filename and formula-safe cells, and make a failure after the first byte visible to the client.","question":"In Gin v1.12.0, a streaming handler panics with http.ErrAbortHandler after its first page, under gin.Recovery(). What does the client receive?","references":["https://pkg.go.dev/encoding/csv#Writer","https://pkg.go.dev/mime#FormatMediaType","https://owasp.org/www-community/attacks/CSV_Injection","https://pkg.go.dev/net/http#ErrAbortHandler"],"reviewAnswer":"Recovery swallows it and the body ends cleanly","reviewPrompt":"Recovery vs http.ErrAbortHandler?","sections":[{"body":"The obvious export loads every row, renders the CSV into a buffer and calls c.Data. Memory grows with the export, the first byte waits for the last row, and proxies and browsers with idle timeouts can give up on a large account before anything arrives, while one query materializes the whole result. Streaming fixes all three: read one keyset page, write it, flush it, repeat. The pagination lesson explains why pages of rows after the last key stay fast and stable where OFFSET pages slow down and drift. Two buffers sit between csv.Writer.Write and the network. csv.NewWriter wraps its destination in a 4 KiB bufio.Writer, which csv.Writer.Flush empties into c.Writer, and net/http keeps a 2 KiB buffer of its own, which c.Writer.Flush pushes onto the connection. Calling both after each page keeps delivery steady; skipping the second leaves bytes waiting until net/http's buffer happens to fill.","title":"Build the file in memory and you pay three times"},{"body":"The handler fetches the first page before it writes anything, sets the headers, then loops: write a page, flush both buffers, stop on a short page, a canceled context or a store error. main first prints the Content-Disposition values for three list names, then runs a full export, a client that disconnects during page one, a store that is down before the first byte and a store that fails on page two, once with Gin's Recovery alone and once with abortPassthrough in front of it.","code":"package main\n\nimport (\n\t\"context\"\n\t\"encoding/csv\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"mime\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strconv\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype Contact struct {\n\tID                int\n\tName, Email, Note string\n}\n\n// Store models a database read with keyset pagination: rows after a key, in key order.\ntype Store struct {\n\trows   []Contact // sorted by ID\n\tfailAt int       // page number that fails; 0 means never\n\tserved int\n\tonPage func(page int)\n}\n\nfunc (s *Store) Page(ctx context.Context, afterID, limit int) ([]Contact, error) {\n\tif err := ctx.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\ts.served++\n\tif s.served == s.failAt {\n\t\treturn nil, errors.New(\"replica connection lost\")\n\t}\n\tvar out []Contact\n\tfor _, r := range s.rows {\n\t\tif r.ID > afterID && len(out) < limit {\n\t\t\tout = append(out, r)\n\t\t}\n\t}\n\tif s.onPage != nil {\n\t\ts.onPage(s.served)\n\t}\n\treturn out, nil\n}\n\n// safeCell keeps spreadsheet apps from evaluating user text as a formula.\nfunc safeCell(s string) string {\n\tif s != \"\" && strings.ContainsRune(\"=+-@\\t\\r\\n\", rune(s[0])) {\n\t\treturn \"'\" + s\n\t}\n\treturn s\n}\n\n// exportName builds a filename from user input: letters, digits, space, - _ only.\nfunc exportName(list string) string {\n\tname := strings.Map(func(r rune) rune {\n\t\tif unicode.IsLetter(r) || unicode.IsDigit(r) || strings.ContainsRune(\" -_\", r) {\n\t\t\treturn r\n\t\t}\n\t\treturn -1\n\t}, list)\n\tif name = strings.TrimSpace(name); name == \"\" || len(name) > 60 {\n\t\tname = \"contacts\"\n\t}\n\treturn name + \".csv\"\n}\n\nfunc exportContacts(s *Store, pageSize int) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tctx := c.Request.Context()\n\t\tpage, err := s.Page(ctx, 0, pageSize)\n\t\tif err != nil { // nothing is written yet, so the status can still say so\n\t\t\tc.JSON(http.StatusServiceUnavailable, gin.H{\"error\": \"export unavailable\"})\n\t\t\treturn\n\t\t}\n\t\tdisp := mime.FormatMediaType(\"attachment\", map[string]string{\"filename\": exportName(c.Query(\"list\"))})\n\t\tif disp == \"\" {\n\t\t\tdisp = \"attachment; filename=contacts.csv\"\n\t\t}\n\t\tc.Header(\"Content-Type\", \"text/csv; charset=utf-8\")\n\t\tc.Header(\"Content-Disposition\", disp)\n\t\tc.Header(\"X-Content-Type-Options\", \"nosniff\")\n\t\tc.Status(http.StatusOK)\n\n\t\tw := csv.NewWriter(c.Writer)\n\t\t_ = w.Write([]string{\"id\", \"name\", \"email\", \"note\"})\n\t\tfor {\n\t\t\tfor _, ct := range page {\n\t\t\t\t_ = w.Write([]string{strconv.Itoa(ct.ID), safeCell(ct.Name), safeCell(ct.Email), safeCell(ct.Note)})\n\t\t\t}\n\t\t\tw.Flush() // csv's buffer -> c.Writer; the first flush commits 200\n\t\t\tif w.Error() != nil {\n\t\t\t\treturn // the client stopped reading; nobody is left to tell\n\t\t\t}\n\t\t\tc.Writer.Flush() // c.Writer -> the connection\n\t\t\tif len(page) < pageSize {\n\t\t\t\treturn // short page: the export is complete\n\t\t\t}\n\t\t\tpage, err = s.Page(ctx, page[len(page)-1].ID, pageSize)\n\t\t\tif ctx.Err() != nil {\n\t\t\t\treturn // client gone or server shutting down: stop reading the database\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\t_ = c.Error(err) // for the access log\n\t\t\t\tpanic(http.ErrAbortHandler)\n\t\t\t}\n\t\t}\n\t}\n}\n\n// abortPassthrough must run outside gin.Recovery, which swallows http.ErrAbortHandler.\nfunc abortPassthrough(c *gin.Context) {\n\tc.Next()\n\tfor _, e := range c.Errors {\n\t\tif errors.Is(e.Err, http.ErrAbortHandler) {\n\t\t\tpanic(http.ErrAbortHandler) // net/http now breaks the connection\n\t\t}\n\t}\n}\n\n// serve is what net/http does around a handler: an ErrAbortHandler panic means\n// \"close the connection without finishing the body\".\nfunc serve(h http.Handler, req *http.Request) (w *httptest.ResponseRecorder, aborted bool) {\n\tw = httptest.NewRecorder()\n\tdefer func() {\n\t\tif rec := recover(); rec != nil {\n\t\t\tif rec != http.ErrAbortHandler {\n\t\t\t\tpanic(rec)\n\t\t\t}\n\t\t\taborted = true\n\t\t}\n\t}()\n\th.ServeHTTP(w, req)\n\treturn w, false\n}\n\nfunc newRouter(s *Store, passthrough bool) *gin.Engine {\n\tr := gin.New()\n\tif passthrough {\n\t\tr.Use(abortPassthrough)\n\t}\n\tr.Use(gin.Recovery())\n\tr.GET(\"/contacts.csv\", exportContacts(s, 3))\n\treturn r\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tgin.DefaultErrorWriter = io.Discard // keep Recovery's log out of the demo\n\trows := []Contact{\n\t\t{1, \"Avery\", \"avery@example.com\", `=HYPERLINK(\"https://attacker.example\",\"invoice\")`},\n\t\t{2, \"Blake, Jr.\", \"blake@example.com\", \"+44 20 7946 0000\"},\n\t\t{3, \"Casey\", \"casey@example.com\", \"-2+3\"},\n\t\t{4, \"Devon\", \"devon@example.com\", \"@SUM(A1:A9)\"},\n\t\t{5, \"Emery\", \"emery@example.com\", `says \"hi\"`},\n\t\t{6, \"Finley\", \"finley@example.com\", \"plain note\"},\n\t\t{7, \"Gray\", \"gray@example.com\", \"\"},\n\t}\n\tfor _, list := range []string{\"Q4 leads\", \"Zoë's list\", \"../../etc/passwd\\r\\nX: 1\"} {\n\t\tfmt.Printf(\"%q -> %s\\n\", list, mime.FormatMediaType(\"attachment\", map[string]string{\"filename\": exportName(list)}))\n\t}\n\n\ts := &Store{rows: rows}\n\tw, _ := serve(newRouter(s, true), httptest.NewRequest(\"GET\", \"/contacts.csv?list=Q4+leads\", nil))\n\tfmt.Println(w.Code, w.Header().Get(\"Content-Type\"), \"pages:\", s.served, \"flushed:\", w.Flushed)\n\tfmt.Print(w.Body.String())\n\n\tctx, disconnect := context.WithCancel(context.Background())\n\ts = &Store{rows: rows, onPage: func(int) { disconnect() }}\n\tw, aborted := serve(newRouter(s, true), httptest.NewRequest(\"GET\", \"/contacts.csv\", nil).WithContext(ctx))\n\tfmt.Println(\"client gone after page 1:\", w.Code, \"pages:\", s.served, \"lines:\", strings.Count(w.Body.String(), \"\\n\"), \"aborted:\", aborted)\n\n\ts = &Store{rows: rows, failAt: 1}\n\tw, _ = serve(newRouter(s, true), httptest.NewRequest(\"GET\", \"/contacts.csv\", nil))\n\tfmt.Println(\"store down before first byte:\", w.Code, w.Body.String())\n\n\tfor _, passthrough := range []bool{false, true} {\n\t\ts = &Store{rows: rows, failAt: 2}\n\t\tw, aborted = serve(newRouter(s, passthrough), httptest.NewRequest(\"GET\", \"/contacts.csv\", nil))\n\t\tfmt.Println(\"store fails on page 2, passthrough\", passthrough, \"->\", w.Code, \"lines:\", strings.Count(w.Body.String(), \"\\n\"), \"aborted:\", aborted)\n\t}\n}","language":"go","title":"An export handler and the ways it can end","walkthrough":"Seven contacts at three per page take three queries; the third page is short, which ends the loop without a fourth. Every user-supplied cell that starts with =, +, -, @, tab, carriage return or line feed gains a leading apostrophe, and encoding/csv quotes the fields that contain commas or quotes and doubles the inner quotes. When the request context is canceled during page one, the handler still writes that page, then its next Page call returns the context error and the loop ends without querying again. A store that fails before the first byte still gets an honest 503. On page two the status is already 200, so the only signal left is the connection itself. With Recovery alone the response ends normally after four lines, which a client cannot tell from a complete export; with abortPassthrough the ErrAbortHandler panic reaches serve, which plays the part of net/http."},{"body":"Content-Disposition carries a filename the browser proposes to the user, so build it like any other output. exportName keeps letters, digits, spaces, hyphens and underscores, falls back to a fixed name when nothing usable is left or the result is too long, and appends the extension itself, so path separators and CR LF never reach the header. mime.FormatMediaType then picks the encoding: a bare token, a quoted string with escaped quotes for ASCII with spaces, or the RFC 2231 form filename*=utf-8'' with percent-encoding for anything else. RFC 6266 defines that filename* parameter for HTTP and current browsers read it. FormatMediaType returns an empty string for an invalid type or parameter name, so keep the fallback. Gin's c.FileAttachment is no substitute: it serves a file from disk, and for non-ASCII names v1.12.0 encodes with url.QueryEscape, which writes spaces as + that RFC 8187 decoding keeps literally, so the browser saves Zoë+list.csv. CSV injection is the second risk. Spreadsheet apps can evaluate a cell that starts with =, +, - or @ as a formula, and OWASP's list adds control characters such as tab and carriage return, so an exported note can build links that leak neighboring cells. OWASP recommends prefixing such cells with a single quote, as safeCell does, while the encoder handles quotes and separators inside the field. That changes the data, so apply it only to free-text columns from users, never to values you format yourself: a negative balance would become text. Offer JSON for machine consumers that need raw values.","title":"Filenames and cells are user input too"},{"body":"The first flush sends the 200 and the headers. From then on Gin's responseWriter ignores WriteHeader, printing a warning only in debug mode, so a c.JSON(500, ...) in the error path would append a JSON object to the CSV and still report success. Two rules follow. First, do everything that can fail cheaply before the first byte: authorize, validate parameters and run the first query, which is why the store-down case can still answer 503. Second, make a late failure visible as truncation. A panic with http.ErrAbortHandler makes net/http close the connection without the final zero-length chunk on HTTP/1.1, or reset the stream on HTTP/2, so curl, browsers and HTTP libraries report an error instead of saving a short file; net/http also skips the stack trace for that value. The surprise is gin.Recovery: v1.12.0 classifies ErrAbortHandler with broken pipes, records it with c.Error, aborts the chain and returns normally, so net/http finishes the response cleanly. abortPassthrough, registered before Recovery, finds the recorded error after c.Next returns and panics again outside Recovery's reach. Log the failure with the request ID and the last key written. Programmatic clients can also check an HTTP trailer or a final row count, but browsers ignore trailers, so the abort is the signal that works everywhere.","title":"After the first byte, the status line is history"},{"body":"net/http cancels the request context when the client disconnects or an HTTP/2 stream is reset. Pass that context to every query so the one in flight is canceled, and check it before the next page, or the handler keeps reading the database for nobody; a write error from csv.Writer.Error after Flush is the same signal from the other side. A long export also outlives http.Server.WriteTimeout, so renew the write deadline per page with ResponseController, as the SSE lesson does for event streams. Each page is its own statement, so the file is not a point-in-time snapshot: a row edited between pages shows whichever value its page saw. When the export must be consistent, read every page inside one read-only REPEATABLE READ transaction, which in PostgreSQL gives all its statements the same snapshot, and accept that a transaction open for the whole download delays vacuum. For very large or audited exports, generate the file as a job, which the async-jobs lesson builds, and serve the finished file with a Content-Length.","code":"tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true})\nif err != nil {\n\treturn err // still before the first byte: the handler can answer 503\n}\ndefer tx.Rollback() // read-only: rolling back just releases the snapshot\n\nrc := http.NewResponseController(c.Writer)\nnextPage := func(afterID int64) (*sql.Rows, error) {\n\t// A fresh write budget per page instead of the server-wide WriteTimeout.\n\tif err := rc.SetWriteDeadline(time.Now().Add(30 * time.Second)); err != nil && !errors.Is(err, http.ErrNotSupported) {\n\t\treturn nil, err\n\t}\n\treturn tx.QueryContext(ctx, `SELECT id, name, email, note FROM contacts\n\t\tWHERE account_id = $1 AND id > $2 ORDER BY id LIMIT $3`, accountID, afterID, pageSize)\n}","language":"go","title":"Cancellation, write deadlines and one consistent snapshot","walkthrough":"This fragment runs against a real PostgreSQL database in your own environment. BeginTx with LevelRepeatableRead and ReadOnly pins one snapshot for every page, and the deferred Rollback releases it, which is all a read-only transaction needs. nextPage renews the write deadline before each page, tolerating http.ErrNotSupported from writers that cannot set one, then selects rows strictly after the last ID. With an index on (account_id, id), every page is a short range scan however deep into the export it is."},{"body":"Parse the body back with csv.NewReader and compare records rather than raw text, so a quoting change does not break tests while a content change does. Include hostile cells for every formula prefix, embedded commas, quotes and newlines, a non-ASCII list name, and page boundaries: zero rows, exactly one page, one row more than a page. Cancel mid-stream and assert that the store stopped being called, and fail both before and after the first byte. Build the test engine with the same middleware order as production, because the abort works only when abortPassthrough runs outside Recovery; a test with a different chain would pass while production silently truncates. Finally, run one integration test against a real listener and assert that reading the body of a failed export ends in an error such as io.ErrUnexpectedEOF rather than a clean EOF.","title":"Test it the way a client reads it"}],"takeaway":"Fetch the first page before writing, stream CSV page by page with csv.Writer.Flush and c.Writer.Flush, stop on the request context, build Content-Disposition with mime.FormatMediaType, prefix formula-leading cells, and abort the connection on late failures from outside gin.Recovery.","title":"Streaming CSV exports in Gin: keyset pages, two flushes, formula-safe cells and an abort on late failure","unitID":"gin-data","wrongAnswers":["A 500 Internal Server Error that replaces the 200","A connection reset, because net/http aborts the response"]},{"conceptTag":"gin.async-jobs","designGuide":{"cautions":["An in-memory queue loses every job on restart.","Guessable job IDs leak other users' results without owner checks."],"cost":"A job store, a worker pool with its own shutdown, polling traffic and result retention; durability adds a jobs table, leases and idempotent work.","family":"gin","flow":["Validate, then enqueue","Answer 202 + Location","Workers run the job","Client polls the job"],"ratings":[],"strengths":["Request latency stays small whatever the job costs.","Overload is explicit: a bounded queue and a 503 with Retry-After."]},"hint":"Look up when net/http cancels the context of an incoming server request.","id":"gin.async-jobs","introduction":"Some requests ask for work that takes longer than any sensible request budget: a monthly report, a re-index, a large import. Holding the connection open ties up a goroutine, a proxy slot and the client's patience, and a timeout halfway leaves the client unsure whether anything happened. The asynchronous pattern splits the work from the request: the POST validates and enqueues, answers 202 Accepted with the URL of a job resource, and the client polls that resource until it reports a result or a failure.","nuance":"net/http cancels an incoming request's context when ServeHTTP returns, so the job sees context.Canceled. context.WithoutCancel keeps the values and drops the cancellation; the worker then adds its own deadline.","objective":"Accept slow work with 202 and a job Location, bound it with a queue and a fixed worker pool, refuse overload with 503 and Retry-After, and keep jobs running after the request ends.","question":"A Gin handler enqueues a job that carries c.Request.Context() and returns 202. What happens to that context by the time a worker runs the job?","references":["https://www.rfc-editor.org/rfc/rfc9110#section-15.3.3","https://www.rfc-editor.org/rfc/rfc9110#section-10.2.3","https://pkg.go.dev/context#WithoutCancel","https://pkg.go.dev/sync#WaitGroup.Go"],"reviewAnswer":"Canceled once ServeHTTP returns; detach it","reviewPrompt":"Job ctx = c.Request.Context()?","sections":[{"body":"RFC 9110 defines 202 as accepted for processing, with processing not yet complete and possibly never completing; the response ought to describe the request's current status and point to a status monitor. In practice that means three things. Everything that can be rejected synchronously is rejected before the 202: malformed input, missing permission and an exhausted quota get a 4xx immediately, because after a 202 the job resource is the only channel left. The 202 carries a Location header with the job URL; RFC 9110 defines Location for 201 and redirects, and using it with 202 is a widespread convention clients expect. And the job resource has a small, closed lifecycle: queued, running, then succeeded with a link to the result or failed with a public error message. Terminal states never change, so a client can stop polling as soon as it sees one.","title":"What 202 Accepted promises"},{"body":"Pool owns the job records, a buffered channel as the queue and a fixed set of workers started with WaitGroup.Go. Submit records and enqueues a job in one critical section and never blocks; the handler turns its refusal into a 503. main holds jobs inside the work function with two channels: started tells main that a worker has picked a job up, and release lets one job finish. That fixes the order of every observable state without a single sleep.","code":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\ntype Job struct {\n\tID     string `json:\"id\"`\n\tStatus string `json:\"status\"` // queued, running, succeeded, failed\n\tResult string `json:\"result,omitempty\"`\n\tError  string `json:\"error,omitempty\"`\n}\n\ntype task struct {\n\tid, month string\n\tctx       context.Context // request values without request cancellation\n}\n\nvar errBusy = errors.New(\"queue full or shutting down\")\n\n// Pool is a fixed set of workers reading one bounded queue.\ntype Pool struct {\n\tmu     sync.Mutex\n\tjobs   map[string]*Job\n\tqueue  chan task\n\tclosed bool\n\tlast   int\n\twg     sync.WaitGroup\n\tbudget time.Duration\n\twork   func(ctx context.Context, month string) error\n}\n\nfunc NewPool(workers, depth int, budget time.Duration, work func(context.Context, string) error) *Pool {\n\tp := &Pool{jobs: map[string]*Job{}, queue: make(chan task, depth), budget: budget, work: work}\n\tfor range workers {\n\t\tp.wg.Go(func() {\n\t\t\tfor t := range p.queue {\n\t\t\t\tp.update(t.id, func(j *Job) { j.Status = \"running\" })\n\t\t\t\terr := p.execute(t)\n\t\t\t\tp.update(t.id, func(j *Job) {\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tj.Status, j.Error = \"failed\", err.Error()\n\t\t\t\t\t} else {\n\t\t\t\t\t\tj.Status, j.Result = \"succeeded\", \"/reports/\"+t.id+\"/result\"\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t}\n\treturn p\n}\n\n// execute gives each job its own deadline and turns a panic into a failed job.\nfunc (p *Pool) execute(t task) (err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"job panicked: %v\", r)\n\t\t}\n\t}()\n\tctx, cancel := context.WithTimeout(t.ctx, p.budget)\n\tdefer cancel()\n\treturn p.work(ctx, t.month)\n}\n\nfunc (p *Pool) Submit(reqCtx context.Context, month string) (Job, error) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tif p.closed {\n\t\treturn Job{}, errBusy\n\t}\n\tid := strconv.Itoa(p.last + 1)\n\tselect {\n\tcase p.queue <- task{id: id, month: month, ctx: context.WithoutCancel(reqCtx)}:\n\t\tp.last++\n\t\tp.jobs[id] = &Job{ID: id, Status: \"queued\"} // workers wait for p.mu, so this lands first\n\t\treturn *p.jobs[id], nil\n\tdefault:\n\t\treturn Job{}, errBusy\n\t}\n}\n\nfunc (p *Pool) update(id string, f func(*Job)) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tf(p.jobs[id])\n}\n\nfunc (p *Pool) Get(id string) (Job, bool) {\n\tp.mu.Lock()\n\tdefer p.mu.Unlock()\n\tj, ok := p.jobs[id]\n\tif !ok {\n\t\treturn Job{}, false\n\t}\n\treturn *j, true\n}\n\n// Shutdown stops intake, lets workers drain the queue and waits for them.\nfunc (p *Pool) Shutdown() {\n\tp.mu.Lock()\n\tp.closed = true\n\tclose(p.queue)\n\tp.mu.Unlock()\n\tp.wg.Wait()\n}\n\nfunc createReport(p *Pool) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar in struct {\n\t\t\tMonth string `json:\"month\" binding:\"required,datetime=2006-01\"`\n\t\t}\n\t\tif err := c.ShouldBindJSON(&in); err != nil {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"month must look like 2026-10\"})\n\t\t\treturn\n\t\t}\n\t\tjob, err := p.Submit(c.Request.Context(), in.Month)\n\t\tif err != nil {\n\t\t\tc.Header(\"Retry-After\", \"30\")\n\t\t\tc.JSON(http.StatusServiceUnavailable, gin.H{\"error\": \"report queue is full\"})\n\t\t\treturn\n\t\t}\n\t\tc.Header(\"Location\", \"/jobs/\"+job.ID)\n\t\tc.JSON(http.StatusAccepted, job)\n\t}\n}\n\nfunc getJob(p *Pool) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tjob, ok := p.Get(c.Param(\"id\"))\n\t\tif !ok {\n\t\t\tc.JSON(http.StatusNotFound, gin.H{\"error\": \"no such job\"})\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusOK, job)\n\t}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tstarted := make(chan string)\n\trelease := make(chan struct{})\n\twork := func(ctx context.Context, month string) error {\n\t\tstarted <- month\n\t\t<-release\n\t\tif err := ctx.Err(); err != nil {\n\t\t\treturn err // a job built on c.Request.Context() would stop here\n\t\t}\n\t\tif month == \"2026-09\" {\n\t\t\treturn errors.New(\"ledger archive offline\")\n\t\t}\n\t\treturn nil\n\t}\n\tpool := NewPool(2, 1, time.Minute, work)\n\tr := gin.New()\n\tr.POST(\"/reports\", createReport(pool))\n\tr.GET(\"/jobs/:id\", getJob(pool))\n\n\tpost := func(month string) context.Context {\n\t\tctx, cancel := context.WithCancel(context.Background())\n\t\treq := httptest.NewRequest(\"POST\", \"/reports\", strings.NewReader(`{\"month\":\"`+month+`\"}`)).WithContext(ctx)\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tcancel() // net/http cancels the request context when ServeHTTP returns\n\t\thdr := \"\"\n\t\tif v := w.Header().Get(\"Location\"); v != \"\" {\n\t\t\thdr = \" Location: \" + v\n\t\t}\n\t\tif v := w.Header().Get(\"Retry-After\"); v != \"\" {\n\t\t\thdr = \" Retry-After: \" + v\n\t\t}\n\t\tfmt.Printf(\"POST %s -> %d%s %s\\n\", month, w.Code, hdr, w.Body.String())\n\t\treturn ctx\n\t}\n\tget := func(id string) {\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, httptest.NewRequest(\"GET\", \"/jobs/\"+id, nil))\n\t\tfmt.Printf(\"GET /jobs/%s -> %d %s\\n\", id, w.Code, w.Body.String())\n\t}\n\n\treqCtx := post(\"2026-10\")\n\tfmt.Println(\"request context of job 1 after the 202:\", reqCtx.Err())\n\t<-started // job 1 is running on one worker\n\tpost(\"2026-09\")\n\t<-started       // job 2 is running on the other\n\tpost(\"2026-08\") // waits in the queue\n\tpost(\"2026-07\") // queue full\n\tpost(\"October\")\n\tget(\"1\")\n\tget(\"3\")\n\n\trelease <- struct{}{} // one worker finishes and takes job 3\n\t<-started\n\trelease <- struct{}{}\n\trelease <- struct{}{}\n\tpool.Shutdown()\n\tfmt.Println(\"shutdown: queue drained, workers joined\")\n\tfor _, id := range []string{\"1\", \"2\", \"3\", \"4\"} {\n\t\tget(id)\n\t}\n}","language":"go","title":"A pool with two workers and room for one more","walkthrough":"Job 1 starts on the first worker and job 2 on the second, so job 3 waits in the one-slot queue and the fourth POST finds it full: 503 with Retry-After and no job created, which the final 404 confirms. October fails the datetime=2006-01 rule before any job exists. The second line matters most: once ServeHTTP has returned, the request context is canceled, yet job 1 later succeeds, because its task carries context.WithoutCancel of that context. The first release frees one worker, which takes job 3 and reports through started; the next two releases let the remaining jobs finish. Shutdown closes the queue under the lock and waits for both workers, so every job is terminal before the final GETs: job 2 failed because its work returned an error, and the other two succeeded and link to their results."},{"body":"The channel capacity is the backlog you are willing to promise, and the worker count is the concurrency the downstream system can sustain; the bounded-work lesson shows how to size both. Submit uses select with a default case, so a full queue is an immediate answer rather than a blocked handler. Waiting for space would only move the queue into parked goroutines, where nothing bounds or measures it. Answer 503 Service Unavailable with Retry-After so clients and SDKs know when to come back. Prefer it to 429, which says that this client exceeded its own quota, as in the rate-limiting lesson; a full queue is a statement about the service. Submit holds the mutex while it sends and records the job, so a worker cannot update a job that does not exist yet, and the close in Shutdown cannot race a send, which would panic. The counter IDs in the demo are for readability only. Real job IDs must be unguessable, and every GET must check that the caller owns the job, or /jobs/{n+1} hands one customer the report of another, as the tenant-isolation lesson warns.","title":"Bound the queue, fix the workers, refuse early"},{"body":"net/http cancels an incoming request's context when ServeHTTP returns, a moment after the 202 is written, so a job that runs on c.Request.Context() is canceled almost as soon as it starts. context.WithoutCancel returns a context that keeps the parent's values, such as the request ID, trace span and principal set by middleware, but has no deadline, never reports an error and has a nil Done channel. The worker adds the job's own budget with WithTimeout when the job starts rather than when it is enqueued, so time spent queued does not eat it. Give the worker the request's context and plain data, never *gin.Context or c.Copy(); the engine recycles context objects, as the context-workers lesson explains. gin.Recovery protects only the handler goroutine, and a panic in a worker goroutine kills the whole process, which is why execute recovers and records the job as failed. Shutdown here drains the queue and joins the workers. In production, bound that with the shutdown budget from the server-lifecycle lesson and give running jobs a pool-level stop signal; context.AfterFunc can cancel each job's context when the pool's context is canceled.","title":"Detach the request context, never the gin.Context"},{"body":"Every queued and running job in this pool disappears on a deploy, a crash or an out-of-memory kill, and with two replicas the one that did not accept job 1 answers 404 for it. When losing a job is unacceptable, persist it before the 202: insert the job row in the same transaction as any business change it depends on, which is the outbox pattern from the systems.outbox-inbox lesson, and let workers claim due rows with a lease. A crashed worker's lease expires and another worker runs the job again, so execution becomes at least once and the work itself must be idempotent. A context cannot be stored, so persist the values the job needs, such as the trace ID and the principal, as columns. A client that retries a POST whose 202 was lost would create a second job, so accept an Idempotency-Key as the idempotency-keys lesson describes, and delete finished jobs and their results after a published retention period.","code":"// A worker claims one due job. SKIP LOCKED lets many workers poll one table.\nconst claim = `\nUPDATE jobs SET status = 'running', attempts = attempts + 1,\n       lease_until = now() + interval '5 minutes'\nWHERE id = (\n    SELECT id FROM jobs\n    WHERE status = 'queued' OR (status = 'running' AND lease_until < now())\n    ORDER BY created_at\n    LIMIT 1\n    FOR UPDATE SKIP LOCKED)\nRETURNING id, kind, input, trace_id`\n\nvar id, kind, traceID string\nvar input []byte\nerr := db.QueryRowContext(ctx, claim).Scan(&id, &kind, &input, &traceID)\nif errors.Is(err, sql.ErrNoRows) {\n\treturn nil // nothing due: wait for a notification or the next poll tick\n}","language":"go","title":"An in-memory pool is a model; durable jobs live in the database","walkthrough":"This fragment runs against PostgreSQL in your own environment. The inner SELECT finds the oldest job that is queued or whose lease has expired, and FOR UPDATE SKIP LOCKED lets many workers run the same statement without blocking each other or claiming the same row. The UPDATE marks it running with a five-minute lease and counts the attempt, and the trace ID comes back as data because no context survived the restart. sql.ErrNoRows means nothing is due. A job that exceeds a maximum attempt count should move to failed rather than retry forever."},{"body":"A test that sleeps and hopes a worker has started is slow on a fast machine and flaky on a loaded one. Make the work function observable instead: an unbuffered started channel proves that a worker holds a job, a release channel decides when it finishes, and Shutdown joins the workers before the final assertions. Cover the full queue and its Retry-After, validation failures that create no job, an unknown or foreign job ID, a job that returns an error, a job that panics, Submit during shutdown and a request context canceled before the worker starts. For deadlines, the synctest lesson shows how to test them without the wall clock. Run the suite with -race, because handlers and workers touch the pool at the same time. On the client side, poll with backoff and honor Retry-After, or let the client register a webhook that is called when the job reaches a terminal state; the webhook-receiver lesson covers the receiving end.","title":"Test the lifecycle with channels, not sleeps"}],"takeaway":"Validate synchronously, enqueue without blocking, answer 202 with a Location for the job, refuse a full queue with 503 and Retry-After, run each job on context.WithoutCancel plus its own deadline, and persist jobs when losing one is unacceptable.","title":"Long work behind 202 Accepted in Gin: a bounded queue, fixed workers, a job resource and an honest 503","unitID":"gin-data","wrongAnswers":["It stays live until the client closes the connection","It inherits the server's IdleTimeout as its deadline"]},{"conceptTag":"gin.webhook-receiver","designGuide":{"cautions":["Dedupe records must outlive the sender's retry schedule.","A 4xx for unhandled event types only causes pointless retries."],"cost":"A shared secret per sender with rotation, a dedupe store with retention, a queue and workers, and monitoring of rejection rates.","family":"gin","flow":["Read the bounded raw body","Verify HMAC and timestamp","Dedupe by event ID","Enqueue, answer 2xx"],"ratings":[],"strengths":["Forged, altered and replayed requests never reach business code.","Duplicate deliveries are acknowledged without reprocessing."]},"hint":"Think about what the sender's HMAC was computed over, and what binding does to the request body.","id":"gin.webhook-receiver","introduction":"A webhook endpoint is a public URL that anyone can POST to, called by a sender that retries whatever it believes failed. Three things matter more than the business logic: proving the request came from the sender unaltered, refusing old requests replayed by someone who captured one, and processing each event once although it may arrive several times. The status code is an instruction to the sender's retry machinery, so choose it as carefully as the verification.","nuance":"Binding reads c.Request.Body to EOF, and re-encoding the struct does not reproduce the sender's bytes, so the MAC can only be checked on the raw body, read first and then restored for the handler.","objective":"Receive signed webhooks in Gin by authenticating the raw body before binding, rejecting replays, deduplicating deliveries and choosing status codes that make the sender retry only when a retry can help.","question":"Why must a Gin webhook handler verify the signature before it calls c.ShouldBindJSON?","references":["https://pkg.go.dev/crypto/hmac#Equal","https://docs.github.com/en/webhooks/using-webhooks/validating-webhook-deliveries","https://www.rfc-editor.org/rfc/rfc2104","https://pkg.go.dev/net/http#MaxBytesReader"],"reviewAnswer":"The MAC covers raw bytes; binding consumes them","reviewPrompt":"Why verify before ShouldBindJSON?","sections":[{"body":"The sender computes HMAC-SHA256 with a shared secret over the exact bytes it sends; in this lesson that is the timestamp header, a dot and the body, a layout many providers use in some form, but follow your sender's documentation for the precise format. The receiver must recompute the MAC over the same bytes. Binding first breaks that: c.ShouldBindJSON reads c.Request.Body to the end, and re-encoding the bound struct does not reproduce the sender's bytes, because field order, spacing, escaping, number formatting and unknown fields all change. It also parses unauthenticated input before you know who sent it. So the verification middleware reads the body once through http.MaxBytesReader, checks it, and puts the same bytes back as a fresh reader so the handler can bind as usual. io.ReadAll is right here, unlike in the streaming-import lesson: a webhook payload is small, the cap is tight and the MAC needs every byte anyway. c.GetRawData is the same io.ReadAll with no limit of its own, so it needs the MaxBytesReader just as much.","title":"The signature covers bytes, so read them before anything parses them"},{"body":"verifySignature runs on the /webhooks group only. It bounds and reads the body, verifies the signature and then the timestamp against an injected clock, records the precise reason with c.Error when it rejects, and restores the body. receive binds the event, acknowledges types it does not handle, and asks Inbox to deduplicate and enqueue in one step. main signs each delivery with a test-only secret, the way a sender would, and prints the status, the body and the reason an access log would record.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"crypto/hmac\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nconst (\n\tmaxPayload = 64 << 10\n\ttolerance  = 5 * time.Minute\n)\n\ntype Event struct {\n\tID   string          `json:\"id\" binding:\"required\"`\n\tType string          `json:\"type\" binding:\"required\"`\n\tData json.RawMessage `json:\"data\"`\n}\n\nfunc sign(secret []byte, ts string, body []byte) []byte {\n\tmac := hmac.New(sha256.New, secret)\n\tmac.Write([]byte(ts))\n\tmac.Write([]byte{'.'})\n\tmac.Write(body)\n\treturn mac.Sum(nil)\n}\n\n// verify checks every v1= signature in the header, so a sender can rotate secrets.\nfunc verify(secret []byte, ts, header string, body []byte, now time.Time) error {\n\twant := sign(secret, ts, body)\n\tok := false\n\tfor part := range strings.SplitSeq(header, \",\") {\n\t\tif v, found := strings.CutPrefix(strings.TrimSpace(part), \"v1=\"); found {\n\t\t\tgot, err := hex.DecodeString(v)\n\t\t\tok = ok || (err == nil && hmac.Equal(got, want))\n\t\t}\n\t}\n\tif !ok {\n\t\treturn errors.New(\"signature mismatch\")\n\t}\n\tsec, err := strconv.ParseInt(ts, 10, 64)\n\tif err != nil {\n\t\treturn errors.New(\"bad timestamp\")\n\t}\n\tif age := now.Sub(time.Unix(sec, 0)); age > tolerance || age < -tolerance {\n\t\treturn errors.New(\"timestamp outside tolerance\")\n\t}\n\treturn nil\n}\n\n// verifySignature authenticates the raw bytes before anything parses them,\n// then hands the same bytes to the handler.\nfunc verifySignature(secret []byte, now func() time.Time) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\traw, err := io.ReadAll(http.MaxBytesReader(c.Writer, c.Request.Body, maxPayload))\n\t\tvar tooBig *http.MaxBytesError\n\t\tif errors.As(err, &tooBig) {\n\t\t\tc.AbortWithStatusJSON(http.StatusRequestEntityTooLarge, gin.H{\"error\": \"payload too large\"})\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tc.AbortWithStatus(http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\t\tts, sig := c.GetHeader(\"Webhook-Timestamp\"), c.GetHeader(\"Webhook-Signature\")\n\t\tif err := verify(secret, ts, sig, raw, now()); err != nil {\n\t\t\t_ = c.Error(err) // the reason goes to the log, not to the caller\n\t\t\tc.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\"error\": \"invalid signature\"})\n\t\t\treturn\n\t\t}\n\t\tc.Request.Body = io.NopCloser(bytes.NewReader(raw))\n\t\tc.Next()\n\t}\n}\n\n// Inbox records event IDs and queues events; both happen under one lock.\ntype Inbox struct {\n\tmu    sync.Mutex\n\tseen  map[string]bool\n\tqueue chan Event\n}\n\nvar errBusy = errors.New(\"queue full\")\n\nfunc (in *Inbox) Accept(e Event) (duplicate bool, err error) {\n\tin.mu.Lock()\n\tdefer in.mu.Unlock()\n\tif in.seen[e.ID] {\n\t\treturn true, nil\n\t}\n\tselect {\n\tcase in.queue <- e:\n\t\tin.seen[e.ID] = true // only once the event is safely queued\n\t\treturn false, nil\n\tdefault:\n\t\treturn false, errBusy\n\t}\n}\n\nvar handled = map[string]bool{\"payment.succeeded\": true, \"payment.refunded\": true}\n\nfunc receive(in *Inbox) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar e Event\n\t\tif err := c.ShouldBindJSON(&e); err != nil {\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"malformed event\"}) // a retry sends the same bytes\n\t\t\treturn\n\t\t}\n\t\tif !handled[e.Type] {\n\t\t\tc.JSON(http.StatusOK, gin.H{\"status\": \"ignored\"}) // 4xx here would only cause retries\n\t\t\treturn\n\t\t}\n\t\tdup, err := in.Accept(e)\n\t\tswitch {\n\t\tcase err != nil:\n\t\t\tc.Header(\"Retry-After\", \"60\")\n\t\t\tc.JSON(http.StatusServiceUnavailable, gin.H{\"error\": \"busy, retry later\"})\n\t\tcase dup:\n\t\t\tc.JSON(http.StatusOK, gin.H{\"status\": \"duplicate\"})\n\t\tdefault:\n\t\t\tc.JSON(http.StatusAccepted, gin.H{\"status\": \"queued\"})\n\t\t}\n\t}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tsecret := []byte(\"whsec-test-only-not-a-real-secret\") // test key, never a production secret\n\tclock := time.Unix(1_800_000_000, 0)\n\tin := &Inbox{seen: map[string]bool{}, queue: make(chan Event, 2)}\n\tr := gin.New()\n\tvar logged string\n\tr.Use(func(c *gin.Context) { // stands in for the access log\n\t\tc.Next()\n\t\tif e := c.Errors.Last(); e != nil {\n\t\t\tlogged = \" (log: \" + e.Error() + \")\"\n\t\t}\n\t})\n\thooks := r.Group(\"/webhooks\", verifySignature(secret, func() time.Time { return clock }))\n\thooks.POST(\"/payments\", receive(in))\n\n\tevent := func(id, typ string) string {\n\t\treturn `{\"id\":\"` + id + `\",\"type\":\"` + typ + `\",\"data\":{\"amount\":1200}}`\n\t}\n\tdeliver := func(label, signed, sent string, at time.Time) {\n\t\tts := strconv.FormatInt(at.Unix(), 10)\n\t\treq := httptest.NewRequest(\"POST\", \"/webhooks/payments\", strings.NewReader(sent))\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\treq.Header.Set(\"Webhook-Timestamp\", ts)\n\t\treq.Header.Set(\"Webhook-Signature\", \"v1=\"+hex.EncodeToString(sign(secret, ts, []byte(signed))))\n\t\tw := httptest.NewRecorder()\n\t\tlogged = \"\"\n\t\tr.ServeHTTP(w, req)\n\t\tfmt.Printf(\"%-24s %d %s%s\\n\", label, w.Code, w.Body.String(), logged)\n\t}\n\n\te1 := event(\"evt_1\", \"payment.succeeded\")\n\tdeliver(\"first delivery\", e1, e1, clock)\n\tdeliver(\"sender retry\", e1, e1, clock.Add(40*time.Second))\n\tdeliver(\"tampered body\", e1, strings.Replace(e1, \"1200\", \"9900\", 1), clock)\n\tdeliver(\"replay after 10 minutes\", e1, e1, clock.Add(-10*time.Minute))\n\te2 := event(\"evt_2\", \"customer.updated\")\n\tdeliver(\"unhandled type\", e2, e2, clock)\n\te3, e4 := event(\"evt_3\", \"payment.refunded\"), event(\"evt_4\", \"payment.succeeded\")\n\tdeliver(\"second event\", e3, e3, clock)\n\tdeliver(\"queue full\", e4, e4, clock)\n\tfmt.Println(\"evt_4 recorded as seen:\", in.seen[\"evt_4\"])\n\n\t// The worker runs after the requests here only so the queue-full case is deterministic.\n\tclose(in.queue)\n\tvar wg sync.WaitGroup\n\tvar processed []string\n\twg.Go(func() {\n\t\tfor e := range in.queue {\n\t\t\tprocessed = append(processed, e.ID)\n\t\t}\n\t})\n\twg.Wait()\n\tfmt.Println(\"worker processed:\", strings.Join(processed, \" \"))\n}","language":"go","title":"A payments endpoint and seven deliveries","walkthrough":"The first delivery is queued with 202. The sender's retry 40 seconds later has a new timestamp and a valid signature over the same event, and Inbox answers 200 duplicate without queuing it again. Changing the amount after signing breaks the MAC; replaying a genuine delivery whose timestamp is ten minutes old passes the MAC but fails the five-minute window. Both get the same 400 body, while the log line tells them apart. An event type the service does not handle is acknowledged with 200, so the sender stops offering it. With evt_3 queued the two-slot queue is full, so evt_4 gets 503 with Retry-After and is not recorded as seen, and the sender's next attempt will be accepted. The worker starts only after the requests here, purely so that the queue-full case is deterministic; in a service it runs from startup."},{"body":"verify decodes each hex signature and compares it with hmac.Equal, which does not return at the first differing byte; the security.constant-time lesson explains why == and bytes.Equal leak how much of a guess was right. Accepting any v1= entry lets the sender sign with an old and a new secret during rotation; keep both configured on your side until the old one is retired. The timestamp is inside the MAC, so an attacker cannot refresh a captured request without the secret. It is parsed strictly and compared with the injected clock, which lets tests move time without sleeping, and the five-minute tolerance applies in both directions to absorb clock skew, so keep server clocks synchronized. The signature is checked first so that a stale-timestamp log line always describes an authentic request. Every verification failure returns the same body; the specific reason goes to the log. Not every provider signs a timestamp: GitHub's X-Hub-Signature-256 covers only the body, so replay protection there rests on deduplicating the X-GitHub-Delivery ID.","title":"Compare in constant time, then check the clock"},{"body":"Senders deliver at least once. A timeout on their side or a lost response triggers a retry with the same event ID, usually with a new timestamp and signature, and Inbox turns it into 200 duplicate. Two orderings matter. Deduplicate only after verification, or forged requests can plant event IDs and make you drop the real events later. And mark an ID as seen in the same step that queues the event, only if queuing succeeded; otherwise a 503 is followed by a retry that is wrongly answered as a duplicate, and the event is lost. The tolerance window and the dedupe store work together: the window limits how long a captured request stays usable, dedupe covers replays inside it, and because sender retries can arrive hours or days later, dedupe records must outlive the sender's retry schedule. In a real service the inbox is a table with a unique key on sender and event ID, written in the same transaction as the job that will process the event, which is the inbox half of the systems.outbox-inbox lesson.","code":"// Same contract as Inbox.Accept, so the handler does not change.\nfunc (s *Store) Accept(ctx context.Context, e Event, raw []byte) (duplicate bool, err error) {\n\ttx, err := s.db.BeginTx(ctx, nil)\n\tif err != nil {\n\t\treturn false, err // the handler answers 503 and the sender retries\n\t}\n\tdefer tx.Rollback()\n\tres, err := tx.ExecContext(ctx, `INSERT INTO webhook_inbox (sender, event_id, payload)\n\t\tVALUES ($1, $2, $3) ON CONFLICT (sender, event_id) DO NOTHING`, \"payments\", e.ID, raw)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tn, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif n == 0 {\n\t\treturn true, nil // already received: the handler answers 200\n\t}\n\tif _, err := tx.ExecContext(ctx, `INSERT INTO jobs (kind, input) VALUES ('webhook', $1)`, raw); err != nil {\n\t\treturn false, err\n\t}\n\treturn false, tx.Commit() // the handler answers 202 only when this is nil\n}","language":"go","title":"Deduplicate after verification, and record only what you queued","walkthrough":"This fragment runs against PostgreSQL in your own environment. ON CONFLICT DO NOTHING makes the duplicate check and the insert one atomic statement, so two concurrent deliveries of the same event cannot both pass. Zero affected rows means a duplicate, reported as duplicate=true so the handler answers 200. The job row for the workers from the async-jobs lesson goes into the same transaction, and a nil error from Commit is the only path to 202; any error before that becomes a 503, and because the rollback also removes the inbox row, a retry from the sender is processed rather than taken for a duplicate."},{"body":"The handler verifies, deduplicates, enqueues and answers; the business work happens later in a worker. Senders time out quickly, and GitHub, for example, expects a response within 10 seconds, so processing inline turns every slow database moment into a retry of an event you may already have handled. Treat the status code as an instruction to the sender's retry logic. 2xx means do not send this again: 202 for a queued event, 200 for a duplicate, and 200 for an event type you do not handle, because a 4xx there only causes retries and, with some senders, a disabled endpoint. 4xx means retrying the same bytes cannot help: a bad or missing signature, a stale timestamp, malformed JSON in an authentic body, or a payload over the cap, which gets 413. 5xx means the failure is yours and temporary: a full queue or an unavailable database gets 503 with Retry-After, and an unexpected panic becomes a 500 through Recovery. Senders differ: many retry any non-2xx with backoff, some never retry, some ignore Retry-After, and several disable an endpoint after a run of failures. These codes are truthful under every policy; check which codes your sender treats specially, and alert on a rising 4xx rate, which usually means a rotated secret or a drifting clock.","title":"Answer in milliseconds, with a status that steers retries"},{"body":"Build test deliveries with the same sign function and a test-only secret, as main does, and never commit a real one. Cover a valid delivery, a retry, a tampered body, a tampered timestamp header, missing headers, malformed hex, a wrong secret, two signatures during rotation, timestamps exactly at the tolerance and one second beyond in both directions, a body over the cap, malformed JSON with a valid signature, an unhandled type, and a full queue followed by a successful retry. Assert that every rejected delivery leaves the inbox unchanged. Add a route-table test that fails if a webhook route is registered outside the verifying group, and remember that a webhook route has no browser session: exempt it from CSRF middleware, never from signature verification.","title":"Test with signed fixtures and a fake clock"}],"takeaway":"Read the bounded raw body once, verify an HMAC over timestamp and body with hmac.Equal, reject timestamps outside a window from an injected clock, dedupe by event ID only after verification, enqueue and answer 2xx fast, and keep 5xx for failures a retry can fix.","title":"Signed webhooks in Gin: verify the raw bytes, reject stale timestamps, dedupe event IDs, answer fast","unitID":"gin-data","wrongAnswers":["Binding removes the signature header from the request","ShouldBindJSON rejects bodies longer than the HMAC block"]},{"conceptTag":"gin.upstream-clients","designGuide":{"cautions":["A new client or Transport per request defeats connection reuse.","Forwarding upstream bodies or headers leaks internal details.","LimitReader alone truncates silently; read the limit plus one byte."],"cost":"One client constructor, an error-mapping function and a fake RoundTripper for tests; tuning pool sizes and timeouts needs load tests against the real upstream.","family":"gin","flow":["Share one client","Derive the call context","Bound the body","Map to your own errors"],"ratings":[],"strengths":["Upstream failures become stable, documented error codes.","A hung upstream costs one bounded budget, not a stuck goroutine."]},"hint":"The slow party is neither your client nor your own code.","id":"gin.upstream-clients","introduction":"Most Gin services are also HTTP clients: they call a payment provider, an inventory service or a search cluster while their own caller waits. Every such call borrows the caller's time, a pooled connection and memory for the reply. Done naively, one slow or misbehaving upstream turns into piled-up goroutines, exhausted sockets and error responses that quote another team's database errors to your users.","nuance":"504 says a server acting as a gateway got no timely answer from an upstream. 408 would blame the client for sending its request slowly, and the Go error text would leak internal hostnames.","objective":"Call an upstream HTTP API from a Gin handler through a shared, budgeted http.Client and map every failure to your own 404, 502 or 504 without leaking upstream details.","question":"A Gin handler's call to an upstream API exceeds its per-call context deadline. What should the handler return to its own client?","references":["https://pkg.go.dev/net/http#Transport","https://pkg.go.dev/net/http#NewRequestWithContext","https://pkg.go.dev/io#LimitReader","https://www.rfc-editor.org/rfc/rfc9110#section-15.6.3"],"reviewAnswer":"504 Gateway Timeout, in your own error format","reviewPrompt":"Upstream call timed out: status?","sections":[{"body":"http.Get uses http.DefaultClient, which has no overall Timeout. DefaultTransport bounds dialing and the TLS handshake but sets no ResponseHeaderTimeout, so an upstream that accepts the connection and never answers holds the handler goroutine until something cancels it, and nothing will unless the request carries a context. Building a new http.Client with a new Transport per request is the opposite mistake: every Transport owns its own connection pool, so keep-alive never helps and idle sockets pile up. io.ReadAll on the body trusts the upstream to be small. Copying the upstream status and body into c.Data turns their 500 into yours and their SQL error into your public API. The fix is four rules: one client built at startup, a per-call context derived from the request, a cap on the bytes you read, and an explicit mapping from upstream outcomes to your own responses.","title":"What goes wrong with http.Get inside a handler"},{"body":"The Transport owns connections, so it is where the phase timeouts live: dialing, the TLS handshake and the wait for response headers. Client.Timeout covers the whole exchange including the body and acts as a backstop. Construct the client in the composition root described in the config-startup lesson and inject it into the handler struct, so a test can swap the Transport without touching the handler.","code":"func newInventoryClient() *http.Client {\n\tdialer := &net.Dialer{Timeout: 2 * time.Second, KeepAlive: 30 * time.Second}\n\ttransport := &http.Transport{\n\t\tProxy:                  http.ProxyFromEnvironment,\n\t\tDialContext:            dialer.DialContext,\n\t\tForceAttemptHTTP2:      true, // a custom DialContext turns HTTP/2 off otherwise\n\t\tTLSHandshakeTimeout:    3 * time.Second,\n\t\tResponseHeaderTimeout:  2 * time.Second,\n\t\tExpectContinueTimeout:  time.Second,\n\t\tIdleConnTimeout:        90 * time.Second,\n\t\tMaxIdleConns:           100,\n\t\tMaxIdleConnsPerHost:    32, // the default of 2 churns connections under load\n\t\tMaxConnsPerHost:        64, // a hard cap: extra requests wait for a free connection\n\t\tMaxResponseHeaderBytes: 64 << 10,\n\t}\n\treturn &http.Client{\n\t\tTransport: transport,\n\t\tTimeout:   5 * time.Second, // a backstop; the per-call context is the real budget\n\t\tCheckRedirect: func(*http.Request, []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse // an API that redirects is misconfigured\n\t\t},\n\t}\n}","language":"go","title":"Build the client once, with budgets on the Transport","walkthrough":"Run this fragment in your own native environment; it dials real hosts. ForceAttemptHTTP2 matters because the Transport documentation says a custom DialContext or TLS config disables HTTP/2 unless it is set. ResponseHeaderTimeout counts from the moment the request is fully written until headers arrive; it does not cover reading the body. MaxIdleConnsPerHost defaults to http.DefaultMaxIdleConnsPerHost, which is 2, so a busy service closes and reopens connections constantly without a higher value. MaxConnsPerHost makes excess requests queue for a connection, and that queueing time still counts against each request's context. CheckRedirect returning http.ErrUseLastResponse makes Do return the 3xx response unfollowed; the SSRF lesson in the security course explains why following redirects needs its own policy."},{"body":"The program wires an Inventory client into a Gin route. Stock derives a 50 ms budget from c.Request.Context(), builds the request with http.NewRequestWithContext, sends this service's own token and reads at most 64 KiB. The upstream is a fake http.RoundTripper, the interface the real Transport implements, so the genuine http.Client code path runs without a socket. Seven SKUs exercise success, a missing item, an upstream 500 with internal headers, an oversized body, a refused connection, a hung upstream and a client that disconnected first.","code":"package main\n\nimport (\n\t\"cmp\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// fakeInventory plays the upstream API. A RoundTripper answers in-process,\n// so the real http.Client code path runs without opening a socket.\ntype fakeInventory struct{ seen []string }\n\nfunc (f *fakeInventory) RoundTrip(req *http.Request) (*http.Response, error) {\n\tif err := req.Context().Err(); err != nil {\n\t\treturn nil, err // http.Transport also fails fast on a finished context\n\t}\n\t_, deadline := req.Context().Deadline()\n\tf.seen = append(f.seen, fmt.Sprintf(\"%s %s deadline=%t auth=%q cookie=%q\",\n\t\treq.Method, req.URL.Path, deadline, req.Header.Get(\"Authorization\"), req.Header.Get(\"Cookie\")))\n\tswitch sku := strings.TrimPrefix(req.URL.Path, \"/v1/stock/\"); sku {\n\tcase \"DOWN\":\n\t\treturn nil, errors.New(\"dial tcp 192.0.2.10:443: connect: connection refused\")\n\tcase \"SLOW\":\n\t\t<-req.Context().Done() // a hung upstream: only our deadline ends the wait\n\t\treturn nil, req.Context().Err()\n\tcase \"ERR\":\n\t\treturn reply(req, 500, `pq: relation \"stock\" does not exist`, \"X-Backend-Host\", \"db-3.internal\"), nil\n\tcase \"BIG\":\n\t\treturn reply(req, 200, `{\"sku\":\"BIG\",\"notes\":\"`+strings.Repeat(\"x\", 1<<20)+`\"}`), nil\n\tcase \"NOPE\":\n\t\treturn reply(req, 404, `{\"message\":\"no such sku\"}`), nil\n\tdefault:\n\t\treturn reply(req, 200, `{\"sku\":\"`+sku+`\",\"available\":4,\"warehouse\":\"wh-eu-2\",\"cost_cents\":1250}`), nil\n\t}\n}\n\nfunc reply(req *http.Request, status int, body string, kv ...string) *http.Response {\n\th := http.Header{\"Content-Type\": {\"application/json\"}}\n\tfor i := 0; i+1 < len(kv); i += 2 {\n\t\th.Set(kv[i], kv[i+1])\n\t}\n\treturn &http.Response{StatusCode: status, Header: h, Body: io.NopCloser(strings.NewReader(body)),\n\t\tContentLength: int64(len(body)), Request: req}\n}\n\nvar errUnknownSKU = errors.New(\"inventory: unknown sku\")\n\n// Stock is the subset of the upstream document this service relies on.\ntype Stock struct {\n\tSKU       string `json:\"sku\"`\n\tAvailable int    `json:\"available\"`\n}\n\ntype Inventory struct {\n\tClient  *http.Client // shared by every request: it owns the connection pool\n\tBaseURL string\n\tToken   string        // this service's credential, never the caller's\n\tBudget  time.Duration // per-call deadline, below the route's own budget\n\tMaxBody int64\n}\n\nfunc (inv *Inventory) Stock(ctx context.Context, sku string) (Stock, error) {\n\tctx, cancel := context.WithTimeout(ctx, inv.Budget)\n\tdefer cancel()\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, inv.BaseURL+\"/v1/stock/\"+url.PathEscape(sku), nil)\n\tif err != nil {\n\t\treturn Stock{}, err\n\t}\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+inv.Token)\n\tresp, err := inv.Client.Do(req)\n\tif err != nil {\n\t\treturn Stock{}, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\tio.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10)) // drain a little so the connection can be reused\n\t\tif resp.StatusCode == http.StatusNotFound {\n\t\t\treturn Stock{}, errUnknownSKU\n\t\t}\n\t\treturn Stock{}, fmt.Errorf(\"inventory: status %d\", resp.StatusCode)\n\t}\n\tbody, err := io.ReadAll(io.LimitReader(resp.Body, inv.MaxBody+1))\n\tif err != nil {\n\t\treturn Stock{}, fmt.Errorf(\"inventory: read: %w\", err)\n\t}\n\tif int64(len(body)) > inv.MaxBody {\n\t\treturn Stock{}, fmt.Errorf(\"inventory: body over %d bytes\", inv.MaxBody)\n\t}\n\tvar s Stock\n\tif err := json.Unmarshal(body, &s); err != nil {\n\t\treturn Stock{}, fmt.Errorf(\"inventory: decode: %w\", err)\n\t}\n\treturn s, nil\n}\n\nvar logs []string // stands in for a structured logger\n\n// fail maps an upstream failure to this API's own error format.\nfunc fail(c *gin.Context, err error) {\n\tstatus, code := http.StatusBadGateway, \"inventory_unavailable\"\n\tswitch {\n\tcase errors.Is(err, errUnknownSKU):\n\t\tc.JSON(http.StatusNotFound, gin.H{\"error\": gin.H{\"code\": \"unknown_sku\"}})\n\t\treturn\n\tcase c.Request.Context().Err() != nil:\n\t\tlogs = append(logs, \"client went away: \"+err.Error())\n\t\tc.AbortWithStatus(499) // nobody reads this; it only labels logs and metrics\n\t\treturn\n\tcase errors.Is(err, context.DeadlineExceeded):\n\t\tstatus, code = http.StatusGatewayTimeout, \"inventory_timeout\"\n\t}\n\tlogs = append(logs, err.Error()) // the cause goes to logs, never to the client\n\tc.JSON(status, gin.H{\"error\": gin.H{\"code\": code}})\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tupstream := &fakeInventory{}\n\tinv := &Inventory{\n\t\tClient:  &http.Client{Transport: upstream},\n\t\tBaseURL: \"https://inventory.internal.example\",\n\t\tToken:   \"svc-test-token\",\n\t\tBudget:  50 * time.Millisecond,\n\t\tMaxBody: 64 << 10,\n\t}\n\tr := gin.New()\n\tr.GET(\"/products/:sku/stock\", func(c *gin.Context) {\n\t\ts, err := inv.Stock(c.Request.Context(), c.Param(\"sku\"))\n\t\tif err != nil {\n\t\t\tfail(c, err)\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusOK, s) // our type: warehouse and cost_cents never reach the client\n\t})\n\n\tfor _, sku := range []string{\"A-1\", \"NOPE\", \"ERR\", \"BIG\", \"DOWN\", \"SLOW\", \"GONE\"} {\n\t\treq := httptest.NewRequest(http.MethodGet, \"/products/\"+sku+\"/stock\", nil)\n\t\treq.Header.Set(\"Authorization\", \"Bearer end-user-token\")\n\t\treq.Header.Set(\"Cookie\", \"session=s3cr3t\")\n\t\tif sku == \"GONE\" {\n\t\t\tctx, cancel := context.WithCancel(req.Context())\n\t\t\tcancel() // the client disconnected before the upstream call\n\t\t\treq = req.WithContext(ctx)\n\t\t}\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tfmt.Printf(\"%s -> %d %s\\n\", sku, w.Code, cmp.Or(w.Body.String(), \"(no body)\"))\n\t\tfor _, line := range logs {\n\t\t\tfmt.Println(\"  log:\", line)\n\t\t}\n\t\tlogs = logs[:0]\n\t\tif sku == \"A-1\" {\n\t\t\tfmt.Println(\"  upstream saw:\", upstream.seen[0])\n\t\t}\n\t\tif sku == \"ERR\" {\n\t\t\tleaked := w.Header().Get(\"X-Backend-Host\") != \"\" || strings.Contains(w.Body.String(), \"pq:\")\n\t\t\tfmt.Println(\"  upstream detail leaked:\", leaked)\n\t\t}\n\t}\n}","language":"go","title":"Pass the request context, cap the body, translate the result","walkthrough":"The A-1 line shows what the upstream received: a deadline on the context, the service token, and no trace of the caller's Authorization or Cookie headers. NOPE maps the upstream 404 to the domain error errUnknownSKU and then to this API's own 404. ERR proves nothing leaks: the client sees inventory_unavailable while the status goes to the log, and X-Backend-Host and the pq: text stay behind. BIG reads 64 KiB plus one byte, sees the extra byte and refuses, instead of decoding a silently truncated document. DOWN and SLOW both fail inside Client.Do, and errors.Is(err, context.DeadlineExceeded) separates the timeout (504) from the refused connection (502). For GONE the request context is already canceled; fail records 499, the nginx convention for a client that closed the request, purely for logs and metrics."},{"body":"RFC 9110 defines 502 Bad Gateway as an invalid response from an upstream and 504 Gateway Timeout as no timely response. Use 502 for refused connections, upstream 5xx, unreadable, oversized or malformed bodies, and 504 when your per-call budget expires. errors.Is(err, context.DeadlineExceeded) also catches an expired Client.Timeout, because in the Go 1.27 source the timeout error net/http returns has an Is method that matches context.DeadlineExceeded. An upstream 404 for a SKU is a domain fact, so it becomes your 404 with your error code. An upstream 400, 401 or 403 usually means your service built a bad request or holds a wrong credential: that is your bug, so answer 502 and alert, and never pass a 401 through, or the client will think its own login failed. Never echo the upstream body, its Set-Cookie, Server or routing headers, or its status text; the problem-details lesson defines the envelope to use instead. And do not forward the caller's Authorization or Cookie: the upstream would act with the user's authority and log their credentials. Send a service credential and pass the user's identity as data when the upstream needs it.","title":"Status codes are yours: 502, 504, 404 and the client that left"},{"body":"io.LimitReader alone truncates silently, so read MaxBody+1 bytes and treat a longer result as a failure. When you do not set Accept-Encoding yourself, the Transport asks for gzip and decompresses transparently, which means the limit applies to decoded bytes, the number that protects your memory; if you set the header yourself, you must decompress and bound the result yourself, as the compression lesson in this unit does for request bodies. Always close the body, and remember that an HTTP/1.1 connection returns to the pool only when its body was read to EOF: drain a few kilobytes on error paths and let anything larger close the connection. Decode into a struct holding only the fields you use. encoding/json ignores unknown fields, so the upstream can add warehouse or cost_cents without breaking you, and those fields never reach your clients because your type does not have them. If a proxy in front of the upstream sometimes returns HTML error pages, check the Content-Type before decoding.","title":"Read the body deliberately: limits, draining and tolerant decoding"},{"body":"A fake RoundTripper records each outgoing request and returns scripted responses or errors, including one that blocks on the request context to model a hung upstream. Assert the method, the escaped path, the headers you send and the ones you must not forward, and that a deadline is present. Each row of your error mapping becomes one test case, exactly as the program's seven SKUs do. Keep one integration test against a real server, httptest.NewServer or a staging upstream, run in your own environment, for what only a real Transport shows: dial and header timeouts, TLS, HTTP/2 and connection reuse. In production, count upstream calls by outcome (ok, not_found, 5xx, timeout, too_large) next to a latency histogram per upstream, so a spike of 502s says which dependency failed and how; the metrics lesson shows how to keep those labels bounded.","title":"Test the client at the RoundTripper seam"}],"takeaway":"Build one http.Client with Transport timeouts at startup, derive each call's context from c.Request.Context(), read at most a fixed number of bytes, and translate every upstream outcome into your own 404, 502 or 504 without forwarding their bodies, their headers or your caller's credentials.","title":"Upstream calls from Gin: one shared client, the request deadline, a bounded body and your own error codes","unitID":"gin-edge","wrongAnswers":["408 Request Timeout, since the request took too long","500 Internal Server Error with the Go error text"]},{"conceptTag":"gin.retries-breakers","designGuide":{"cautions":["Retries at several layers multiply load; retry at one.","Count only transport errors and 5xx as breaker failures.","A request body must be replayable through GetBody to retry it."],"cost":"A few hundred lines of policy code or a reviewed library, per-upstream state, and metrics for attempts, budget refusals and breaker transitions; thresholds need tuning against real traffic.","family":"gin","flow":["Check idempotency","Back off with jitter","Spend the retry budget","Trip the breaker"],"ratings":[],"strengths":["Transient blips are absorbed before the client notices.","An outage gets fast 503s instead of queued, doomed attempts."]},"hint":"Ask what happens if the first attempt actually committed.","id":"gin.retries-breakers","introduction":"A retry turns a transient failure into a success and a persistent failure into extra load at the worst possible moment. Whether a retry helps depends on three questions: is it safe to send the request twice, is the failure likely to clear soon, and how much extra traffic is the fleet already sending. This lesson builds the client side of those answers behind a Gin handler, with a seeded random source and an injected clock so every wait is reproducible.","nuance":"A timeout is ambiguous: the first attempt may have succeeded and only its response was lost. Resending the same Idempotency-Key lets the upstream replay the stored result instead of charging twice; PUT and DELETE are idempotent too.","objective":"Wrap upstream calls in a retry policy that respects idempotency, Retry-After and a shared budget, and use a circuit breaker so Gin answers 503 quickly while a dependency is down.","question":"A POST to a payment upstream times out after the request was fully sent. When may the client retry it automatically?","references":["https://www.rfc-editor.org/rfc/rfc9110#section-9.2.2","https://www.rfc-editor.org/rfc/rfc9110#section-10.2.3","https://sre.google/sre-book/handling-overload/","https://martinfowler.com/bliki/CircuitBreaker.html"],"reviewAnswer":"Only if the upstream honors an Idempotency-Key you resend","reviewPrompt":"Retry a POST after a timeout?","sections":[{"body":"RFC 9110 defines GET, HEAD, OPTIONS, TRACE, PUT and DELETE as idempotent: sending one twice has the same intended effect as sending it once. POST and PATCH are not, and a timeout is ambiguous, because the first attempt may have committed and only the response was lost. Retrying such a request can create a second order or a second charge. A client may retry a POST only when the upstream honors an Idempotency-Key and the client resends the same key on every attempt; the idempotency-keys lesson builds that server side. Worth retrying: connection errors, 502, 503, 504 and 429. Not worth retrying: other 4xx, which will fail again identically, and usually 500, which is often a deterministic bug. Retry at one layer only, ideally the one closest to the failing dependency; the cache-stampede lesson in the Go course shows how retries stacked at several layers multiply load.","title":"Which requests and which failures may be retried"},{"body":"The upstream is a scripted RoundTripper, and the injected clock's Sleep only advances time, so the program runs in milliseconds and prints the same waits on every run. Jitter comes from math/rand/v2 with fixed PCG seeds. Eight client requests walk through a flaky success, a POST without and with an Idempotency-Key, upstream throttling with Retry-After, an outage that first empties the retry budget and then opens the breaker, a request rejected while the breaker is open, and the half-open probe that closes it.","code":"package main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"math/rand/v2\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// fakeClock is the injected clock: Sleep advances time instead of blocking.\ntype fakeClock struct{ now time.Time }\n\nfunc (c *fakeClock) Now() time.Time        { return c.now }\nfunc (c *fakeClock) Sleep(d time.Duration) { c.now = c.now.Add(d) }\n\n// scripted plays the upstream: each call takes the next step of the script.\ntype scripted struct {\n\tscript []string // \"200\", \"503\", \"429:2\" (status:Retry-After)\n\tcalls  int\n}\n\nfunc (s *scripted) RoundTrip(req *http.Request) (*http.Response, error) {\n\ts.calls++\n\tstep := \"200\"\n\tif len(s.script) > 0 {\n\t\tstep, s.script = s.script[0], s.script[1:]\n\t}\n\tcode, after, _ := strings.Cut(step, \":\")\n\tstatus, _ := strconv.Atoi(code)\n\th := http.Header{}\n\tif after != \"\" {\n\t\th.Set(\"Retry-After\", after)\n\t}\n\treturn &http.Response{StatusCode: status, Header: h, Body: io.NopCloser(strings.NewReader(\"{}\")), Request: req}, nil\n}\n\ntype state int\n\nconst (\n\tclosed state = iota\n\topen\n\thalfOpen\n)\n\n// Breaker opens after Threshold consecutive failures, stays open for\n// Cooldown, then lets exactly one probe through.\ntype Breaker struct {\n\tmu        sync.Mutex\n\tClock     *fakeClock\n\tThreshold int\n\tCooldown  time.Duration\n\tstate     state\n\tfailures  int\n\topenedAt  time.Time\n\tprobing   bool\n}\n\n// Allow reports whether a call may go out and, if not, when to try again.\nfunc (b *Breaker) Allow() (time.Duration, bool) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\tif b.state == open {\n\t\tif wait := b.openedAt.Add(b.Cooldown).Sub(b.Clock.Now()); wait > 0 {\n\t\t\treturn wait, false\n\t\t}\n\t\tb.state, b.probing = halfOpen, false\n\t}\n\tif b.state == halfOpen {\n\t\tif b.probing {\n\t\t\treturn time.Second, false // one probe at a time\n\t\t}\n\t\tb.probing = true\n\t}\n\treturn 0, true\n}\n\nfunc (b *Breaker) Record(ok bool) {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\tswitch {\n\tcase ok:\n\t\tb.state, b.failures, b.probing = closed, 0, false\n\tcase b.state == halfOpen:\n\t\tb.state, b.openedAt, b.probing = open, b.Clock.Now(), false\n\tdefault:\n\t\tb.failures++\n\t\tif b.failures >= b.Threshold {\n\t\t\tb.state, b.openedAt = open, b.Clock.Now()\n\t\t}\n\t}\n}\n\nfunc (b *Breaker) Open() bool {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\treturn b.state == open\n}\n\n// Budget caps retries at a fraction of traffic: every call deposits Ratio,\n// every retry spends one token, and the balance never exceeds Max.\ntype Budget struct {\n\tmu                 sync.Mutex\n\tTokens, Ratio, Max float64\n}\n\nfunc (b *Budget) Deposit() {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\tb.Tokens = min(b.Max, b.Tokens+b.Ratio)\n}\n\nfunc (b *Budget) Spend() bool {\n\tb.mu.Lock()\n\tdefer b.mu.Unlock()\n\tif b.Tokens < 1 {\n\t\treturn false\n\t}\n\tb.Tokens--\n\treturn true\n}\n\ntype OpenError struct{ RetryAfter time.Duration }\n\nfunc (e *OpenError) Error() string { return \"circuit open\" }\n\ntype Retrier struct {\n\tClient      *http.Client\n\tClock       *fakeClock\n\tRand        *rand.Rand // seeded, so the jitter below is reproducible\n\tBreaker     *Breaker\n\tBudget      *Budget\n\tMaxAttempts int\n\tBase, Cap   time.Duration\n\tMaxWait     time.Duration // total waiting allowed for one call\n\ttrace       []string\n}\n\nfunc safeToRetry(req *http.Request) bool {\n\tif req.Body != nil && req.Body != http.NoBody && req.GetBody == nil {\n\t\treturn false // the body was consumed and cannot be sent again\n\t}\n\tswitch req.Method {\n\tcase http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPut, http.MethodDelete:\n\t\treturn true\n\t}\n\treturn req.Header.Get(\"Idempotency-Key\") != \"\"\n}\n\nfunc retryableStatus(code int) bool {\n\treturn code == http.StatusTooManyRequests || code == http.StatusBadGateway ||\n\t\tcode == http.StatusServiceUnavailable || code == http.StatusGatewayTimeout\n}\n\n// retryAfter accepts delay-seconds or an HTTP-date, as RFC 9110 allows.\nfunc retryAfter(v string, now time.Time) (time.Duration, bool) {\n\tif s, err := strconv.Atoi(v); err == nil && s >= 0 {\n\t\treturn time.Duration(s) * time.Second, true\n\t}\n\tif t, err := http.ParseTime(v); err == nil {\n\t\treturn max(0, t.Sub(now)), true\n\t}\n\treturn 0, false\n}\n\n// backoff is \"full jitter\": uniform in [0, min(Cap, Base*2^(attempt-1))).\nfunc (r *Retrier) backoff(attempt int) time.Duration {\n\tceiling := min(r.Cap, r.Base<<(attempt-1))\n\treturn time.Duration(r.Rand.Int64N(int64(ceiling))).Truncate(time.Millisecond)\n}\n\nfunc (r *Retrier) Do(req *http.Request) (*http.Response, error) {\n\tr.trace = r.trace[:0]\n\tr.Budget.Deposit()\n\tdeadline := r.Clock.Now().Add(r.MaxWait)\n\tfor attempt := 1; ; attempt++ {\n\t\tif wait, ok := r.Breaker.Allow(); !ok {\n\t\t\tr.trace = append(r.trace, \"rejected by open breaker\")\n\t\t\treturn nil, &OpenError{RetryAfter: wait}\n\t\t}\n\t\tif req.GetBody != nil {\n\t\t\treq.Body, _ = req.GetBody() // a fresh copy of the body for every attempt\n\t\t}\n\t\tresp, err := r.Client.Do(req)\n\t\tr.Breaker.Record(err == nil && resp.StatusCode < 500)\n\t\tif err == nil && !retryableStatus(resp.StatusCode) {\n\t\t\tr.trace = append(r.trace, strconv.Itoa(resp.StatusCode))\n\t\t\treturn resp, nil\n\t\t}\n\t\tlabel := \"error\"\n\t\twait := r.backoff(attempt)\n\t\tif err == nil {\n\t\t\tlabel = strconv.Itoa(resp.StatusCode)\n\t\t\tif d, ok := retryAfter(resp.Header.Get(\"Retry-After\"), r.Clock.Now()); ok {\n\t\t\t\twait = d // the server named the wait; honor it instead of guessing\n\t\t\t}\n\t\t}\n\t\tstop := \"\"\n\t\tswitch {\n\t\tcase !safeToRetry(req):\n\t\t\tstop = \"not idempotent\"\n\t\tcase attempt == r.MaxAttempts:\n\t\t\tstop = \"attempts used\"\n\t\tcase r.Breaker.Open():\n\t\t\tstop = \"circuit opened\"\n\t\tcase r.Clock.Now().Add(wait).After(deadline):\n\t\t\tstop = \"deadline\"\n\t\tcase !r.Budget.Spend():\n\t\t\tstop = \"budget empty\"\n\t\t}\n\t\tif stop != \"\" {\n\t\t\tr.trace = append(r.trace, label+\" stop: \"+stop)\n\t\t\treturn resp, err\n\t\t}\n\t\tif resp != nil {\n\t\t\tio.Copy(io.Discard, resp.Body)\n\t\t\tresp.Body.Close()\n\t\t}\n\t\tr.trace = append(r.trace, label+\" wait \"+wait.String())\n\t\tr.Clock.Sleep(wait)\n\t}\n}\n\n// respond turns the outcome into this API's answer.\nfunc respond(c *gin.Context, resp *http.Response, err error) {\n\tvar open *OpenError\n\tswitch {\n\tcase errors.As(err, &open):\n\t\tsecs := int((open.RetryAfter + time.Second - 1) / time.Second)\n\t\tc.Header(\"Retry-After\", strconv.Itoa(secs))\n\t\tc.JSON(http.StatusServiceUnavailable, gin.H{\"error\": \"quotes_unavailable\"})\n\tcase err != nil || resp.StatusCode >= 500 || resp.StatusCode == http.StatusTooManyRequests:\n\t\tc.JSON(http.StatusBadGateway, gin.H{\"error\": \"quotes_failed\"})\n\tdefault:\n\t\tresp.Body.Close()\n\t\tc.JSON(resp.StatusCode, gin.H{\"ok\": true})\n\t}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tclock := &fakeClock{now: time.Date(2026, 11, 18, 9, 0, 0, 0, time.UTC)}\n\tup := &scripted{}\n\trt := &Retrier{\n\t\tClient:      &http.Client{Transport: up},\n\t\tClock:       clock,\n\t\tRand:        rand.New(rand.NewPCG(1, 2)),\n\t\tBreaker:     &Breaker{Clock: clock, Threshold: 3, Cooldown: 30 * time.Second},\n\t\tBudget:      &Budget{Tokens: 3, Ratio: 0.5, Max: 3},\n\t\tMaxAttempts: 3,\n\t\tBase:        100 * time.Millisecond,\n\t\tCap:         time.Second,\n\t\tMaxWait:     3 * time.Second,\n\t}\n\tconst upstream = \"https://quotes.internal.example/v1\"\n\tr := gin.New()\n\tr.GET(\"/quotes/:sym\", func(c *gin.Context) {\n\t\treq, _ := http.NewRequestWithContext(c.Request.Context(), http.MethodGet, upstream+\"/quotes/\"+c.Param(\"sym\"), nil)\n\t\tresp, err := rt.Do(req)\n\t\trespond(c, resp, err)\n\t})\n\tr.POST(\"/orders\", func(c *gin.Context) {\n\t\tbody, _ := io.ReadAll(io.LimitReader(c.Request.Body, 1<<20))\n\t\treq, _ := http.NewRequestWithContext(c.Request.Context(), http.MethodPost, upstream+\"/orders\", strings.NewReader(string(body)))\n\t\tif key := c.GetHeader(\"Idempotency-Key\"); key != \"\" {\n\t\t\treq.Header.Set(\"Idempotency-Key\", key) // the upstream dedupes on it\n\t\t}\n\t\tresp, err := rt.Do(req)\n\t\trespond(c, resp, err)\n\t})\n\n\tcall := func(label, method, path, key string, script ...string) {\n\t\tup.script = script\n\t\treq := httptest.NewRequest(method, path, strings.NewReader(`{\"qty\":1}`))\n\t\tif key != \"\" {\n\t\t\treq.Header.Set(\"Idempotency-Key\", key)\n\t\t}\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\textra := \"\"\n\t\tif ra := w.Header().Get(\"Retry-After\"); ra != \"\" {\n\t\t\textra = \" Retry-After=\" + ra\n\t\t}\n\t\tfmt.Printf(\"%-14s %s -> %d%s\\n\", label, strings.Join(rt.trace, \", \"), w.Code, extra)\n\t}\n\tcall(\"GET flaky\", \"GET\", \"/quotes/GO\", \"\", \"503\", \"503\", \"200\")\n\tcall(\"POST no key\", \"POST\", \"/orders\", \"\", \"503\")\n\tcall(\"POST with key\", \"POST\", \"/orders\", \"k-7f3a\", \"503\", \"201\")\n\tcall(\"GET throttled\", \"GET\", \"/quotes/GO\", \"\", \"429:2\", \"200\")\n\tcall(\"GET outage\", \"GET\", \"/quotes/GO\", \"\", \"503\", \"503\")\n\tcall(\"GET outage\", \"GET\", \"/quotes/GO\", \"\", \"503\")\n\tcall(\"GET while open\", \"GET\", \"/quotes/GO\", \"\")\n\tclock.Sleep(31 * time.Second)\n\tcall(\"GET probe\", \"GET\", \"/quotes/GO\", \"\", \"200\")\n\tfmt.Println(\"upstream calls:\", up.calls, \"for 8 client requests; breaker open:\", rt.Breaker.Open())\n}","language":"go","title":"Backoff, Retry-After, a budget and a breaker in one client","walkthrough":"Do deposits into the budget once per call, then loops. Each attempt first asks the breaker, refreshes the body through GetBody, sends, and records success or failure; only transport errors and 5xx count against the breaker, so the 429 does not. A non-retryable status returns at once. Otherwise the wait is the jittered backoff, replaced by Retry-After when the upstream sends one, and the switch names the first reason to stop: unsafe method, attempts used, breaker now open, wait past the deadline, or no budget. The first outage request spends the last whole token on one retry and then finds the budget empty; the second takes the third consecutive failure, which opens the breaker. The next request never reaches the upstream, and respond turns OpenError into 503 with Retry-After rounded up to whole seconds. After 31 simulated seconds one probe succeeds and the breaker closes. trace exists only to print attempts and is not safe for concurrent use; a real client would emit metrics instead."},{"body":"Clients that failed together and back off by the same schedule retry together, in synchronized waves that knock the recovering upstream over again. Full jitter draws each wait uniformly from zero to min(Cap, Base times 2 to the power of the attempt number minus one): the ceiling grows exponentially while individual waits spread across it, and the cap keeps the exponent from producing minute-long waits. In production every process should draw differently, which math/rand/v2's top-level functions already do because they are randomly seeded; in tests inject a *rand.Rand built from rand.NewPCG with fixed seeds, which yields the same sequence every run. Time works the same way: depend on a clock interface, give tests a fake one, and give production a sleep that also watches the request context, as in the fragment below. Retry-After, defined in RFC 9110 section 10.2.3, may hold seconds or an HTTP-date; prefer it over your own guess, but a value longer than the remaining budget means give up now and tell your own client when to return.","code":"// realClock sleeps on a timer but wakes as soon as the request is canceled.\ntype realClock struct{}\n\nfunc (realClock) Now() time.Time { return time.Now() }\n\nfunc (realClock) Sleep(ctx context.Context, d time.Duration) error {\n\tif deadline, ok := ctx.Deadline(); ok && time.Until(deadline) < d {\n\t\treturn context.DeadlineExceeded // the wait cannot finish in time: give up now\n\t}\n\tt := time.NewTimer(d)\n\tdefer t.Stop()\n\tselect {\n\tcase <-t.C:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}","language":"go","title":"Jitter spreads the herd; seeds and clocks make it testable","walkthrough":"This fragment is the production counterpart of fakeClock and runs in your own native environment. It refuses a wait that would end after the context deadline, because a retry that starts after the caller gave up is pure waste. time.NewTimer with a deferred Stop releases the timer when the request is canceled first, and the select returns ctx.Err() so the retry loop stops instead of sending another attempt for a client that has already left."},{"body":"MaxAttempts bounds one call, not the fleet. When every request fails, three attempts each triple the load on a dependency that may be failing precisely because it is overloaded. A budget ties retries to overall traffic: every call deposits Ratio tokens, every retry spends one, and the balance is capped, so over time retries add at most Ratio times the request rate. Google's SRE book describes the same idea as a per-client retry budget of about ten percent; the program uses 0.5 only so that the effect appears within eight requests. Keep one budget per upstream in each process; coordinating budgets across instances is rarely worth the complexity. Export the number of retries and of budget refusals as metrics: a sudden rise in refusals is an early, cheap signal that a dependency is degrading.","title":"A retry budget caps amplification across requests"},{"body":"Closed: calls pass and consecutive failures are counted; at the threshold the breaker opens. Open: calls fail immediately with no socket and no waiting, which protects both the upstream and your own goroutines. After the cooldown the breaker turns half-open and lets exactly one probe through; success closes it, failure reopens it for a fresh cooldown, and other callers are refused while the probe is in flight. Allow and Record take a mutex because every request touches them concurrently. While open, the handler chose not to do the work, so it answers 503 Service Unavailable with Retry-After set to the remaining cooldown, in your own error format, consistent with the timeouts lesson's convention; if the product allows, serve a stale cached value instead. Keep one breaker per upstream, or per endpoint when endpoints fail independently, never one for everything. Consecutive failures are the simplest trigger; production breakers often use a failure rate over a sliding window with a minimum request volume, so two failures in a quiet hour do not trip it.","title":"Breaker states and what the Gin handler returns while open"},{"body":"Each test row is a method, an optional Idempotency-Key, an upstream script and the expected attempts, waits, final status and breaker state; with an injected clock and seeded random source the assertions can be exact. Add a concurrency test in which many goroutines hit a half-open breaker and exactly one RoundTrip call happens. Check that every attempt resends the body: http.NewRequest sets GetBody only for *bytes.Buffer, *bytes.Reader and *strings.Reader bodies, so for any other reader GetBody is nil and safeToRetry refuses rather than sending an empty second attempt. In staging, inject faults by making a test upstream return 503 or hang, and watch the attempt counts, budget refusals and breaker transitions on your dashboards before a real outage does it for you.","title":"Test the policy as a table of scripts"}],"takeaway":"Retry only idempotent requests or those carrying an Idempotency-Key, only on transient failures, with capped full-jitter backoff, honored Retry-After and a shared retry budget, and put a per-upstream circuit breaker in front so an outage gets fast 503s with Retry-After instead of more load.","title":"Retrying upstream calls from Gin: only when safe, jittered backoff, a retry budget and a circuit breaker","unitID":"gin-edge","wrongAnswers":["Always, since a timeout means the upstream never got it","Never, because only GET requests can be retried safely"]},{"conceptTag":"gin.compression","designGuide":{"cautions":["Never compress SSE, ranges, images or already-encoded bodies.","Bound decompressed request bodies, not just the wire bytes.","A reverse proxy or CDN usually compresses better than the app."],"cost":"CPU on every compressible response, a small buffer per request, and a wrapper whose every write path must stay in sync with gin.ResponseWriter as Gin evolves.","family":"gin","flow":["Parse Accept-Encoding","Buffer the first bytes","Decide per response","Fix headers, compress"],"ratings":[],"strengths":["Text APIs typically shrink several times on slow links.","A per-route opt-out keeps BREACH-prone pages uncompressed."]},"hint":"The cache needs to know which request header changed the response.","id":"gin.compression","introduction":"JSON, CSV and HTML often shrink several times under gzip, which matters on mobile links and metered egress. A compression middleware sits between every handler and the network, so its bugs appear everywhere at once: a missing Vary header serves gzip to a client that cannot read it, a stale Content-Length truncates bodies, a compressed event stream stalls, and a page that mixes a secret with reflected input becomes a BREACH oracle.","nuance":"Vary tells caches to key the stored response by Accept-Encoding. Without it on both variants, the first stored copy is served to every client regardless of what it can decode; no-transform only forbids intermediaries from changing the body.","objective":"Write a gzip middleware for Gin that negotiates Accept-Encoding correctly and skips responses that must not be compressed, and accept gzip request bodies without a decompression-bomb hole.","question":"A gzip middleware compresses responses for clients that send Accept-Encoding: gzip. Which header stops a shared cache from serving the compressed bytes to a client that cannot decode them?","references":["https://www.rfc-editor.org/rfc/rfc9110#section-12.5.3","https://pkg.go.dev/compress/gzip","https://pkg.go.dev/net/http#MaxBytesReader","https://www.rfc-editor.org/rfc/rfc7694"],"reviewAnswer":"Vary: Accept-Encoding, on gzip and identity responses","reviewPrompt":"Gzip middleware: header to add?","sections":[{"body":"Accept-Encoding is a list of content codings with optional weights. \"gzip, br\" accepts both; \"gzip;q=0, br\" explicitly refuses gzip; \"*;q=0.5\" accepts any coding not listed. An explicit entry beats the wildcard, q=0 means not acceptable, and several Accept-Encoding header lines form one list, which is why the code joins Header.Values. RFC 9110 lets a server pick any coding when the header is absent, but clients that omit it are usually simple tools, so identity is the safe answer. The client's preference is only half the decision. The other half depends on the response: its status, its Content-Type, its size, whether a Content-Encoding is already set and whether the handler streams. None of that is known before the handler writes, so the wrapper buffers the first bytes and decides at the last possible moment.","title":"Negotiate with q-values, then decide per response"},{"body":"Compress swaps c.Writer for a gzipWriter that embeds the original gin.ResponseWriter. decide runs exactly once: when buffered bytes reach 512, on Flush or WriteHeaderNow, or after the chain returns. NoCompression lets one handler opt out, and GunzipBody accepts compressed uploads. main sends twelve requests and decodes every gzip response, so a corrupt stream would show up as an error line.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"errors\"\n\t\"fmt\"\n\t\"html\"\n\t\"io\"\n\t\"mime\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nconst minSize = 512 // below this, gzip framing and CPU cost more than they save\n\n// acceptsGzip applies q-values: an explicit gzip entry beats *, and q=0\n// means \"not acceptable\". Several Accept-Encoding lines form one list.\nfunc acceptsGzip(values []string) bool {\n\tgzipQ, anyQ := -1.0, -1.0\n\tfor part := range strings.SplitSeq(strings.Join(values, \",\"), \",\") {\n\t\tcoding, params, _ := strings.Cut(part, \";\")\n\t\tq := 1.0\n\t\tfor p := range strings.SplitSeq(params, \";\") {\n\t\t\tif v, ok := strings.CutPrefix(strings.ToLower(strings.TrimSpace(p)), \"q=\"); ok {\n\t\t\t\tif f, err := strconv.ParseFloat(v, 64); err == nil && f >= 0 && f <= 1 {\n\t\t\t\t\tq = f\n\t\t\t\t} else {\n\t\t\t\t\tq = 0\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tswitch strings.ToLower(strings.TrimSpace(coding)) {\n\t\tcase \"gzip\", \"x-gzip\":\n\t\t\tgzipQ = q\n\t\tcase \"*\":\n\t\t\tanyQ = q\n\t\t}\n\t}\n\tif gzipQ >= 0 {\n\t\treturn gzipQ > 0\n\t}\n\treturn anyQ > 0\n}\n\n// compressible is an allow-list: images, archives, video and fonts are\n// already compressed, and an event stream must leave event by event.\nfunc compressible(contentType string) bool {\n\tmt, _, err := mime.ParseMediaType(contentType)\n\tif err != nil || mt == \"text/event-stream\" {\n\t\treturn false\n\t}\n\treturn strings.HasPrefix(mt, \"text/\") || mt == \"application/json\" || mt == \"application/javascript\" ||\n\t\tmt == \"image/svg+xml\" || strings.HasSuffix(mt, \"+json\") || strings.HasSuffix(mt, \"+xml\")\n}\n\nfunc addVary(h http.Header, field string) {\n\tfor _, v := range h.Values(\"Vary\") {\n\t\tfor f := range strings.SplitSeq(v, \",\") {\n\t\t\tif strings.EqualFold(strings.TrimSpace(f), field) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\th.Add(\"Vary\", field)\n}\n\nvar gzPool = sync.Pool{New: func() any { return gzip.NewWriter(io.Discard) }}\n\n// gzipWriter buffers the first bytes so the decision can see the status,\n// the headers and whether the body is big enough to be worth compressing.\ntype gzipWriter struct {\n\tgin.ResponseWriter\n\taccepts  bool\n\tdisabled bool\n\tdecided  bool\n\tbuf      []byte\n\tgz       *gzip.Writer\n}\n\nfunc (w *gzipWriter) decide(sizeKnown bool) {\n\tif w.decided {\n\t\treturn\n\t}\n\tw.decided = true\n\th, status := w.Header(), w.Status()\n\tif status == http.StatusNotModified {\n\t\taddVary(h, \"Accept-Encoding\") // a 304 repeats the Vary of the 200 it stands for\n\t\treturn\n\t}\n\tif w.disabled || status < 200 || status == http.StatusNoContent || status == http.StatusPartialContent ||\n\t\th.Get(\"Content-Encoding\") != \"\" || !compressible(h.Get(\"Content-Type\")) {\n\t\treturn\n\t}\n\taddVary(h, \"Accept-Encoding\") // caches must key this URL by Accept-Encoding\n\tif !w.accepts || (sizeKnown && len(w.buf) < minSize) {\n\t\treturn\n\t}\n\th.Set(\"Content-Encoding\", \"gzip\")\n\th.Del(\"Content-Length\") // it described the uncompressed bytes\n\th.Del(\"Accept-Ranges\")  // ranges would now address the compressed stream\n\tif etag := h.Get(\"ETag\"); strings.HasPrefix(etag, `\"`) {\n\t\th.Set(\"ETag\", \"W/\"+etag) // different bytes, so no longer a strong validator\n\t}\n\tw.gz = gzPool.Get().(*gzip.Writer)\n\tw.gz.Reset(w.ResponseWriter)\n}\n\nfunc (w *gzipWriter) flushBuf() error {\n\tbuf := w.buf\n\tw.buf = nil\n\tif len(buf) == 0 {\n\t\treturn nil\n\t}\n\tif w.gz != nil {\n\t\t_, err := w.gz.Write(buf)\n\t\treturn err\n\t}\n\t_, err := w.ResponseWriter.Write(buf)\n\treturn err\n}\n\nfunc (w *gzipWriter) Write(p []byte) (int, error) {\n\tif !w.decided {\n\t\tw.buf = append(w.buf, p...)\n\t\tif len(w.buf) < minSize {\n\t\t\treturn len(p), nil\n\t\t}\n\t\tw.decide(false)\n\t\treturn len(p), w.flushBuf()\n\t}\n\tif w.gz != nil {\n\t\treturn w.gz.Write(p)\n\t}\n\treturn w.ResponseWriter.Write(p)\n}\n\n// Every write path must go through the wrapper, or bytes bypass gzip.\nfunc (w *gzipWriter) WriteString(s string) (int, error) { return w.Write([]byte(s)) }\n\nfunc (w *gzipWriter) Written() bool { return len(w.buf) > 0 || w.ResponseWriter.Written() }\n\nfunc (w *gzipWriter) WriteHeaderNow() {\n\tw.decide(false)\n\tw.flushBuf()\n\tw.ResponseWriter.WriteHeaderNow()\n}\n\nfunc (w *gzipWriter) Flush() {\n\tw.decide(false)\n\tw.flushBuf()\n\tif w.gz != nil {\n\t\tw.gz.Flush()\n\t}\n\tw.ResponseWriter.Flush()\n}\n\nfunc (w *gzipWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter }\n\nfunc (w *gzipWriter) finish() {\n\tw.decide(true)\n\tw.flushBuf()\n\tif w.gz != nil {\n\t\tw.gz.Close() // writes the gzip trailer\n\t\tgzPool.Put(w.gz)\n\t\tw.gz = nil\n\t}\n}\n\nfunc Compress() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tif c.Request.Method == http.MethodHead {\n\t\t\tc.Next() // no body to compress\n\t\t\treturn\n\t\t}\n\t\tw := &gzipWriter{ResponseWriter: c.Writer, accepts: acceptsGzip(c.Request.Header.Values(\"Accept-Encoding\"))}\n\t\tc.Writer = w\n\t\tc.Next()\n\t\tw.finish()\n\t\tc.Writer = w.ResponseWriter\n\t}\n}\n\n// NoCompression opts one response out: use it for pages that mix a secret\n// with reflected input, the precondition for BREACH.\nfunc NoCompression(c *gin.Context) {\n\tif w, ok := c.Writer.(*gzipWriter); ok {\n\t\tw.disabled = true\n\t}\n}\n\n// GunzipBody accepts gzip request bodies and bounds the compressed and\n// the decompressed size separately.\nfunc GunzipBody(maxWire, maxDecoded int64) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tswitch strings.ToLower(c.GetHeader(\"Content-Encoding\")) {\n\t\tcase \"\":\n\t\t\tc.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxDecoded)\n\t\t\tc.Next()\n\t\t\treturn\n\t\tcase \"gzip\":\n\t\tdefault:\n\t\t\tc.Header(\"Accept-Encoding\", \"gzip\") // RFC 7694: say what would work\n\t\t\tc.AbortWithStatusJSON(http.StatusUnsupportedMediaType, gin.H{\"error\": \"unsupported_content_encoding\"})\n\t\t\treturn\n\t\t}\n\t\tzr, err := gzip.NewReader(http.MaxBytesReader(c.Writer, c.Request.Body, maxWire))\n\t\tif err != nil {\n\t\t\tc.AbortWithStatusJSON(http.StatusBadRequest, gin.H{\"error\": \"invalid_gzip\"})\n\t\t\treturn\n\t\t}\n\t\tc.Request.Body = http.MaxBytesReader(c.Writer, zr, maxDecoded)\n\t\tc.Request.Header.Del(\"Content-Encoding\")\n\t\tc.Request.ContentLength = -1\n\t\tc.Next()\n\t}\n}\n\nfunc gzipped(b []byte) []byte {\n\tvar buf bytes.Buffer\n\tzw := gzip.NewWriter(&buf)\n\tzw.Write(b)\n\tzw.Close()\n\treturn buf.Bytes()\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\treport := []byte(\"region,orders,total\\n\" + strings.Repeat(\"eu-west,1200,98000.00\\n\", 180))\n\tr := gin.New()\n\tr.Use(Compress())\n\tr.GET(\"/report\", func(c *gin.Context) {\n\t\tc.Header(\"ETag\", `\"r1\"`)\n\t\tif strings.TrimPrefix(c.GetHeader(\"If-None-Match\"), \"W/\") == `\"r1\"` {\n\t\t\tc.Status(http.StatusNotModified)\n\t\t\treturn\n\t\t}\n\t\tc.Data(http.StatusOK, \"text/csv; charset=utf-8\", report)\n\t})\n\tr.GET(\"/small\", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{\"ok\": true}) })\n\tr.GET(\"/logo.png\", func(c *gin.Context) { c.Data(http.StatusOK, \"image/png\", make([]byte, 2048)) })\n\tr.GET(\"/events\", func(c *gin.Context) {\n\t\tc.Header(\"Content-Type\", \"text/event-stream\")\n\t\tfor i := 1; i <= 3; i++ {\n\t\t\tfmt.Fprintf(c.Writer, \"data: tick %d\\n\\n\", i)\n\t\t\tc.Writer.Flush()\n\t\t}\n\t})\n\tr.GET(\"/account\", func(c *gin.Context) {\n\t\tNoCompression(c) // the CSRF token and the reflected query share one body\n\t\tpage := `<form><input type=\"hidden\" name=\"csrf\" value=\"tok-test-9f2c\">` +\n\t\t\t\"<p>Results for \" + html.EscapeString(c.Query(\"q\")) + \"</p>\" + strings.Repeat(\"<li>row</li>\", 60) + \"</form>\"\n\t\tc.Data(http.StatusOK, \"text/html; charset=utf-8\", []byte(page))\n\t})\n\tr.POST(\"/import\", GunzipBody(64<<10, 1<<20), func(c *gin.Context) {\n\t\tdata, err := io.ReadAll(c.Request.Body)\n\t\tvar tooBig *http.MaxBytesError\n\t\tswitch {\n\t\tcase errors.As(err, &tooBig):\n\t\t\tc.JSON(http.StatusRequestEntityTooLarge, gin.H{\"error\": \"body_too_large\", \"limit\": tooBig.Limit})\n\t\tcase err != nil:\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"invalid_body\"})\n\t\tdefault:\n\t\t\tc.JSON(http.StatusOK, gin.H{\"imported\": len(data)})\n\t\t}\n\t})\n\n\tshow := func(label string, req *http.Request) {\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tbody := w.Body.Bytes()\n\t\tenc := w.Header().Get(\"Content-Encoding\")\n\t\tif enc == \"gzip\" {\n\t\t\tzr, err := gzip.NewReader(bytes.NewReader(body))\n\t\t\tif err == nil {\n\t\t\t\tbody, err = io.ReadAll(zr)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(label, \"corrupt gzip:\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\tline := fmt.Sprintf(\"%-14s %d enc=%s vary=%s\", label, w.Code, cmpOr(enc, \"-\"), cmpOr(w.Header().Get(\"Vary\"), \"-\"))\n\t\tif etag := w.Header().Get(\"ETag\"); etag != \"\" {\n\t\t\tline += \" etag=\" + etag\n\t\t}\n\t\tif strings.HasPrefix(w.Header().Get(\"Content-Type\"), \"application/json\") {\n\t\t\tline += \" \" + string(body)\n\t\t} else {\n\t\t\tline += \" body=\" + strconv.Itoa(len(body))\n\t\t}\n\t\tif enc == \"gzip\" {\n\t\t\tline += \" smaller=\" + strconv.FormatBool(w.Body.Len() < len(body))\n\t\t}\n\t\tfmt.Println(line)\n\t}\n\tget := func(path, acceptEncoding string, kv ...string) *http.Request {\n\t\treq := httptest.NewRequest(http.MethodGet, path, nil)\n\t\tif acceptEncoding != \"\" {\n\t\t\treq.Header.Set(\"Accept-Encoding\", acceptEncoding)\n\t\t}\n\t\tfor i := 0; i+1 < len(kv); i += 2 {\n\t\t\treq.Header.Set(kv[i], kv[i+1])\n\t\t}\n\t\treturn req\n\t}\n\tupload := func(encoding string, body []byte) *http.Request {\n\t\treq := httptest.NewRequest(http.MethodPost, \"/import\", bytes.NewReader(body))\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\treq.Header.Set(\"Content-Encoding\", encoding)\n\t\treturn req\n\t}\n\n\tshow(\"gzip\", get(\"/report\", \"gzip, deflate, br\"))\n\tshow(\"gzip;q=0\", get(\"/report\", \"gzip;q=0, br\"))\n\tshow(\"*;q=0.5\", get(\"/report\", \"*;q=0.5\"))\n\tshow(\"no header\", get(\"/report\", \"\"))\n\tshow(\"revalidate\", get(\"/report\", \"gzip\", \"If-None-Match\", `W/\"r1\"`))\n\tshow(\"small json\", get(\"/small\", \"gzip\"))\n\tshow(\"png\", get(\"/logo.png\", \"gzip\"))\n\tshow(\"sse\", get(\"/events\", \"gzip\"))\n\tshow(\"breach opt-out\", get(\"/account?q=reflected\", \"gzip\"))\n\trows := []byte(`[` + strings.Repeat(`{\"sku\":\"A-1\",\"qty\":3},`, 99) + `{\"sku\":\"A-1\",\"qty\":3}]`)\n\tshow(\"upload gzip\", upload(\"gzip\", gzipped(rows)))\n\tbomb := gzipped(make([]byte, 8<<20))\n\tfmt.Println(\"bomb: 8 MiB of zeros, gzip under 64 KiB:\", len(bomb) < 64<<10)\n\tshow(\"upload bomb\", upload(\"gzip\", bomb))\n\tshow(\"upload br\", upload(\"br\", []byte(\"x\")))\n}\n\nfunc cmpOr(s, fallback string) string {\n\tif s == \"\" {\n\t\treturn fallback\n\t}\n\treturn s\n}","language":"go","title":"A gzip writer around gin.ResponseWriter","walkthrough":"Overriding Write is not enough. gin.ResponseWriter also has WriteString, which io.WriteString and Gin's renderers can reach, and an embedded method would send bytes straight past gzip; WriteHeaderNow is what c.Render calls for 204 and 304 and what AbortWithStatus calls. Status works through the embedded writer because Gin's WriteHeader only records the code until the first real write. finish runs after c.Next and before Gin's engine flushes its own writer, and gz.Close writes the gzip trailer. Unwrap lets http.ResponseController reach SetWriteDeadline, while its Flush finds the wrapper's Flush first, because ResponseController checks for a Flusher before unwrapping. Writers come from a sync.Pool because each gzip.Writer carries sizeable compressor state. In the output, gzip;q=0 and the missing header get identity, *;q=0.5 gets gzip, the 304 carries Vary and no body, and the PNG, the event stream and the opted-out page pass through untouched."},{"body":"Add Vary: Accept-Encoding to every response whose encoding depends on that header, including the identity ones; otherwise a shared cache that stored the gzip variant serves it to a client that sent no Accept-Encoding. A 304 must repeat the Vary its 200 would carry. Delete Content-Length, which described the uncompressed bytes. A strong ETag names exact bytes, as the conditional-requests lesson explains, so weaken it as nginx does or compute one per coding; the handler's If-None-Match check uses the weak comparison, so W/\"r1\" still revalidates. Drop Accept-Ranges, because ranges would address the compressed stream. Skip HEAD, which has no body; 1xx, 204 and 304; 206 partial content; bodies that already have a Content-Encoding, such as precompressed assets; and every type outside the allow-list. PNG, JPEG, ZIP, video and WOFF2 are already compressed, so gzip burns CPU and can even grow them. Never compress text/event-stream: the compressor holds bytes until a block fills and proxies may buffer further, which delays the events and heartbeats the SSE lesson relies on. Below roughly half a kilobyte, gzip framing and CPU cost more than they save.","title":"Headers that must change with the body"},{"body":"DEFLATE can shrink a run of zeros by about a thousand to one: the program's 8 MiB of zeros fits in well under 64 KiB of gzip. A limit on Content-Length or on wire bytes therefore says nothing about memory. GunzipBody applies http.MaxBytesReader twice, once to the compressed stream and once to the decompressed stream; it can wrap the *gzip.Reader because that type has a Close method. When the decoded limit trips, the handler sees *http.MaxBytesError and answers 413. One v1.12.0 surprise: MaxBytesReader asks net/http to close the connection through an unexported method that only the server's own ResponseWriter has, and Gin's writer does not forward it, so passing c.Writer loses that signal; the server still discards at most 256 KiB of unread body after the handler and closes the connection when more remains. The middleware removes Content-Encoding and sets ContentLength to -1, so later binding code does not trust values that described the compressed bytes. A coding you do not support gets 415 with an Accept-Encoding response header naming what does work, as RFC 7694 describes. gzip.Reader reads concatenated members as one stream by default, and the decoded limit still holds across them. Apply the same rule wherever you decompress yourself: upstream responses when you set Accept-Encoding manually, and archives, whose zip-slip half the path-traversal lesson covers.","title":"Decompression bombs: bound the bytes after gunzip"},{"body":"BREACH needs four things: HTTP compression, a secret such as a CSRF token in the body, attacker-controlled input reflected into the same body, and an attacker who can make the victim's browser send many requests and observe the encrypted response sizes. Guesses that match the secret compress better, so the response gets shorter, and the secret is recovered byte by byte despite TLS. Defenses: turn compression off for such pages, as NoCompression does for the account page; mask the token with a fresh random pad per response so its bytes never repeat; keep secrets out of bodies that echo input; and limit cross-site request driving with SameSite cookies and the Sec-Fetch-Site checks from the CSRF lesson. When nginx, Envoy, a load balancer or a CDN sits in front of the service, let it compress: it offers brotli and zstd, caches compressed variants and keeps the CPU off your application. Compress in the app only when nothing in front can, and never in both places.","code":"# nginx in front of the Gin service: compress here, not in the app\ngzip            on;\ngzip_min_length 1024;\ngzip_proxied    any;\ngzip_vary       on;\ngzip_types      application/json text/csv image/svg+xml;\n\nlocation /events {\n    proxy_pass       http://app;\n    proxy_buffering  off;   # SSE must reach the client event by event\n    gzip             off;\n}","language":"text","title":"BREACH, and when the proxy should compress instead","walkthrough":"This nginx configuration is an illustration for your own deployment, not part of the Go program. gzip_vary on adds Vary: Accept-Encoding, gzip_proxied any keeps compressing when the request itself arrived through another proxy such as a CDN, which nginx detects from the Via header, and gzip_types is an allow-list just like compressible. The /events location turns off both proxy buffering and gzip, so Server-Sent Events leave the proxy as soon as the Gin handler flushes them. With this in place, remove Compress from the Gin engine rather than running both."}],"takeaway":"Compress only allow-listed, non-streaming bodies big enough to benefit, add Vary: Accept-Encoding and drop Content-Length when you do, bound gzip request bodies after decompression, and switch compression off for pages that mix secrets with reflected input.","title":"Gzip in Gin by hand: negotiate q-values, wrap the writer, add Vary and know what never to compress","unitID":"gin-edge","wrongAnswers":["Content-Length set to the size of the compressed body","Cache-Control: no-transform on the gzip response"]},{"conceptTag":"gin.downloads-ranges","designGuide":{"cautions":["c.File follows symlinks and lists directories; never pass user paths.","If-Range needs a strong ETag, or resumes restart from zero.","Gin's FileAttachment encodes spaces as + in filename*."],"cost":"A metadata lookup per download and a stored strong validator per file; very large files also need their own write deadline or offloading to object storage.","family":"gin","flow":["Authorize the ID","Open via os.Root","Set type, ETag and name","Hand to ServeContent"],"ratings":[],"strengths":["Resumable, parallel and conditional downloads come from the stdlib.","Filenames with quotes and non-ASCII letters encode correctly."]},"hint":"If-Range compares validators the strict way.","id":"gin.downloads-ranges","introduction":"A download endpoint looks like one line, c.File(path), and that line hides most of the behavior: byte ranges for resumed and parallel downloads, conditional requests, HEAD, the content type and the filename the browser saves. Knowing what Gin delegates to net/http and what it adds decides whether a large export resumes after a dropped connection or starts over, and whether a user-chosen filename can break the response header.","nuance":"If-Range requires the strong comparison, which a weak ETag never passes. ServeContent then ignores the Range header and sends the whole file with 200, so every resume starts again from byte zero.","objective":"Serve downloadable files from Gin with correct Range, If-Range, ETag and HEAD behavior, a Content-Disposition built by mime.FormatMediaType and file access confined to an os.Root.","question":"A client resumes with Range: bytes=1000- and If-Range: W/\"v3\", and the handler set ETag: W/\"v3\" before calling http.ServeContent. What does the client receive?","references":["https://pkg.go.dev/net/http#ServeContent","https://www.rfc-editor.org/rfc/rfc9110#section-14","https://www.rfc-editor.org/rfc/rfc6266","https://pkg.go.dev/mime#FormatMediaType"],"reviewAnswer":"Never matches, so the full file comes back with 200","reviewPrompt":"If-Range with a weak ETag?","sections":[{"body":"In Gin v1.12.0, c.File(path) is one line: http.ServeFile(c.Writer, c.Request, path). c.FileAttachment(path, name) sets Content-Disposition and then makes the same call, and c.FileFromFS temporarily rewrites c.Request.URL.Path and runs http.FileServer. ServeFile opens the path through http.Dir, which, as its documentation warns, follows symlinks out of the directory and serves dotfiles such as .git. It rejects requests whose URL path contains a .. element with 400, redirects URL paths ending in /index.html, lists directories and sets Last-Modified but no ETag. All three paths end in the same serveContent code, so Range, If-Range, If-None-Match, If-Modified-Since and HEAD work everywhere. http.ServeContent(w, r, name, modtime, content) is the level below: you pass an io.ReadSeeker and a modification time, name is used only to guess a type, and an ETag takes part only if you set the header before the call. That makes ServeContent the right tool when files are looked up by ID, opened through os.Root or an embedded file system, or need a validator you control.","title":"c.File, c.FileAttachment and http.ServeContent, read from the source"},{"body":"The handler maps an export ID to a server-chosen path and a display name, opens the file through an fs.FS, checks that it is a regular, seekable file, sets Content-Type, Content-Disposition, ETag and Cache-Control, and hands over to ServeContent. An in-memory fstest.MapFS plays the file system. main sends ten requests, then compares the header Gin's FileAttachment builds with mime.FormatMediaType, using a temporary file because FileAttachment only accepts a path.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"io/fs\"\n\t\"mime\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"strings\"\n\t\"testing/fstest\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// Export is a row from your database: the client sends only the ID.\ntype Export struct {\n\tPath     string // storage name chosen by the server, relative to the root\n\tFilename string // the name the user sees; never used to open anything\n\tETag     string // a version you already track, quoted and strong\n}\n\nvar exports = map[string]Export{\n\t\"e-42\": {Path: \"exports/e-42.csv\", Filename: `Q3 \"final\" résumé.csv`, ETag: `\"v3\"`},\n}\n\n// download serves from an fs.FS. In production that is root.FS() for an\n// os.Root opened once at startup; here it is an in-memory fstest.MapFS.\nfunc download(fsys fs.FS) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\texp, ok := exports[c.Param(\"id\")] // authorize the caller for this ID here\n\t\tif !ok {\n\t\t\tc.AbortWithStatusJSON(http.StatusNotFound, gin.H{\"error\": \"unknown_export\"})\n\t\t\treturn\n\t\t}\n\t\tf, err := fsys.Open(exp.Path)\n\t\tif err != nil {\n\t\t\tc.AbortWithStatusJSON(http.StatusNotFound, gin.H{\"error\": \"unknown_export\"})\n\t\t\treturn\n\t\t}\n\t\tdefer f.Close()\n\t\tinfo, err := f.Stat()\n\t\tcontent, seekable := f.(io.ReadSeeker)\n\t\tif err != nil || !seekable || !info.Mode().IsRegular() {\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{\"error\": \"export_unavailable\"})\n\t\t\treturn\n\t\t}\n\t\th := c.Writer.Header()\n\t\th.Set(\"Content-Type\", \"text/csv; charset=utf-8\") // explicit: no sniffing\n\t\th.Set(\"Content-Disposition\", mime.FormatMediaType(\"attachment\", map[string]string{\"filename\": exp.Filename}))\n\t\th.Set(\"ETag\", exp.ETag)\n\t\th.Set(\"Cache-Control\", \"private, no-cache\")\n\t\th.Set(\"X-Content-Type-Options\", \"nosniff\")\n\t\thttp.ServeContent(c.Writer, c.Request, \"\", info.ModTime(), content)\n\t}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tdata := \"region,orders,total\\neu-west,1200,98000.00\\nus-east,900,71000.00\\n\"\n\tfsys := fstest.MapFS{\"exports/e-42.csv\": &fstest.MapFile{\n\t\tData: []byte(data), ModTime: time.Date(2026, 11, 2, 9, 30, 0, 0, time.UTC)}}\n\n\tr := gin.New()\n\tr.Match([]string{http.MethodGet, http.MethodHead}, \"/exports/:id\", download(fsys))\n\n\tsend := func(label, method, path string, kv ...string) *httptest.ResponseRecorder {\n\t\treq := httptest.NewRequest(method, path, nil)\n\t\tfor i := 0; i+1 < len(kv); i += 2 {\n\t\t\treq.Header.Set(kv[i], kv[i+1])\n\t\t}\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\th := w.Header()\n\t\tline := fmt.Sprintf(\"%-15s %d\", label, w.Code)\n\t\tif n := h.Get(\"Content-Length\"); n != \"\" && !strings.HasPrefix(h.Get(\"Content-Type\"), \"multipart/\") {\n\t\t\tline += \" len=\" + n\n\t\t}\n\t\tif cr := h.Get(\"Content-Range\"); cr != \"\" {\n\t\t\tline += \" range=\" + cr\n\t\t}\n\t\tif mt, _, _ := mime.ParseMediaType(h.Get(\"Content-Type\")); mt == \"multipart/byteranges\" {\n\t\t\tline += \" type=\" + mt\n\t\t} else if w.Code == http.StatusPartialContent {\n\t\t\tline += fmt.Sprintf(\" body=%q\", w.Body.String())\n\t\t}\n\t\tline += \" etag=\" + cmpOr(h.Get(\"ETag\"), \"-\")\n\t\tfmt.Println(line)\n\t\treturn w\n\t}\n\n\tfirst := send(\"GET\", \"GET\", \"/exports/e-42\")\n\tfmt.Println(\"  Accept-Ranges:\", first.Header().Get(\"Accept-Ranges\"))\n\tfmt.Println(\"  Last-Modified:\", first.Header().Get(\"Last-Modified\"))\n\tfmt.Println(\"  Content-Disposition:\", first.Header().Get(\"Content-Disposition\"))\n\tsend(\"HEAD\", \"HEAD\", \"/exports/e-42\")\n\tsend(\"first 10 bytes\", \"GET\", \"/exports/e-42\", \"Range\", \"bytes=0-9\")\n\tsend(\"last 9 bytes\", \"GET\", \"/exports/e-42\", \"Range\", \"bytes=-9\")\n\tsend(\"two ranges\", \"GET\", \"/exports/e-42\", \"Range\", \"bytes=0-5,20-26\")\n\tsend(\"past the end\", \"GET\", \"/exports/e-42\", \"Range\", \"bytes=500-\")\n\tsend(\"If-Range fresh\", \"GET\", \"/exports/e-42\", \"Range\", \"bytes=20-26\", \"If-Range\", `\"v3\"`)\n\tsend(\"If-Range stale\", \"GET\", \"/exports/e-42\", \"Range\", \"bytes=20-26\", \"If-Range\", `\"v2\"`)\n\tsend(\"If-None-Match\", \"GET\", \"/exports/e-42\", \"If-None-Match\", `\"v3\"`)\n\tsend(\"unknown id\", \"GET\", \"/exports/e-7\")\n\n\t// c.FileAttachment builds the header itself; compare it on a temp file.\n\ttmp, err := os.CreateTemp(\"\", \"gf-export-*.csv\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer os.Remove(tmp.Name())\n\ttmp.WriteString(data)\n\ttmp.Close()\n\tfor _, name := range []string{`Q3 \"final\".csv`, \"résumé 2026.csv\"} {\n\t\tw := httptest.NewRecorder()\n\t\tc, _ := gin.CreateTestContext(w)\n\t\tc.Request = httptest.NewRequest(http.MethodGet, \"/download\", nil)\n\t\tc.Request.Header.Set(\"Range\", \"bytes=0-5\")\n\t\tc.FileAttachment(tmp.Name(), name)\n\t\tfmt.Printf(\"FileAttachment  %d %s\\n\", w.Code, w.Header().Get(\"Content-Disposition\"))\n\t\tfmt.Printf(\"FormatMediaType     %s\\n\", mime.FormatMediaType(\"attachment\", map[string]string{\"filename\": name}))\n\t}\n}\n\nfunc cmpOr(s, fallback string) string {\n\tif s == \"\" {\n\t\treturn fallback\n\t}\n\treturn s\n}","language":"go","title":"Serve by ID through ServeContent","walkthrough":"The full GET advertises Accept-Ranges: bytes and derives Last-Modified from the MapFile ModTime. HEAD reports the same Content-Length while ServeContent skips the body, but only because the route is registered for both methods: Gin does not send HEAD to a GET handler, it answers 404. bytes=0-9 returns 206 with Content-Range: bytes 0-9/63, and the suffix form bytes=-9 returns the last nine bytes. Two ranges produce multipart/byteranges with a random boundary, so the program prints only the media type. A range past the end gives 416 with Content-Range: bytes */63, and the ETag is gone: since Go 1.23, ServeContent's error path deletes ETag, Last-Modified, Cache-Control and Content-Encoding, unless GODEBUG=httpservecontentkeepheaders=1. If-Range with the current ETag honors the range; with a stale one the client gets the whole new file. If-None-Match yields 304. The last four lines compare the two header builders: they agree on the ASCII name, but for the non-ASCII one Gin encodes the space as + in filename* while FormatMediaType writes %20."},{"body":"A client resuming a download sends Range: bytes=N- together with If-Range carrying the ETag or Last-Modified of the copy it holds. If the file changed in between, it must receive the whole new file, not bytes of a new version spliced onto an old prefix. ServeContent compares If-Range strongly: a weak ETag such as W/\"v3\" never matches, so every resume silently restarts from zero, and a date matches only to the second. Store a strong validator with the file, a version number or a content hash computed once at write time; hashing a large file on every request is far too expensive. The Go 1.27 source adds defensive rules worth knowing: a range starting beyond the end is a 416 except for empty files, which get 200; ranges whose sizes add up to more than the file are ignored and answered with 200, which defeats overlapping-range amplification; and a header with more than 200 ranges is ignored. Never compress a ServeContent response: ranges address identity bytes, and the source comments that it omits Content-Length when you set Content-Encoding because that combination is already wrong.","title":"Range and If-Range depend on a strong validator"},{"body":"The name a user sees is display data. It contains spaces, quotes and non-ASCII letters, and when users choose it, semicolons, control characters and very long strings too. Concatenation produces headers that parse wrongly: an unescaped quote ends the parameter early and a semicolon starts a new one. mime.FormatMediaType(\"attachment\", map[string]string{\"filename\": name}) writes a bare token when it can, a quoted string with backslash escapes for ASCII with spaces or quotes, and RFC 2231 percent-encoding in filename* when the name contains non-ASCII or control characters; it returns an empty string for an invalid type or parameter name, so check for that. Gin's FileAttachment escapes quotes for ASCII names but uses url.QueryEscape otherwise, which turns spaces into +, and browsers decode filename* by RFC 8187, where + is a literal plus. RFC 6266 suggests an ASCII filename fallback next to filename* for old clients; FormatMediaType cannot emit both from one map, so add it yourself if you need it. Set an explicit Content-Type and nosniff, as the security-headers lesson recommends, so an HTML file is never rendered inline from your origin.","title":"Build Content-Disposition, never concatenate it"},{"body":"The handler takes an fs.FS, so production passes root.FS() for an os.Root opened once at startup, and every name then resolves beneath that directory; the path-traversal lesson in the security course explains what os.Root guarantees and what it does not. Look files up by ID after an authorization check, keep the storage path and display name in your database, and never let a client name a path. Large files collide with http.Server.WriteTimeout, which the server-lifecycle lesson describes as one deadline for the entire response: a 2 GB export on a slow link needs its own deadline through http.ResponseController, sized to the file, or a separate download server. For heavy traffic, redirect to a signed object-storage URL or let the proxy send the file. Test with a table of Range, If-Range, If-None-Match and HEAD requests through ServeHTTP, assert byte-exact 206 bodies and the 416 Content-Range, and feed hostile filenames with quotes, semicolons, CR LF and non-ASCII letters into the header builder.","code":"root, err := os.OpenRoot(cfg.ExportsDir)\nif err != nil {\n\treturn fmt.Errorf(\"open exports root: %w\", err)\n}\ndefer root.Close()\n\nr.Match([]string{http.MethodGet, http.MethodHead}, \"/exports/:id\", download(root.FS()))\n\n// Inside download, before ServeContent, for very large files:\n// http.NewResponseController(c.Writer).SetWriteDeadline(time.Now().Add(budgetFor(info.Size())))","language":"go","title":"Open through os.Root at startup and keep large files in budget","walkthrough":"This fragment belongs in your composition root and runs in your own native environment against a real directory. os.OpenRoot fails early if the directory is missing, which is better than a 404 on the first download. root.FS() returns an fs.FS whose files are *os.File values, so the seekability check in download passes and ServeContent can serve ranges. The commented line shows where a per-response write deadline goes for very large files; budgetFor is your own policy function."}],"takeaway":"Look files up by ID, open them through os.Root, set Content-Type, a strong ETag and a Content-Disposition from mime.FormatMediaType, then let http.ServeContent handle Range, If-Range, conditional requests and HEAD, and never compress the result.","title":"File downloads in Gin: ServeContent for ranges and validators, a safe Content-Disposition, files opened by ID","unitID":"gin-edge","wrongAnswers":["206 Partial Content starting at byte 1000","412 Precondition Failed, because the tag is weak"]},{"conceptTag":"gin.content-negotiation","designGuide":{"cautions":["Gin's NegotiateFormat ignores q-values and letter case.","c.Negotiate has no CSV branch and answers 406 with no body.","Vary: Accept fragments shared caches; prefer ?format= for links."],"cost":"A small negotiation function with its tests, one renderer per representation, and lower CDN hit ratios on URLs that vary on Accept.","family":"gin","flow":["Check ?format= override","Negotiate Accept by q","Render or answer 406","Send Vary: Accept"],"ratings":[],"strengths":["One URL serves API clients, spreadsheets and browsers.","q-aware matching returns what clients actually asked for."]},"hint":"Look at what parseAccept keeps from each element of the header.","id":"gin.content-negotiation","introduction":"Content negotiation lets one URL return the representation each client prefers: JSON for an API client, CSV for a spreadsheet import, HTML for a browser. Gin offers c.NegotiateFormat and c.Negotiate for this, and reading their v1.12.0 source shows that they implement much less of the HTTP rules than their names suggest. The gaps are easy to close, but only once you know where they are.","nuance":"parseAccept cuts every element at its first semicolon, so q=0 disappears and text/csv is the first accepted entry that matches an offer. RFC 9110 would exclude it and pick application/json through */*.","objective":"Serve JSON, CSV and HTML from one Gin handler with q-value-aware negotiation, a 406 that lists what is available, Vary: Accept for caches and a ?format= override where URLs must name the representation.","question":"A client sends Accept: text/csv;q=0, */* and a Gin v1.12.0 handler calls c.NegotiateFormat(\"application/json\", \"text/csv\"). What does it return?","references":["https://pkg.go.dev/github.com/gin-gonic/gin#Context.NegotiateFormat","https://www.rfc-editor.org/rfc/rfc9110#section-12.5.1","https://www.rfc-editor.org/rfc/rfc9110#section-12.5.5","https://owasp.org/www-community/attacks/CSV_Injection"],"reviewAnswer":"text/csv, because Gin discards q-values","reviewPrompt":"NegotiateFormat, text/csv;q=0?","sections":[{"body":"parseAccept splits the header on commas, cuts each element at its first semicolon and trims spaces, so q-values and every other parameter are thrown away. NegotiateFormat caches that list in c.Accepted, which SetAccepted can replace, returns your first offer when the header is missing or empty, and panics if you pass no offers. Otherwise it walks the accepted entries in the client's order and compares each with your offers byte by byte: a * at the same position in either string matches the rest, and an accepted entry that is a prefix of an offer also matches, so even Accept: a selects application/json. Three consequences follow. Header order beats q: \"application/json;q=0.1, text/csv\" gets JSON. q=0 counts as acceptance: \"text/csv;q=0, */*\" gets CSV, the one type the client excluded. And media types compare case-sensitively although RFC 9110 says they are case-insensitive, so \"Application/JSON\" matches nothing. c.Negotiate switches on that result for JSON, HTML, XML, YAML, TOML, ProtoBuf and BSON; any other offer, including text/csv and even text/xml, falls to the default branch, AbortWithError with 406, which commits the status with an empty body.","title":"How Gin matches Accept, read from the source"},{"body":"negotiate implements RFC 9110 section 12.5.1: each offer takes the q-value of the most specific media range that matches it, an exact type beating type/* and type/* beating */*, q=0 excludes, the highest q wins and ties go to the server's order. The program prints Gin's choice and the RFC choice side by side for seven Accept headers, then sends seven requests through the real router, including a ?format= override and a call to c.Negotiate.","code":"package main\n\nimport (\n\t\"bytes\"\n\t\"cmp\"\n\t\"encoding/csv\"\n\t\"fmt\"\n\t\"html/template\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n\t\"github.com/gin-gonic/gin/binding\"\n)\n\nconst mimeCSV = \"text/csv\"\n\n// offers is the server's preference order; ties go to the earlier entry.\nvar offers = []string{binding.MIMEJSON, mimeCSV, binding.MIMEHTML}\n\n// negotiate follows RFC 9110 section 12.5.1: each offer takes the q of the\n// most specific range that matches it, q=0 excludes, the highest q wins.\nfunc negotiate(accept string, offers []string) string {\n\tif strings.TrimSpace(accept) == \"\" {\n\t\treturn offers[0] // no Accept means any type is acceptable\n\t}\n\tbest, bestQ := \"\", 0.0\n\tfor _, offer := range offers {\n\t\tq, specificity := 0.0, -1\n\t\tfor part := range strings.SplitSeq(accept, \",\") {\n\t\t\tmediaRange, params, _ := strings.Cut(part, \";\")\n\t\t\ts := specificityOf(strings.ToLower(strings.TrimSpace(mediaRange)), offer)\n\t\t\tif s > specificity {\n\t\t\t\tspecificity, q = s, qValue(params)\n\t\t\t}\n\t\t}\n\t\tif q > bestQ {\n\t\t\tbest, bestQ = offer, q\n\t\t}\n\t}\n\treturn best\n}\n\n// specificityOf ranks a match: exact type 2, type/* 1, */* 0, no match -1.\nfunc specificityOf(mediaRange, offer string) int {\n\tswitch {\n\tcase mediaRange == offer:\n\t\treturn 2\n\tcase mediaRange == \"*/*\":\n\t\treturn 0\n\tcase strings.HasSuffix(mediaRange, \"/*\") && strings.HasPrefix(offer, mediaRange[:len(mediaRange)-1]):\n\t\treturn 1\n\t}\n\treturn -1\n}\n\nfunc qValue(params string) float64 {\n\tfor p := range strings.SplitSeq(params, \";\") {\n\t\tif v, ok := strings.CutPrefix(strings.ToLower(strings.TrimSpace(p)), \"q=\"); ok {\n\t\t\tq, err := strconv.ParseFloat(v, 64)\n\t\t\tif err != nil || q < 0 || q > 1 {\n\t\t\t\treturn 0\n\t\t\t}\n\t\t\treturn q\n\t\t}\n\t}\n\treturn 1\n}\n\ntype Row struct {\n\tRegion string `json:\"region\"`\n\tOrders int    `json:\"orders\"`\n}\n\nvar rows = []Row{{\"eu-west\", 1200}, {\"us-east\", 900}}\n\nvar formats = map[string]string{\"json\": binding.MIMEJSON, \"csv\": mimeCSV, \"html\": binding.MIMEHTML}\n\nfunc report(c *gin.Context) {\n\tformat := \"\"\n\tif f, ok := c.GetQuery(\"format\"); ok {\n\t\tif format, ok = formats[f]; !ok { // the URL names the representation\n\t\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": \"unknown_format\", \"formats\": []string{\"csv\", \"html\", \"json\"}})\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tc.Header(\"Vary\", \"Accept\") // the representation depends on Accept\n\t\tformat = negotiate(c.GetHeader(\"Accept\"), offers)\n\t}\n\tswitch format {\n\tcase binding.MIMEJSON:\n\t\tc.JSON(http.StatusOK, rows)\n\tcase mimeCSV:\n\t\tvar buf bytes.Buffer\n\t\tw := csv.NewWriter(&buf)\n\t\tw.Write([]string{\"region\", \"orders\"})\n\t\tfor _, r := range rows {\n\t\t\tw.Write([]string{r.Region, strconv.Itoa(r.Orders)})\n\t\t}\n\t\tw.Flush()\n\t\tc.Data(http.StatusOK, \"text/csv; charset=utf-8\", buf.Bytes())\n\tcase binding.MIMEHTML:\n\t\tc.HTML(http.StatusOK, \"report\", rows)\n\tdefault:\n\t\tc.JSON(http.StatusNotAcceptable, gin.H{\"error\": \"not_acceptable\", \"available\": offers})\n\t}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tr := gin.New()\n\tr.SetHTMLTemplate(template.Must(template.New(\"report\").Parse(\n\t\t`<table>{{range .}}<tr><td>{{.Region}}</td><td>{{.Orders}}</td></tr>{{end}}</table>`)))\n\tr.GET(\"/reports/sales\", report)\n\tr.GET(\"/gin-negotiate\", func(c *gin.Context) {\n\t\tc.Negotiate(http.StatusOK, gin.Negotiate{Offered: offers, Data: rows})\n\t})\n\n\tginChoice := func(accept string) string {\n\t\tc, _ := gin.CreateTestContext(httptest.NewRecorder())\n\t\tc.Request = httptest.NewRequest(http.MethodGet, \"/\", nil)\n\t\tif accept != \"\" {\n\t\t\tc.Request.Header.Set(\"Accept\", accept)\n\t\t}\n\t\treturn cmp.Or(c.NegotiateFormat(offers...), \"(none)\")\n\t}\n\tfmt.Println(\"Accept header -> gin.NegotiateFormat | RFC 9110\")\n\tfor _, accept := range []string{\n\t\t\"\",\n\t\t\"text/csv\",\n\t\t\"application/json;q=0.1, text/csv\",\n\t\t\"text/csv;q=0, */*\",\n\t\t\"Application/JSON\",\n\t\t\"image/png\",\n\t\t\"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\",\n\t} {\n\t\tfmt.Printf(\"%q -> %s | %s\\n\", accept, ginChoice(accept), cmp.Or(negotiate(accept, offers), \"(none)\"))\n\t}\n\n\tfmt.Println(\"responses:\")\n\tfor _, tc := range []struct{ path, accept string }{\n\t\t{\"/reports/sales\", \"application/json\"},\n\t\t{\"/reports/sales\", \"text/csv\"},\n\t\t{\"/reports/sales\", \"text/html\"},\n\t\t{\"/reports/sales\", \"image/png\"},\n\t\t{\"/reports/sales?format=csv\", \"application/json\"},\n\t\t{\"/reports/sales?format=xml\", \"\"},\n\t\t{\"/gin-negotiate\", \"text/csv\"},\n\t} {\n\t\treq := httptest.NewRequest(http.MethodGet, tc.path, nil)\n\t\treq.Header.Set(\"Accept\", tc.accept)\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tmediaType, _, _ := strings.Cut(w.Header().Get(\"Content-Type\"), \";\")\n\t\tfmt.Printf(\"%s Accept=%q -> %d %s vary=%s %s\\n\", tc.path, tc.accept, w.Code, cmp.Or(mediaType, \"-\"),\n\t\t\tcmp.Or(w.Header().Get(\"Vary\"), \"-\"), cmp.Or(strings.ReplaceAll(w.Body.String(), \"\\n\", `\\n`), \"(no body)\"))\n\t}\n}","language":"go","title":"One handler, three representations, two negotiators","walkthrough":"ginChoice builds a fresh test context per header because NegotiateFormat caches the parsed list in c.Accepted. The table shows the three divergences described above; the browser header agrees in both because text/html comes first and has the highest q. In report, a format query parameter is checked against an allow-list and, when present, replaces negotiation entirely, so no Vary is sent. Without it the handler sets Vary: Accept before choosing, so even the 406 carries it. CSV is rendered with encoding/csv into a buffer and sent with c.Data; HTML uses the template installed with SetHTMLTemplate. image/png gets a 406 whose JSON body lists the available types. ?format=xml is a 400, because the URL itself is wrong. The last line is c.Negotiate offered text/csv and asked for text/csv: 406 with no body and no Content-Type, since it has no CSV renderer."},{"body":"An empty result means none of your representations is acceptable. Answer 406 Not Acceptable with a body listing what is available, as RFC 9110 suggests, written in your normal error format; a client that accepts only image/png will receive something it did not ask for either way. RFC 9110 also allows ignoring Accept and sending a default instead. Choose one behavior and document it, though for API clients 406 is kinder, because silent JSON delivered to a CSV importer fails later and more confusingly. A missing Accept means anything is acceptable, so put the safest default first in the offers. Browsers send text/html first with */*;q=0.8, so a person opening the URL gets HTML. Send Vary: Accept on every negotiated response so caches know the URL has several representations; without it, a CDN that stored the CSV serves it to the next JSON client. The price is fragmentation: every distinct Accept string becomes its own cache key, and many caches do not normalize it. Each representation also needs its own ETag, as the conditional-requests lesson requires.","title":"406, defaults and Vary: Accept"},{"body":"Negotiation hides the representation in a header, and sometimes it belongs in the URL. A \"Download CSV\" link in a page or an email cannot set Accept, and a browser's address bar always sends its own. A CDN keys on the URL without needing Vary, and logs and support tickets show exactly what was requested. So many APIs accept ?format=csv, or a suffix such as /sales.csv, as an explicit override validated against an allow-list, and fall back to Accept only when it is absent. An unknown value is a 400 because the URL is wrong; 406 is about the Accept header. Never copy the query value into Content-Type, or ?format=text/html turns your JSON into a page a browser renders, which is reflected XSS. CSV has a hazard of its own: a cell beginning with =, +, - or @ is evaluated as a formula when a user opens the export in a spreadsheet, so prefix such values with a single quote when people will open the file, as OWASP's CSV injection page describes.","title":"When ?format= beats the Accept header"},{"body":"Turn the comparison table into a test against your real router. Include a missing header, curl's */*, a browser's full header, q=0 exclusions, a low q listed first, letter-case variants and a type you do not offer. Assert the status, the media type parsed from Content-Type and Vary: Accept, and decode each body with the matching reader, encoding/json for JSON and encoding/csv for CSV, so a renderer that writes the wrong format with the right header cannot pass. Add cases for ?format=: a valid override with no Vary, and 400 for an unknown value.","code":"func TestReportNegotiation(t *testing.T) {\n\tgin.SetMode(gin.TestMode)\n\tr := newRouter()\n\tcases := []struct {\n\t\taccept, wantType string\n\t\twantStatus       int\n\t}{\n\t\t{\"\", \"application/json\", 200},\n\t\t{\"*/*\", \"application/json\", 200},\n\t\t{\"text/csv\", \"text/csv\", 200},\n\t\t{\"application/json;q=0.1, text/csv\", \"text/csv\", 200},\n\t\t{\"text/csv;q=0, */*\", \"application/json\", 200},\n\t\t{\"TEXT/HTML\", \"text/html\", 200},\n\t\t{\"text/html,application/xhtml+xml,*/*;q=0.8\", \"text/html\", 200},\n\t\t{\"image/png\", \"application/json\", 406},\n\t}\n\tfor _, tc := range cases {\n\t\treq := httptest.NewRequest(http.MethodGet, \"/reports/sales\", nil)\n\t\treq.Header.Set(\"Accept\", tc.accept)\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tmt, _, _ := mime.ParseMediaType(w.Header().Get(\"Content-Type\"))\n\t\tif w.Code != tc.wantStatus || mt != tc.wantType || w.Header().Get(\"Vary\") != \"Accept\" {\n\t\t\tt.Errorf(\"Accept %q: got %d %s, Vary %q\", tc.accept, w.Code, mt, w.Header().Get(\"Vary\"))\n\t\t}\n\t}\n}","language":"go","title":"Test every Accept header you claim to support","walkthrough":"This test fragment lives in your service package and runs with go test in your own project; newRouter is the constructor from the first lesson's pattern. Each row names an Accept header and the status and media type you promise for it. mime.ParseMediaType strips the charset parameter so the comparison is about the type alone. The q-value rows and the TEXT/HTML row fail with Gin's NegotiateFormat and pass with the q-aware negotiate function, which is exactly the regression this test exists to catch."}],"takeaway":"Treat Gin's NegotiateFormat as a first-match helper that ignores q-values and letter case, negotiate by q yourself when clients depend on it, answer 406 in your own format, send Vary: Accept on every negotiated response and offer ?format= where URLs must name the representation.","title":"Content negotiation in Gin: what NegotiateFormat really matches, 406 in your format and Vary: Accept","unitID":"gin-edge","wrongAnswers":["application/json, because q=0 excludes text/csv","An empty string, so the handler should answer 406"]},{"conceptTag":"gin.api-versioning","designGuide":{"cautions":["Group middleware does not run for 404 and 405, so typos carry no Sunset.","Cross-origin clients cannot read the headers without Access-Control-Expose-Headers.","A test that fails because v1 still exists after a date is a date bomb."],"cost":"Two DTO sets and their adapters to maintain until the sunset, one middleware, and a route-table test; the real cost is the months of supporting v1 that the headers announce.","family":"gin","flow":["Map domain to DTOs","Mark v1 in middleware","Test the route table","Retire on traffic"],"ratings":[],"strengths":["A bug fix in the service reaches both versions at once.","Clients learn the end date and the replacement from standard headers.","One Retirement value keeps headers and tests in agreement."]},"hint":"One header announces a state; the other announces an end.","id":"gin.api-versioning","introduction":"A breaking change to a response shape cannot be deployed in place: some clients will keep sending yesterday's requests for months. The route-groups lesson put /v1 and /v2 groups side by side. This lesson adds what makes a second version manageable: a domain type that belongs to neither version, adapters that own each wire shape, standard headers that tell clients when v1 ends, and a route-table test that stops anyone from deleting v1 early.","nuance":"Deprecation only discourages the resource and changes no behavior; Sunset is when it may stop responding. The route-table test enforces Sunset, and traffic per route template shows when removal hurts no one.","objective":"Serve two API versions from one service through per-version DTO adapters, mark v1 with Deprecation, Sunset and successor-version links, and test that v1 routes survive until the announced date.","question":"A v1 group sends Deprecation and Sunset headers and points to /v2 with successor-version links. When is it safe to delete a v1 route registration?","references":["https://www.rfc-editor.org/rfc/rfc9745","https://www.rfc-editor.org/rfc/rfc8594","https://www.rfc-editor.org/rfc/rfc5829","https://pkg.go.dev/github.com/gin-gonic/gin#Context.FullPath"],"reviewAnswer":"After its Sunset date, once its remaining traffic is gone","reviewPrompt":"When may a v1 route be deleted?","sections":[{"body":"Suppose v1 returned a numeric id, a flat author string and a date, and the product now needs string IDs, a nested author object and a full timestamp. Changing the v1 handler breaks every mobile app that has not updated, and those apps update on their users' schedule, not yours. Copying the whole service into a v2 package fails differently: every bug fix now has to land twice, and the copies drift. The stable middle is one application service and one domain type that know nothing about JSON, plus one small adapter per version that maps the domain value to that version's DTO. A v1 handler and a v2 handler differ only in which adapter they call. Additive changes, such as a new optional field, do not need a new version; reserve /v2 for changes an old client cannot ignore. The compatibility lesson in the Go course covers the other half of the problem, when old and new binaries run during one rollout.","title":"Version the wire shape, not the service"},{"body":"The program keeps one Notes service and registers both groups on one engine. The v1 group carries a deprecated middleware built from a single Retirement value, which also feeds the route-table check, so the headers and the test can never disagree about the dates. The router receives its clock as a function, so the same engine can be asked what it does today and after the sunset.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"maps\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"slices\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// Note is the domain type. Neither version's JSON shape lives here.\ntype Note struct {\n\tID      int64\n\tAuthor  string\n\tCreated time.Time\n}\n\ntype Notes struct{ byID map[int64]Note }\n\nfunc (s *Notes) Get(id int64) (Note, bool) { n, ok := s.byID[id]; return n, ok }\n\nfunc (s *Notes) List() []Note {\n\tvar out []Note\n\tfor _, id := range slices.Sorted(maps.Keys(s.byID)) {\n\t\tout = append(out, s.byID[id])\n\t}\n\treturn out\n}\n\n// v1 wire shape: numeric id, flat author, date only, bare array lists.\ntype noteV1 struct {\n\tID      int64  `json:\"id\"`\n\tAuthor  string `json:\"author\"`\n\tCreated string `json:\"created\"`\n}\n\n// v2 wire shape: string id, nested author, RFC 3339 time, list envelope.\ntype authorV2 struct {\n\tName string `json:\"name\"`\n}\n\ntype noteV2 struct {\n\tID        string   `json:\"id\"`\n\tAuthor    authorV2 `json:\"author\"`\n\tCreatedAt string   `json:\"created_at\"`\n}\n\nfunc toV1(n Note) noteV1 {\n\treturn noteV1{ID: n.ID, Author: n.Author, Created: n.Created.Format(time.DateOnly)}\n}\n\nfunc toV2(n Note) noteV2 {\n\treturn noteV2{ID: strconv.FormatInt(n.ID, 10), Author: authorV2{Name: n.Author},\n\t\tCreatedAt: n.Created.UTC().Format(time.RFC3339)}\n}\n\n// Retirement is the v1 plan, kept in one place for headers and tests.\ntype Retirement struct {\n\tDeprecated time.Time\n\tSunset     time.Time\n\tDocsURL    string\n\tSuccessors map[string]string // \"GET /v1/...\" route -> \"GET /v2/...\" route\n}\n\nfunc deprecated(rt Retirement, now func() time.Time) gin.HandlerFunc {\n\tdeprecation := \"@\" + strconv.FormatInt(rt.Deprecated.Unix(), 10)\n\tsunset := rt.Sunset.UTC().Format(http.TimeFormat)\n\treturn func(c *gin.Context) {\n\t\th := c.Writer.Header()\n\t\th.Set(\"Deprecation\", deprecation)\n\t\th.Set(\"Sunset\", sunset)\n\t\tlinks := []string{\"<\" + rt.DocsURL + `>; rel=\"deprecation\"; type=\"text/html\"`}\n\t\tif next, ok := rt.Successors[c.Request.Method+\" \"+c.FullPath()]; ok {\n\t\t\t_, template, _ := strings.Cut(next, \" \")\n\t\t\tlinks = append(links, \"<\"+fill(template, c)+`>; rel=\"successor-version\"`)\n\t\t}\n\t\th.Set(\"Link\", strings.Join(links, \", \"))\n\t\tif !now().Before(rt.Sunset) {\n\t\t\tc.AbortWithStatusJSON(http.StatusGone, gin.H{\"error\": \"v1 has been retired; follow the successor-version link\"})\n\t\t\treturn\n\t\t}\n\t\tc.Next()\n\t}\n}\n\n// fill turns \"/v2/notes/:id\" into \"/v2/notes/7\" using this request's parameters.\nfunc fill(template string, c *gin.Context) string {\n\tparts := strings.Split(template, \"/\")\n\tfor i, p := range parts {\n\t\tif name, ok := strings.CutPrefix(p, \":\"); ok {\n\t\t\tparts[i] = url.PathEscape(c.Param(name))\n\t\t}\n\t}\n\treturn strings.Join(parts, \"/\")\n}\n\nfunc noteID(c *gin.Context) (int64, bool) {\n\tid, err := strconv.ParseInt(c.Param(\"id\"), 10, 64)\n\treturn id, err == nil && id > 0\n}\n\nfunc newRouter(notes *Notes, rt Retirement, now func() time.Time) *gin.Engine {\n\tr := gin.New()\n\tv1 := r.Group(\"/v1\", deprecated(rt, now))\n\tv1.GET(\"/notes\", func(c *gin.Context) {\n\t\tout := []noteV1{}\n\t\tfor _, n := range notes.List() {\n\t\t\tout = append(out, toV1(n))\n\t\t}\n\t\tc.JSON(http.StatusOK, out)\n\t})\n\tv1.GET(\"/notes/:id\", func(c *gin.Context) {\n\t\tid, ok := noteID(c)\n\t\tn, found := notes.Get(id)\n\t\tif !ok || !found {\n\t\t\tc.JSON(http.StatusNotFound, gin.H{\"error\": \"note not found\"})\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusOK, toV1(n))\n\t})\n\tv2 := r.Group(\"/v2\")\n\tv2.GET(\"/notes\", func(c *gin.Context) {\n\t\titems := []noteV2{}\n\t\tfor _, n := range notes.List() {\n\t\t\titems = append(items, toV2(n))\n\t\t}\n\t\tc.JSON(http.StatusOK, gin.H{\"items\": items, \"next\": nil})\n\t})\n\tv2.GET(\"/notes/:id\", func(c *gin.Context) {\n\t\tid, ok := noteID(c)\n\t\tn, found := notes.Get(id)\n\t\tif !ok || !found {\n\t\t\tc.JSON(http.StatusNotFound, gin.H{\"error\": \"note not found\"})\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusOK, toV2(n))\n\t})\n\treturn r\n}\n\n// checkRetirement is the route-table test: v1 stays until its sunset and\n// every v1 route points at a successor that is really registered.\nfunc checkRetirement(routes gin.RoutesInfo, rt Retirement, now time.Time) []string {\n\thave := map[string]bool{}\n\tfor _, r := range routes {\n\t\thave[r.Method+\" \"+r.Path] = true\n\t}\n\tvar problems []string\n\tfor _, r := range routes {\n\t\tkey := r.Method + \" \" + r.Path\n\t\tif strings.HasPrefix(r.Path, \"/v1/\") && rt.Successors[key] == \"\" {\n\t\t\tproblems = append(problems, key+\" has no successor-version mapping\")\n\t\t}\n\t}\n\tfor _, old := range slices.Sorted(maps.Keys(rt.Successors)) {\n\t\tif !have[old] && now.Before(rt.Sunset) {\n\t\t\tproblems = append(problems, old+\" removed before its sunset \"+rt.Sunset.Format(time.DateOnly))\n\t\t}\n\t\tif next := rt.Successors[old]; !have[next] {\n\t\t\tproblems = append(problems, \"successor \"+next+\" is not registered\")\n\t\t}\n\t}\n\tslices.Sort(problems)\n\treturn problems\n}\n\nfunc report(label string, problems []string) {\n\tif len(problems) == 0 {\n\t\tfmt.Println(label + \": ok\")\n\t\treturn\n\t}\n\tfor _, p := range problems {\n\t\tfmt.Println(label + \": \" + p)\n\t}\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tnotes := &Notes{byID: map[int64]Note{\n\t\t7: {ID: 7, Author: \"Platform Team\", Created: time.Date(2026, 11, 1, 9, 30, 0, 0, time.UTC)},\n\t}}\n\trt := Retirement{\n\t\tDeprecated: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC),\n\t\tSunset:     time.Date(2027, 5, 1, 0, 0, 0, 0, time.UTC),\n\t\tDocsURL:    \"https://docs.example.com/api/v1-retirement\",\n\t\tSuccessors: map[string]string{\n\t\t\t\"GET /v1/notes\":     \"GET /v2/notes\",\n\t\t\t\"GET /v1/notes/:id\": \"GET /v2/notes/:id\",\n\t\t},\n\t}\n\ttoday := time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)\n\tafterSunset := time.Date(2027, 5, 2, 0, 0, 0, 0, time.UTC)\n\tclock := today\n\tr := newRouter(notes, rt, func() time.Time { return clock })\n\n\tcall := func(path string) {\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))\n\t\tfmt.Println(clock.Format(time.DateOnly), \"GET\", path, w.Code, w.Body.String())\n\t\tfor _, k := range []string{\"Deprecation\", \"Sunset\", \"Link\"} {\n\t\t\tif v := w.Header().Get(k); v != \"\" {\n\t\t\t\tfmt.Printf(\"  %s: %s\\n\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\tcall(\"/v1/notes/7\")\n\tcall(\"/v2/notes/7\")\n\tcall(\"/v2/notes\")\n\tclock = afterSunset\n\tcall(\"/v1/notes\")\n\n\troutes := r.Routes()\n\treport(\"table today\", checkRetirement(routes, rt, today))\n\ttrimmed := slices.DeleteFunc(slices.Clone(routes), func(ri gin.RouteInfo) bool {\n\t\treturn ri.Method == http.MethodGet && ri.Path == \"/v1/notes\"\n\t})\n\treport(\"v1 list deleted today\", checkRetirement(trimmed, rt, today))\n\treport(\"v1 list deleted after sunset\", checkRetirement(trimmed, rt, afterSunset))\n}","language":"go","title":"Two adapters, one service, and a v1 group that announces its end","walkthrough":"toV1 and toV2 are the only code that knows either wire shape; handlers fetch a Note and pick an adapter. deprecated computes both header values once: Deprecation is a structured-field date, an at sign followed by Unix seconds, and Sunset is an HTTP-date from http.TimeFormat. Per request it looks up the method and c.FullPath(), the route template, in Successors and fills the v2 template with this request's parameters, so /v1/notes/7 links to /v2/notes/7. Once the injected clock passes the sunset, v1 answers 410 Gone but keeps its links. checkRetirement reads r.Routes(): a v1 route missing before the sunset is a finding, after it the removal is allowed, and every successor must be registered."},{"body":"The three headers answer different client questions. Deprecation (RFC 9745) says the resource is deprecated, or will be, as of a date; it changes nothing about how the request is processed. Sunset (RFC 8594) says when the resource is expected to stop responding, and RFC 9745 adds that the sunset should not be earlier than the deprecation date; a sunset in the past means the resource may vanish at any moment. A Link with rel=\"successor-version\" (RFC 5829) names the replacement, and rel=\"deprecation\" points people at migration notes. Set all of them in group middleware before c.Next, because a header added after the handler has started the body is silently not sent. Know what the middleware cannot reach: Gin's 404 and 405 answers run only engine-level middleware, so a mistyped v1 path carries no Sunset. Browsers hide these headers from cross-origin scripts unless the CORS middleware lists them in Access-Control-Expose-Headers. After the sunset, 410 Gone with the successor link is kinder than 404: it tells a client the path was real and where it went.","title":"What Deprecation, Sunset and successor-version promise"},{"body":"Adapters run in both directions. A v1 POST body should be decoded into a v1 request DTO and translated into the same domain command v2 uses, so validation and side effects stay in one place. Do not implement v1 by calling the v2 handler and rewriting its JSON: you pay two encodings, and v1 quietly inherits every later v2 change, including ones its clients must not see. Watch for semantic changes that no type shows: if v2 reports durations in milliseconds and v1 in seconds, the conversion belongs in toV1 and in a test. A golden test per adapter, with one captured v1 response checked in as a fixture, catches accidental changes to the old shape when someone edits the domain type. Path versioning, as here, is the easiest scheme to route, cache and label in metrics; with header or media-type versioning, every cache key, log query and dashboard has to learn the header too.","title":"Keep version differences inside the adapters"},{"body":"checkRetirement takes the time as a parameter. Its own unit tests pin dates on both sides of the sunset, as the program does, so their outcome never changes. The guard on the real router passes time.Now(): until the announced date, deleting a v1 route fails CI, and from the sunset on the same test permits the deletion without anyone editing it. The opposite rule, failing the build because v1 still exists after the sunset, is a date bomb that breaks an unrelated pull request on a calendar day. Track the clean-up with traffic instead: count requests by c.FullPath() as the metrics lesson does, and remove the v1 group when its remaining callers are clients you have contacted, not merely when the date passes.","code":"func TestV1RoutesSurviveUntilSunset(t *testing.T) {\n\tgin.SetMode(gin.TestMode)\n\tr := newRouter(seedNotes(), retirement, time.Now)\n\tfor _, problem := range checkRetirement(r.Routes(), retirement, time.Now()) {\n\t\tt.Error(problem)\n\t}\n}\n\nfunc TestCheckRetirementAroundSunset(t *testing.T) {\n\tgin.SetMode(gin.TestMode)\n\tr := newRouter(seedNotes(), retirement, time.Now)\n\troutes := slices.DeleteFunc(r.Routes(), func(ri gin.RouteInfo) bool {\n\t\treturn ri.Method == http.MethodGet && ri.Path == \"/v1/notes\"\n\t})\n\tif got := checkRetirement(routes, retirement, retirement.Sunset.Add(-time.Hour)); len(got) != 1 {\n\t\tt.Fatalf(\"before sunset: got %q, want one removal finding\", got)\n\t}\n\tif got := checkRetirement(routes, retirement, retirement.Sunset); len(got) != 0 {\n\t\tt.Fatalf(\"at sunset: got %q, want none\", got)\n\t}\n}","language":"go","title":"A route-table test that cannot become a date bomb","walkthrough":"This fragment belongs in a _test.go file beside newRouter; retirement and seedNotes are the package's own values. The first test guards the real router with the real clock, so it relaxes by itself at the sunset. The second pins both sides of the boundary: an hour before the sunset the deleted list route is exactly one finding, and at the sunset instant, where Before is false, there are none. r.Routes() builds a fresh slice on every call, so DeleteFunc cannot change the engine."}],"takeaway":"Keep the domain version-free and give each version an adapter; put the retirement dates in one value that drives the Deprecation, Sunset and successor-version headers and a route-table test that receives its clock.","title":"API versions in Gin: one service under /v1 and /v2, an adapter per version, and a v1 that announces its sunset","unitID":"gin-edge","wrongAnswers":["Once the Deprecation date passes, since it marks the end","As soon as v2 ships, because clients can follow the link"]},{"conceptTag":"gin.contract-drift","designGuide":{"cautions":["Catch-all routes have no faithful OpenAPI template.","Only exercised status codes are compared; 4XX and default accept anything in range."],"cost":"About a hundred lines of test helpers and one recording middleware; it checks paths, methods and codes, not body schemas, which need a separate validator.","family":"gin","flow":["Parse spec operations","Convert route templates","Record observed codes","Report sorted findings"],"ratings":[],"strengths":["Undocumented routes and dead operations fail CI the day they appear.","Status checks reuse the API test table instead of new fixtures."]},"hint":"Compare /v2/notes/7 with the keys of the paths object.","id":"gin.contract-drift","introduction":"An OpenAPI document is a promise that clients, generated SDKs and gateway configurations build on, while the router is what actually answers. Nothing connects the two unless you write the check: a handler added on Friday never reaches the document, an operation deleted from code lingers in the SDK, and a handler that starts returning 422 contradicts a spec that says 400. A small test that reads both sides and prints sorted differences keeps them together.","nuance":"c.FullPath() returns the template, such as /v2/notes/:id, which maps to /v2/notes/{id}; raw paths would give one key per ID. It is empty for unmatched requests, so the middleware skips NoRoute answers.","objective":"Write a test that converts engine.Routes() to OpenAPI path templates, reports routes and operations that exist on only one side, and checks recorded status codes against declared responses.","question":"A drift test records the status of each test call and compares it with the OpenAPI responses. Why key the records by c.FullPath() instead of c.Request.URL.Path?","references":["https://github.com/OAI/OpenAPI-Specification","https://pkg.go.dev/github.com/gin-gonic/gin#Engine.Routes","https://pkg.go.dev/github.com/gin-gonic/gin#Context.FullPath","https://pkg.go.dev/embed"],"reviewAnswer":"It is the route template that matches a spec path key","reviewPrompt":"Why record FullPath, not URL path?","sections":[{"body":"Drift comes in three shapes, and each hurts a different reader. A route missing from the document is invisible to client generators and API gateways that validate requests against the spec, so the new endpoint works in curl and fails behind the gateway. An operation in the document without a route ships as a method in every generated SDK that returns 404 at runtime. A status code the handler sends but the document does not declare breaks clients that switch on declared responses, and generated clients often treat an undeclared code as a decoding error. None of these fail a build by themselves. It does not matter whether the document is written by hand or generated from annotations: annotations drift from handler code in exactly the same ways, because they are comments that nothing executes. The cure is a test that reads both sides.","title":"How a document and a router drift apart"},{"body":"The program parses a small OpenAPI 3.1 document, builds a router that disagrees with it in three ways, sends the calls an API test table would send, and prints each finding in sorted order. The document is a string constant only so the example fits in one file; the last section embeds the real file.","code":"package main\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"maps\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"slices\"\n\t\"strconv\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// In the service this is //go:embed openapi.json; a constant keeps the example in one file.\nconst openAPI = `{\n  \"openapi\": \"3.1.0\",\n  \"info\": {\"title\": \"notes\", \"version\": \"2.3.0\"},\n  \"paths\": {\n    \"/v2/notes\": {\n      \"get\": {\"responses\": {\"200\": {\"description\": \"a page of notes\"}}},\n      \"post\": {\"responses\": {\"201\": {\"description\": \"created\"}, \"400\": {\"description\": \"invalid note\"}}}\n    },\n    \"/v2/notes/{id}\": {\n      \"parameters\": [{\"name\": \"id\", \"in\": \"path\", \"required\": true, \"schema\": {\"type\": \"string\"}}],\n      \"get\": {\"responses\": {\"200\": {\"description\": \"the note\"}, \"4XX\": {\"description\": \"client error\"}}},\n      \"delete\": {\"responses\": {\"204\": {\"description\": \"deleted\"}}}\n    },\n    \"/v2/files/{path}\": {\n      \"get\": {\"responses\": {\"200\": {\"description\": \"file bytes\"}}}\n    }\n  }\n}`\n\nvar httpMethods = []string{\"get\", \"put\", \"post\", \"delete\", \"options\", \"head\", \"patch\", \"trace\"}\n\n// operations maps \"METHOD /template\" to the declared response codes.\nfunc operations(doc []byte) (map[string][]string, error) {\n\tvar spec struct {\n\t\tPaths map[string]map[string]json.RawMessage `json:\"paths\"`\n\t}\n\tif err := json.Unmarshal(doc, &spec); err != nil {\n\t\treturn nil, err\n\t}\n\tops := map[string][]string{}\n\tfor path, item := range spec.Paths {\n\t\tfor _, m := range httpMethods {\n\t\t\traw, ok := item[m]\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tvar op struct {\n\t\t\t\tResponses map[string]json.RawMessage `json:\"responses\"`\n\t\t\t}\n\t\t\tif err := json.Unmarshal(raw, &op); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"%s %s: %w\", m, path, err)\n\t\t\t}\n\t\t\tops[strings.ToUpper(m)+\" \"+path] = slices.Sorted(maps.Keys(op.Responses))\n\t\t}\n\t}\n\treturn ops, nil\n}\n\n// template converts Gin's /notes/:id and /files/*path to /notes/{id} and /files/{path}.\nfunc template(ginPath string) (string, bool) {\n\tparts := strings.Split(ginPath, \"/\")\n\tcatchAll := false\n\tfor i, p := range parts {\n\t\tswitch {\n\t\tcase strings.HasPrefix(p, \":\"):\n\t\t\tparts[i] = \"{\" + p[1:] + \"}\"\n\t\tcase strings.HasPrefix(p, \"*\"):\n\t\t\tparts[i] = \"{\" + p[1:] + \"}\"\n\t\t\tcatchAll = true\n\t\t}\n\t}\n\treturn strings.Join(parts, \"/\"), catchAll\n}\n\nfunc declared(codes []string, status int) bool {\n\ts := strconv.Itoa(status)\n\treturn slices.Contains(codes, s) || slices.Contains(codes, s[:1]+\"XX\") || slices.Contains(codes, \"default\")\n}\n\n// observed records which status each route template actually answered with.\ntype observed struct {\n\tmu   sync.Mutex\n\tseen map[string]map[int]bool\n}\n\nfunc (o *observed) middleware(c *gin.Context) {\n\tc.Next()\n\tif c.FullPath() == \"\" {\n\t\treturn // unmatched requests are not operations\n\t}\n\tt, _ := template(c.FullPath())\n\tkey := c.Request.Method + \" \" + t\n\to.mu.Lock()\n\tdefer o.mu.Unlock()\n\tif o.seen[key] == nil {\n\t\to.seen[key] = map[int]bool{}\n\t}\n\to.seen[key][c.Writer.Status()] = true\n}\n\nfunc drift(routes gin.RoutesInfo, ops map[string][]string, seen map[string]map[int]bool, internal map[string]bool) []string {\n\tvar out []string\n\trouted := map[string]bool{}\n\tfor _, r := range routes {\n\t\tt, catchAll := template(r.Path)\n\t\tkey := r.Method + \" \" + t\n\t\trouted[key] = true\n\t\tif internal[r.Method+\" \"+r.Path] {\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := ops[key]; !ok {\n\t\t\tout = append(out, \"route missing from spec: \"+key)\n\t\t}\n\t\tif catchAll {\n\t\t\tout = append(out, \"warning: \"+key+\" is a Gin catch-all; OpenAPI {param} matches one segment\")\n\t\t}\n\t}\n\tfor key, codes := range ops {\n\t\tif !routed[key] {\n\t\t\tout = append(out, \"spec operation without route: \"+key)\n\t\t}\n\t\tfor status := range seen[key] {\n\t\t\tif !declared(codes, status) {\n\t\t\t\tout = append(out, fmt.Sprintf(\"undeclared status: %s answered %d, spec declares %s\", key, status, strings.Join(codes, \" \")))\n\t\t\t}\n\t\t}\n\t}\n\tslices.Sort(out)\n\treturn out\n}\n\nfunc newRouter(obs *observed) *gin.Engine {\n\tr := gin.New()\n\tr.Use(obs.middleware)\n\tr.GET(\"/healthz\", func(c *gin.Context) { c.String(http.StatusOK, \"ok\") })\n\tv2 := r.Group(\"/v2\")\n\tv2.GET(\"/notes\", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{\"items\": []string{}}) })\n\tv2.POST(\"/notes\", func(c *gin.Context) {\n\t\tvar in struct {\n\t\t\tTitle string `json:\"title\" binding:\"required\"`\n\t\t}\n\t\tif err := c.ShouldBindJSON(&in); err != nil {\n\t\t\tc.JSON(http.StatusUnprocessableEntity, gin.H{\"error\": \"title is required\"})\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusCreated, gin.H{\"id\": \"8\", \"title\": in.Title})\n\t})\n\tv2.GET(\"/notes/:id\", func(c *gin.Context) {\n\t\tif c.Param(\"id\") != \"7\" {\n\t\t\tc.JSON(http.StatusNotFound, gin.H{\"error\": \"note not found\"})\n\t\t\treturn\n\t\t}\n\t\tc.JSON(http.StatusOK, gin.H{\"id\": \"7\"})\n\t})\n\tv2.PATCH(\"/notes/:id\", func(c *gin.Context) { c.Status(http.StatusNoContent) })\n\tv2.GET(\"/files/*path\", func(c *gin.Context) { c.String(http.StatusOK, \"file %s\", c.Param(\"path\")) })\n\treturn r\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tops, err := operations([]byte(openAPI))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tobs := &observed{seen: map[string]map[int]bool{}}\n\tr := newRouter(obs)\n\tcalls := []struct{ method, path, body string }{\n\t\t{\"GET\", \"/v2/notes\", \"\"},\n\t\t{\"POST\", \"/v2/notes\", `{\"title\":\"retro\"}`},\n\t\t{\"POST\", \"/v2/notes\", `{}`},\n\t\t{\"GET\", \"/v2/notes/7\", \"\"},\n\t\t{\"GET\", \"/v2/notes/99\", \"\"},\n\t\t{\"GET\", \"/v2/files/a/b.txt\", \"\"},\n\t\t{\"GET\", \"/v2/typo\", \"\"},\n\t}\n\tfor _, tc := range calls {\n\t\treq := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))\n\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\t\tw := httptest.NewRecorder()\n\t\tr.ServeHTTP(w, req)\n\t\tfmt.Println(tc.method, tc.path, w.Code)\n\t}\n\tproblems := drift(r.Routes(), ops, obs.seen, map[string]bool{\"GET /healthz\": true})\n\tfor _, p := range problems {\n\t\tfmt.Println(p)\n\t}\n\tfmt.Printf(\"%d operations in spec, %d findings\\n\", len(ops), len(problems))\n}","language":"go","title":"Diff the route table against the document","walkthrough":"operations decodes paths into raw path items and reads only the eight HTTP method keys, because a path item can also hold keys such as parameters and summary. template rewrites each Gin segment: :id becomes {id}, *path becomes {path}, and the catch-all is reported. The observed middleware runs after c.Next, keys each response by method and converted c.FullPath(), and skips requests whose FullPath is empty because they matched no route. drift walks the routes against the operations, then each operation's observed statuses against its declared codes, accepting an exact code, a range such as 4XX or default. Map iteration order never reaches stdout, because only the sorted findings are printed."},{"body":"A Gin :param matches one path segment, which is exactly what an OpenAPI {param} means, so the conversion is mechanical, but the names must match: a document that says /notes/{noteId} for the route /notes/:id produces two findings, and that is correct, because generated clients use the parameter name. A catch-all is different. Gin's *path matches several segments and c.Param returns them with a leading slash, while an OpenAPI path parameter value cannot contain an unescaped slash, so no template describes the route faithfully. Either redesign it, for example as a query parameter, or keep it as a reviewed warning, as the program does. Watch the edges as well: OpenAPI method keys are lowercase, a servers URL such as /api is a prefix the router may or may not include, and the redirects and 405 answers Gin generates are not operations. Gin registers no implicit HEAD or OPTIONS routes, so engine.Routes() holds exactly what your code registered and nothing more.","title":"Translate Gin paths into OpenAPI templates"},{"body":"Matching routes compares structure; status codes need behavior. The recording middleware observes what the handlers really send, and the natural source of calls is the table the API-tests lesson already runs through the real router, so each success and error case contributes its status for free. The check can only judge codes the table exercises: a 409 that no case triggers is never compared, which is one more reason to give every error kind a row. Use ranges such as 4XX and the default response deliberately, because each one accepts codes nobody reviewed. Requests that match no route have an empty FullPath and Gin's NoRoute answers them, so they are skipped rather than reported against an operation. Checking response bodies against the declared schemas is the next step and needs a JSON Schema validator; the problem-details lesson fixes the error body shape, which keeps that check small.","title":"Declared codes against observed codes"},{"body":"In the service, embed the document so the binary and the test read the same bytes, and serve those bytes at /openapi.json if clients fetch the spec at runtime. Keep the allow-list of undocumented internal routes in the test file, where every exemption is visible in review. Because the findings are sorted, a CI failure is a stable list that diffs cleanly between runs instead of a different order every time.","code":"// spec.go\npackage httpapi\n\nimport _ \"embed\"\n\n//go:embed openapi.json\nvar openAPIDoc []byte\n\n// contract_test.go\nfunc TestContractDrift(t *testing.T) {\n\tgin.SetMode(gin.TestMode)\n\tops, err := operations(openAPIDoc)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tobs := &observed{seen: map[string]map[int]bool{}}\n\tr := newRouter(obs)\n\tfor _, tc := range apiCases { // the table the API tests already use\n\t\tr.ServeHTTP(httptest.NewRecorder(), tc.request())\n\t}\n\tinternal := map[string]bool{\"GET /healthz\": true, \"GET /openapi.json\": true}\n\tfor _, finding := range drift(r.Routes(), ops, obs.seen, internal) {\n\t\tt.Error(finding)\n\t}\n}","language":"go","title":"Run it as a test against the embedded document","walkthrough":"This fragment spans two files of the package. spec.go embeds openapi.json into the binary; go:embed patterns are relative to the package directory and cannot contain .., so the document lives beside the package or in a small package of its own that exports the bytes. The test replays the shared case table through a router built with the recording middleware, then reports one error per finding. internal is the reviewed allow-list, including the route that serves the document itself."}],"takeaway":"Treat the OpenAPI document as test input: convert engine.Routes() to templates, fail on routes or operations present on one side only, compare observed status codes with declared responses, and print findings sorted.","title":"Keep the OpenAPI document and the Gin router honest: diff routes, operations and status codes in a test","unitID":"gin-edge","wrongAnswers":["URL.Path is empty once Gin has matched a route","FullPath includes the query string the spec declares"]},{"conceptTag":"gin.admin-listener","designGuide":{"cautions":["A NoRoute fallback to DefaultServeMux leaks pprof with a 404 status.","pprof.Index only works under the exact /debug/pprof/ prefix.","Secrets passed as flags appear in cmdline and expvar output."],"cost":"A second engine, http.Server and listener with their own budgets and shutdown, plus network policy to keep the port private; profiling itself costs CPU while a profile runs.","family":"gin","flow":["Build an admin engine","Guard network and token","Bind an internal address","Test public 404 bodies"],"ratings":[],"strengths":["Profiles are available during an incident without a redeploy.","The public router cannot leak diagnostics by construction."]},"hint":"Look at which mux the package's init function writes to.","id":"gin.admin-listener","introduction":"A CPU profile or a goroutine dump from a live process can end an incident in minutes, so production services should be able to produce them. The same endpoints in the wrong hands publish the command line, internal function names and memory statistics, and let anyone start a 30-second CPU profile on demand. The safe arrangement is structural: a second Gin engine that serves only diagnostics, hosted by its own http.Server on an address the internet cannot reach.","nuance":"Its init calls http.HandleFunc on http.DefaultServeMux, however you import it. Gin never consults that mux, so exposure depends on what serves it: a nil handler, a NoRoute fallback or a second server.","objective":"Mount net/http/pprof and expvar on an admin-only Gin engine behind a network and token guard, and prove with httptest that the public engine does not serve them.","question":"A Gin service imports net/http/pprof. Which statement about the pprof handlers is true?","references":["https://pkg.go.dev/net/http/pprof","https://pkg.go.dev/expvar","https://pkg.go.dev/github.com/gin-gonic/gin#WrapH","https://go.dev/doc/diagnostics"],"reviewAnswer":"Registers /debug/pprof/ handlers on DefaultServeMux","reviewPrompt":"What does importing pprof do?","sections":[{"body":"The package's init function registers five handlers on http.DefaultServeMux: Index for /debug/pprof/ and the named profiles beneath it, Cmdline, Profile, Symbol and Trace, each with a GET method pattern since Go 1.22. expvar's init does the same for GET /debug/vars and publishes two variables, the command line and runtime memory statistics. The registration happens when the package is linked into the binary, whether you import it with a blank identifier or by name to call pprof.Index, and whether the import is in your code or in a dependency. Each endpoint leaks something: cmdline shows every flag, including any secret passed as one; goroutine?debug=2 prints every stack; profile and trace run the CPU profiler or the execution tracer, with their overhead, for as many seconds as the caller asks. A Gin engine never consults the default mux, so it is safe only as long as nothing else serves that mux.","title":"What importing net/http/pprof does to the process"},{"body":"The program builds both engines and drives them only with httptest recorders, so no port is opened. It first asks the default mux which pattern would serve the debug paths, then shows the public engine's answers, a leaky variant, and the admin engine behind its guard.","code":"package main\n\nimport (\n\t\"crypto/subtle\"\n\t\"encoding/json\"\n\t\"expvar\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/http/pprof\"\n\t\"net/netip\"\n\t\"slices\"\n\t\"strings\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\nvar notesServed = expvar.NewInt(\"notes_served\")\n\n// newPublic is the internet-facing engine. It never touches http.DefaultServeMux.\nfunc newPublic() *gin.Engine {\n\tr := gin.New()\n\tr.GET(\"/notes\", func(c *gin.Context) {\n\t\tnotesServed.Add(1)\n\t\tc.JSON(http.StatusOK, gin.H{\"items\": []string{}})\n\t})\n\treturn r\n}\n\n// adminOnly admits a caller only from an allowed network AND with the admin token.\nfunc adminOnly(allowed []netip.Prefix, token string) gin.HandlerFunc {\n\twant := []byte(\"Bearer \" + token)\n\treturn func(c *gin.Context) {\n\t\taddr, err := netip.ParseAddr(c.RemoteIP())\n\t\tif err != nil || !slices.ContainsFunc(allowed, func(p netip.Prefix) bool { return p.Contains(addr.Unmap()) }) {\n\t\t\tc.AbortWithStatus(http.StatusForbidden)\n\t\t\treturn\n\t\t}\n\t\tif subtle.ConstantTimeCompare([]byte(c.GetHeader(\"Authorization\")), want) != 1 {\n\t\t\tc.AbortWithStatus(http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tc.Next()\n\t}\n}\n\n// newAdmin is served on a separate, internal-only listener.\nfunc newAdmin(allowed []netip.Prefix, token string) *gin.Engine {\n\ta := gin.New()\n\ta.Use(adminOnly(allowed, token))\n\tpp := a.Group(\"/debug/pprof\")\n\tpp.GET(\"/\", gin.WrapF(pprof.Index))\n\tpp.GET(\"/cmdline\", gin.WrapF(pprof.Cmdline))\n\tpp.GET(\"/profile\", gin.WrapF(pprof.Profile))\n\tpp.GET(\"/symbol\", gin.WrapF(pprof.Symbol))\n\tpp.POST(\"/symbol\", gin.WrapF(pprof.Symbol))\n\tpp.GET(\"/trace\", gin.WrapF(pprof.Trace))\n\tpp.GET(\"/:profile\", gin.WrapF(pprof.Index)) // heap, goroutine, allocs, block, mutex, threadcreate\n\ta.GET(\"/debug/vars\", gin.WrapH(expvar.Handler()))\n\treturn a\n}\n\nfunc send(h http.Handler, path, from, auth string) *httptest.ResponseRecorder {\n\treq := httptest.NewRequest(http.MethodGet, path, nil)\n\treq.RemoteAddr = from + \":40000\"\n\tif auth != \"\" {\n\t\treq.Header.Set(\"Authorization\", auth)\n\t}\n\tw := httptest.NewRecorder()\n\th.ServeHTTP(w, req)\n\treturn w\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\tpublic := newPublic()\n\tadmin := newAdmin([]netip.Prefix{netip.MustParsePrefix(\"127.0.0.0/8\"), netip.MustParsePrefix(\"192.0.2.0/24\")}, \"example-admin-token\")\n\n\t// 1. The import of net/http/pprof already registered handlers on the default mux.\n\tfor _, p := range []string{\"/debug/pprof/\", \"/debug/vars\"} {\n\t\t_, pattern := http.DefaultServeMux.Handler(httptest.NewRequest(http.MethodGet, p, nil))\n\t\tfmt.Printf(\"default mux %-14s -> pattern %q\\n\", p, pattern)\n\t}\n\n\t// 2. The public engine never consults the default mux: debug paths get Gin's 404 body.\n\tfor _, p := range []string{\"/notes\", \"/debug/pprof/\", \"/debug/pprof/heap\", \"/debug/vars\"} {\n\t\tw := send(public, p, \"198.51.100.7\", \"\")\n\t\tfmt.Printf(\"public %-17s %d %q\\n\", p, w.Code, w.Body.String())\n\t}\n\n\t// 3. A \"helpful\" fallback to the default mux leaks every side-effect registration,\n\t// and the status still says 404 because Gin preset it before running NoRoute.\n\tleaky := newPublic()\n\tleaky.NoRoute(gin.WrapH(http.DefaultServeMux))\n\tw := send(leaky, \"/debug/pprof/\", \"198.51.100.7\", \"\")\n\tfmt.Printf(\"leaky  %-17s %d %s leaks index=%t\\n\", \"/debug/pprof/\", w.Code, w.Header().Get(\"Content-Type\"),\n\t\tstrings.Contains(w.Body.String(), \"Types of profiles available\"))\n\n\t// 4. The admin engine: network allow-list first, then the token.\n\tok := \"Bearer example-admin-token\"\n\tfmt.Println(\"admin from 198.51.100.7:\", send(admin, \"/debug/pprof/\", \"198.51.100.7\", ok).Code)\n\tfmt.Println(\"admin from 192.0.2.10, no token:\", send(admin, \"/debug/pprof/\", \"192.0.2.10\", \"\").Code)\n\tw = send(admin, \"/debug/pprof/goroutine?debug=1\", \"192.0.2.10\", ok)\n\tfmt.Println(\"admin goroutine profile:\", w.Code, w.Header().Get(\"Content-Type\"))\n\tw = send(admin, \"/debug/vars\", \"127.0.0.1\", ok)\n\tvar vars map[string]json.RawMessage\n\tif err := json.Unmarshal(w.Body.Bytes(), &vars); err != nil {\n\t\tpanic(err)\n\t}\n\t_, hasCmdline := vars[\"cmdline\"]\n\tfmt.Printf(\"admin expvar: %d notes_served=%s cmdline published=%t\\n\", w.Code, vars[\"notes_served\"], hasCmdline)\n}","language":"go","title":"An admin engine, a guard, and proof that the public engine is clean","walkthrough":"http.DefaultServeMux.Handler reports the patterns GET /debug/pprof/ and GET /debug/vars, registered by the init functions of the two imports. The public engine answers every debug path with Gin's plain 404 body. The leaky engine adds NoRoute(gin.WrapH(http.DefaultServeMux)) and serves the whole pprof index, yet its status is still 404: Gin sets 404 before running NoRoute handlers, and the pprof index never calls WriteHeader. adminOnly checks c.RemoteIP() against the allow-list first, then the bearer token with subtle.ConstantTimeCompare. gin.WrapF adapts each pprof function, gin.WrapH adapts expvar.Handler(), and the decoded expvar JSON shows the custom counter next to the published command line."},{"body":"The leaky engine is the failure worth remembering. Someone adds a NoRoute fallback to the default mux so a legacy http.Handle registration keeps working, and every debug endpoint becomes public. A test that only checks for status 404 still passes, because Gin preset the status before the wrapped handler wrote its body. Assert the body and Content-Type too, for every path pprof and expvar register, as the program does. The other ways to serve the default mux are just as quiet: http.ListenAndServe(addr, nil), a metrics server built without a handler, or a second http.Server whose Handler field was left empty. If a service needs standard-library handlers next to Gin, give them a private http.NewServeMux and mount that, never the default one. A review rule that rejects a nil handler argument, plus the public 404-body test, closes both paths.","title":"A 404 status is not proof"},{"body":"pprof.Index chooses a profile by cutting the literal prefix /debug/pprof/ from r.URL.Path. Mount it under /admin/debug/pprof/*any and every profile URL returns the HTML index with status 200, which looks like success and contains no profile. Keep the exact prefix on the admin engine, or wrap the handler in http.StripPrefix and gin.WrapH. In Gin 1.12 the :profile parameter route coexists with the static cmdline, profile, symbol and trace routes, and Gin redirects /debug/pprof to /debug/pprof/ with a 301. Profile and Trace extend the connection's write deadline by the requested seconds through http.ResponseController, which works through Gin because its response writer implements Unwrap. Only one CPU profile can run at a time; a second request gets a 500. The block and mutex profiles stay empty until the program calls runtime.SetBlockProfileRate and runtime.SetMutexProfileFraction.","title":"Mount pprof at exactly /debug/pprof/"},{"body":"A separate listener is the real boundary; the guard is defense in depth. Bind the admin server to loopback and reach it with kubectl port-forward, or bind it to the Pod address on a port that no public Service or ingress selects and that a NetworkPolicy restricts. The guard uses c.RemoteIP(), not c.ClientIP(), because forwarded headers are client input, as the trusted-proxies lesson explains, and nothing should proxy the admin port anyway. Load the token from configuration rather than a flag, since a flag would appear in the cmdline endpoint it protects, and log every admin request.","code":"public := &http.Server{Addr: \":8080\", Handler: newPublic(), ReadHeaderTimeout: 5 * time.Second}\nadmin := &http.Server{\n\tAddr:              \"127.0.0.1:6060\",\n\tHandler:           newAdmin(cfg.AdminNetworks, cfg.AdminToken),\n\tReadHeaderTimeout: 5 * time.Second,\n\tWriteTimeout:      10 * time.Second, // pprof extends it by ?seconds=\n}\ng, ctx := errgroup.WithContext(ctx)\ng.Go(func() error { return listen(public) })\ng.Go(func() error { return listen(admin) })\ng.Go(func() error {\n\t<-ctx.Done()\n\tdrain, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\treturn errors.Join(public.Shutdown(drain), admin.Shutdown(drain))\n})\nreturn g.Wait()","language":"go","title":"Two servers in one process","walkthrough":"Run this fragment in your own environment; listen is a small helper that calls ListenAndServe and treats http.ErrServerClosed as nil. Each engine gets its own http.Server with its own budgets, and the admin WriteTimeout is a floor that pprof raises per request. errgroup ties the two lifetimes together: if either listener fails, ctx is canceled and both servers shut down within one budget, so the process never keeps serving public traffic with its diagnostics gone, or the reverse."}],"takeaway":"Importing pprof or expvar registers handlers on http.DefaultServeMux; serve them only from a separate, guarded admin engine and listener, and test the public engine for a 404 body, not just a 404 status.","title":"Debug endpoints in Gin: pprof and expvar on a separate admin engine and listener, never on the public router","unitID":"gin-edge","wrongAnswers":["Gin's engine serves them at /debug/pprof/ automatically","They are registered only for a blank _ import"]},{"conceptTag":"gin.release-builds","designGuide":{"cautions":["An unknown GIN_MODE panics in Gin init, before main.","With -trimpath the -ldflags value is absent from build info.","ARG and ENV values are readable in the image history."],"cost":"A few build flags and a two-stage Dockerfile; you give up a shell in the runtime image, so debugging moves to logs, the admin listener and ephemeral debug containers.","family":"gin","flow":["Fix the Gin mode owner","Stamp version and VCS","Build static, trimmed","Run non-root, no secrets"],"ratings":[],"strengths":["/version answers which commit is running in one request.","A static binary on distroless has a tiny attack surface and no shell."]},"hint":"Ask which file the kernel needs before main can run.","id":"gin.release-builds","introduction":"The binary you test with go run is not the one you ship. A release build differs in Gin's mode, in what the toolchain stamps into the executable, in how it links and in the image around it. Each difference has a failure attached: request headers in debug logs, an incident where nobody can say which commit is running, a container that will not start because a C library is missing. This lesson follows the build from the mode switch to the final image.","nuance":"With a C compiler present cgo is on, so net and os/user link dynamically and need a loader such as ld-linux. The static image has none, so exec reports no such file or directory; CGO_ENABLED=0 builds a static binary.","objective":"Build a Gin service for production with release mode, -trimpath, -ldflags -X and CGO_ENABLED=0, report its identity from runtime/debug build info, and package it in a minimal non-root image.","question":"A Gin binary built in the golang image runs on the build host but fails in a distroless static container with \"no such file or directory\". What is the likely cause?","references":["https://pkg.go.dev/runtime/debug#ReadBuildInfo","https://pkg.go.dev/cmd/go","https://pkg.go.dev/cmd/link","https://github.com/GoogleContainerTools/distroless"],"reviewAnswer":"A cgo build needs a C loader the static image lacks","reviewPrompt":"Why CGO_ENABLED=0 for distroless?","sections":[{"body":"Gin reads GIN_MODE once, in its package init, and an empty value means debug, or test under go test. Debug mode prints the route table and warnings to stdout, re-parses templates loaded with LoadHTMLGlob on every render, and when Recovery catches a panic it logs the request's headers with only Authorization masked, so cookies and API-key headers reach the logs. Release mode drops all of that. An unknown value is not ignored: GIN_MODE=production makes SetMode panic inside Gin's init, before main runs and before your logger exists. Pick one owner for the mode. Either the deployment sets GIN_MODE=release and nothing calls SetMode, or validated configuration calls gin.SetMode before any engine is built, as the config-startup lesson does, and GIN_MODE stays unset. Two owners eventually disagree.","title":"What Gin's debug mode does in production"},{"body":"debug.ReadBuildInfo returns the running binary's own record, which differs on every build, so the program parses a fixed record in the same text format with debug.ParseBuildInfo. It also validates a mode setting, shows what SetMode does with an unknown value, and serves /version twice: as go run links it, and with a version string as -ldflags -X would set it.","code":"package main\n\nimport (\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"runtime/debug\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// version is set at link time: go build -ldflags \"-X main.version=v1.4.0\".\nvar version = \"\"\n\n// A fixed build record in the format debug.BuildInfo.String produces.\n// In the service, debug.ReadBuildInfo returns the running binary's own record.\nconst recorded = \"go\\tgo1.27.3\\n\" +\n\t\"path\\texample.com/notes-api/cmd/api\\n\" +\n\t\"mod\\texample.com/notes-api\\tv1.4.0\\t\\n\" +\n\t\"dep\\tgithub.com/gin-gonic/gin\\tv1.12.0\\th1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8=\\n\" +\n\t\"build\\t-buildmode=exe\\n\" +\n\t\"build\\t-compiler=gc\\n\" +\n\t\"build\\t-trimpath=true\\n\" +\n\t\"build\\tCGO_ENABLED=0\\n\" +\n\t\"build\\tGOARCH=amd64\\n\" +\n\t\"build\\tGOOS=linux\\n\" +\n\t\"build\\tGOAMD64=v1\\n\" +\n\t\"build\\tvcs=git\\n\" +\n\t\"build\\tvcs.revision=9f3c2b7d41e0a5c8b6f1e2d3c4b5a69788796a5b\\n\" +\n\t\"build\\tvcs.time=2026-11-17T09:30:00Z\\n\" +\n\t\"build\\tvcs.modified=false\\n\"\n\ntype Version struct {\n\tVersion  string `json:\"version\"`\n\tRevision string `json:\"revision\"`\n\tTime     string `json:\"time\"`\n\tModified bool   `json:\"modified\"`\n\tGo       string `json:\"go\"`\n\tGin      string `json:\"gin\"`\n\tCgo      bool   `json:\"cgo\"`\n}\n\nfunc versionFrom(bi *debug.BuildInfo, linked string) Version {\n\tv := Version{Version: linked, Go: bi.GoVersion}\n\tif v.Version == \"\" {\n\t\tv.Version = bi.Main.Version // \"(devel)\" when the build had no VCS or tag data\n\t}\n\tfor _, s := range bi.Settings {\n\t\tswitch s.Key {\n\t\tcase \"vcs.revision\":\n\t\t\tv.Revision = s.Value\n\t\tcase \"vcs.time\":\n\t\t\tv.Time = s.Value\n\t\tcase \"vcs.modified\":\n\t\t\tv.Modified = s.Value == \"true\"\n\t\tcase \"CGO_ENABLED\":\n\t\t\tv.Cgo = s.Value == \"1\"\n\t\t}\n\t}\n\tfor _, d := range bi.Deps {\n\t\tif d.Path == \"github.com/gin-gonic/gin\" {\n\t\t\tv.Gin = d.Version\n\t\t}\n\t}\n\treturn v\n}\n\n// ginMode validates the mode from the service's own config and defaults to\n// release, where Gin itself would default to debug.\nfunc ginMode(configured string) (string, error) {\n\tswitch configured {\n\tcase \"\":\n\t\treturn gin.ReleaseMode, nil\n\tcase gin.ReleaseMode, gin.DebugMode, gin.TestMode:\n\t\treturn configured, nil\n\t}\n\treturn \"\", fmt.Errorf(\"mode %q: want release, debug or test\", configured)\n}\n\nfunc newRouter(v Version) *gin.Engine {\n\tr := gin.New()\n\tr.Use(gin.Recovery())\n\tr.GET(\"/version\", func(c *gin.Context) {\n\t\tc.Header(\"Cache-Control\", \"no-store\")\n\t\tc.JSON(http.StatusOK, v)\n\t})\n\treturn r\n}\n\nfunc main() {\n\tfor _, configured := range []string{\"\", \"debug\", \"production\"} {\n\t\tmode, err := ginMode(configured)\n\t\tfmt.Printf(\"config %q -> mode %q, err %v\\n\", configured, mode, err)\n\t}\n\n\tfunc() {\n\t\tdefer func() { fmt.Println(\"gin.SetMode(\\\"production\\\") panics:\", recover()) }()\n\t\tgin.SetMode(\"production\")\n\t}()\n\tgin.SetMode(gin.ReleaseMode) // no route table or debug warnings on stdout\n\tfmt.Println(\"mode\", gin.Mode(), \"debugging\", gin.IsDebugging())\n\n\tbi, err := debug.ParseBuildInfo(recorded)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"parsed GoVersion %q: ParseBuildInfo skips the go line\\n\", bi.GoVersion)\n\tbi.GoVersion = \"go1.27.3\" // ReadBuildInfo fills this from runtime.Version()\n\n\tfor _, linked := range []string{version, \"v1.4.0-rc.2\"} {\n\t\tw := httptest.NewRecorder()\n\t\tnewRouter(versionFrom(bi, linked)).ServeHTTP(w, httptest.NewRequest(http.MethodGet, \"/version\", nil))\n\t\tfmt.Println(w.Code, w.Body.String())\n\t}\n}","language":"go","title":"Report the build identity at /version","walkthrough":"ginMode accepts the three names Gin knows and maps an empty setting to release, the opposite of Gin's own default. SetMode panics on anything else, and recover turns that into a printed line here. ParseBuildInfo reads the path, mod, dep and build lines but skips the go line, because ReadBuildInfo fills GoVersion from runtime.Version() separately, so the program sets it by hand. versionFrom prefers the linked string, falls back to the main module version, which go build derives from a VCS tag or reports as (devel), and copies vcs.revision, vcs.time and vcs.modified. Cache-Control: no-store stops caches from reporting a previous deploy's identity."},{"body":"-trimpath removes the build machine's directories from file names recorded in the binary, so stack traces do not reveal home directories and builds from different checkouts match. -ldflags \"-X main.version=...\" sets a package-level string variable at link time; for other packages it needs the full import path, it works only on a variable that is uninitialized or initialized to a constant string, and a misspelled name is silently ignored, which is why /version should be checked after every build. -s -w drop the symbol table and DWARF data: panics and pprof still name functions because they use the runtime's own tables, but a debugger has less to work with. CGO_ENABLED=0 matters because the golang image has a C compiler, so cgo is on by default and net and os/user link against the system C library.","code":"VERSION=$(git describe --tags --always --dirty)\nCGO_ENABLED=0 GOOS=linux GOARCH=amd64 \\\n  go build -trimpath -ldflags \"-s -w -X main.version=${VERSION}\" -o bin/api ./cmd/api\ngo version -m bin/api | grep -E 'vcs\\.|CGO_ENABLED|trimpath'\nfile bin/api","language":"bash","title":"Build flags that make the binary honest","walkthrough":"Run these in your own checkout. git describe prints a tag-based version with a -dirty suffix when the tree has uncommitted changes. go version -m prints the record the /version handler reads; expect vcs.revision, vcs.time, vcs.modified, CGO_ENABLED=0 and -trimpath=true. One surprise: with -trimpath, go build leaves -ldflags out of that record, because linker flags can contain local paths, so the -X value is visible only through the variable it set. file should report a statically linked executable."},{"body":"The containers lesson builds a basic two-stage image on scratch. For a Gin API, the distroless static image is a better default runtime: it adds CA certificates for outbound TLS, time zone data, an /etc/passwd with a nonroot user and a /tmp directory, and still has no shell or package manager. A cgo-linked binary fails in it with a confusing no such file or directory, because the missing file is the dynamic loader, not your program. Use a numeric USER: when a Pod sets runAsNonRoot without a runAsUser, Kubernetes can verify only a numeric image user and refuses to start a container whose image names one. If .dockerignore excludes .git, as it usually should, go build has no VCS data inside the build, the vcs fields are empty and the version is (devel), so CI passes the version in as a build argument.","code":"# syntax=docker/dockerfile:1\nFROM golang:1.27 AS build\nWORKDIR /src\nCOPY go.mod go.sum ./\nRUN --mount=type=cache,target=/go/pkg/mod go mod download\nCOPY . .\nARG VERSION=dev\nRUN --mount=type=cache,target=/go/pkg/mod \\\n    --mount=type=cache,target=/root/.cache/go-build \\\n    CGO_ENABLED=0 GOOS=linux go build -trimpath \\\n    -ldflags \"-s -w -X main.version=${VERSION}\" -o /out/api ./cmd/api\n\n# Pin the digest you reviewed: static-debian12:nonroot@sha256:...\nFROM gcr.io/distroless/static-debian12:nonroot\nCOPY --from=build /out/api /api\nUSER 65532:65532\nEXPOSE 8080\nENTRYPOINT [\"/api\"]","language":"text","title":"A multi-stage image with a distroless, non-root runtime","walkthrough":"This Dockerfile runs in your own environment: docker build --build-arg VERSION=$(git describe --tags --always --dirty) -t notes-api:dev . The build stage holds the toolchain, module cache and source; only /out/api crosses into the runtime stage. Cache mounts keep downloads and compiled packages between builds without storing them in any layer. The exec-form ENTRYPOINT makes the binary PID 1, so it receives SIGTERM directly, which the rolling-deploys lesson relies on."},{"body":"Anything in a layer or in the image config is readable by everyone who can pull the image, forever. ARG and ENV values are recorded in the image history, so a token passed as a build argument is published; private module credentials belong in a BuildKit secret mount used by a single RUN step and never written to a layer. Environment-specific settings, such as database URLs, tokens, trusted proxy ranges or a debug mode, come from the orchestrator at runtime, so the same digest can be promoted from staging to production as the delivery lesson requires. The source tree, .git, .env files, fixtures and local binaries stay out through .dockerignore. Decide what /version itself may reveal: version, revision, commit time and the modified flag help operators, while hostnames, environment values or the full dependency list help attackers. A production response with modified true is itself a finding: someone shipped uncommitted code.","title":"What must not be baked into the image"}],"takeaway":"Ship with release mode set by one owner, -trimpath, CGO_ENABLED=0 and a -X version; report vcs.revision, vcs.time and vcs.modified from build info at /version, and run as a numeric non-root user with no secrets in any layer.","title":"Shipping a Gin binary: release mode, a /version endpoint from build info, static builds and a non-root image","unitID":"gin-edge","wrongAnswers":["The distroless image has no shell to start the binary","-trimpath removed paths the binary opens at startup"]},{"conceptTag":"gin.rolling-deploys","designGuide":{"cautions":["Delay plus budget must fit inside terminationGracePeriodSeconds.","Shutdown does not wait for hijacked connections or streams.","A main that returns when ListenAndServe does cuts the drain short."],"cost":"Every Pod termination takes the drain delay plus in-flight time, which lengthens each rollout; the code is one Lifecycle flag, one Drain function and a grace period to keep in sync.","family":"gin","flow":["Flip readiness to 503","Disable keep-alives","Serve through the delay","Shutdown, then Close"],"ratings":[],"strengths":["Rollouts complete without refused connections or cut requests.","An injected clock makes the sequence testable in milliseconds."]},"hint":"Think about who still believes the old Pod is a valid target.","id":"gin.rolling-deploys","introduction":"During a rolling deploy every old replica is told to stop while traffic is still arriving. Calling Shutdown the moment SIGTERM lands closes the listener before every load balancer has heard the replica is leaving, and the requests they still send meet a refused connection. The fix is an ordered sequence with one owner, and because it is about time and ordering, it should be modeled with an injected clock and tested like any other code.","nuance":"Endpoint removal and SIGTERM start together, and proxies learn of the removal late. Shutdown closes the listener at once, refusing connections still routed to the Pod; a short serving delay covers that window.","objective":"Implement and test a SIGTERM sequence that flips readiness to 503, keeps serving while load balancers stop routing, disables keep-alives, and shuts the http.Server down within a grace period the platform honors.","question":"On SIGTERM a Gin service calls http.Server.Shutdown at once, and during rolling deploys some clients see connection refused. Why does a short drain delay before Shutdown fix this?","references":["https://pkg.go.dev/net/http#Server.Shutdown","https://pkg.go.dev/net/http#Server.SetKeepAlivesEnabled","https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#pod-termination","https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/"],"reviewAnswer":"Load balancers still route until endpoint removal spreads","reviewPrompt":"Why wait before calling Shutdown?","sections":[{"body":"When Kubernetes deletes a Pod, two things start in parallel: the control plane removes the Pod's endpoints from its Services, and the kubelet runs any preStop hook and then sends SIGTERM. The endpoint change then has to reach every kube-proxy, ingress controller and cloud load balancer, which takes from milliseconds to several seconds. A process that closes its listener at once refuses connections routed during that window; one that exits drops requests mid-flight; and clients holding keep-alive connections keep reusing the old Pod's sockets. Kubernetes already marks a terminating Pod's endpoints not ready, so for a plain Service the readiness flip mostly confirms what the control plane did. It matters for load balancers and ingress controllers that health-check the Pod directly, and EndpointSlices still publish the probe result as their serving condition. The drain delay is what covers propagation. The server-lifecycle lesson sets the budgets; this one orders the steps.","title":"The window where requests get dropped"},{"body":"Drain depends only on interfaces: a Clock with After, and the three methods of *http.Server it calls. The model supplies a clock that moves only when told and a server that runs the Gin engine through httptest recorders and refuses requests once Shutdown has closed its listener. main narrates two runs: a slow export that finishes inside the budget, and one that does not.","code":"package main\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"github.com/gin-gonic/gin\"\n)\n\n// Clock is the drain sequence's only source of time.\ntype Clock interface {\n\tAfter(d time.Duration) <-chan time.Time\n}\n\n// Server is the part of *http.Server the sequence uses; *http.Server satisfies it.\ntype Server interface {\n\tSetKeepAlivesEnabled(bool)\n\tShutdown(context.Context) error\n\tClose() error\n}\n\n// Lifecycle owns the readiness flag; handlers read it, Drain writes it.\ntype Lifecycle struct{ draining atomic.Bool }\n\nfunc (l *Lifecycle) Readyz(c *gin.Context) {\n\tif l.draining.Load() {\n\t\tc.String(http.StatusServiceUnavailable, \"draining\")\n\t\treturn\n\t}\n\tc.String(http.StatusOK, \"ready\")\n}\n\n// Drain runs once SIGTERM arrives: readiness, delay, graceful Shutdown, then Close.\nfunc Drain(sigterm <-chan struct{}, lc *Lifecycle, srv Server, clock Clock, delay, budget time.Duration, step func(string)) error {\n\t<-sigterm\n\tlc.draining.Store(true)\n\tsrv.SetKeepAlivesEnabled(false)\n\twait := clock.After(delay)\n\tstep(\"SIGTERM: readiness 503, keep-alives off, still serving for \" + delay.String())\n\t<-wait\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\texpired := clock.After(budget)\n\tgo func() {\n\t\tselect {\n\t\tcase <-expired:\n\t\t\tcancel()\n\t\tcase <-ctx.Done():\n\t\t}\n\t}()\n\tstep(\"delay over: Shutdown closes the listener, budget \" + budget.String())\n\tif err := srv.Shutdown(ctx); err != nil {\n\t\tsrv.Close()\n\t\treturn fmt.Errorf(\"drain budget exceeded, connections closed: %w\", err)\n\t}\n\treturn nil\n}\n\n// fakeClock fires timers only when Advance is called.\ntype fakeClock struct {\n\tmu     sync.Mutex\n\tnow    time.Duration\n\ttimers map[chan time.Time]time.Duration\n}\n\nfunc (c *fakeClock) After(d time.Duration) <-chan time.Time {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tch := make(chan time.Time, 1)\n\tc.timers[ch] = c.now + d\n\treturn ch\n}\n\nfunc (c *fakeClock) Elapsed() time.Duration {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\treturn c.now\n}\n\nfunc (c *fakeClock) Advance(d time.Duration) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\tc.now += d\n\tfor ch, at := range c.timers {\n\t\tif at <= c.now {\n\t\t\tch <- time.Time{}.Add(at)\n\t\t\tdelete(c.timers, ch)\n\t\t}\n\t}\n}\n\n// fakeServer models what http.Server does with a handler, without sockets.\ntype fakeServer struct {\n\th        http.Handler\n\tmu       sync.Mutex\n\tclosed   bool\n\tnoKeep   atomic.Bool\n\tinflight sync.WaitGroup\n\tshutdown chan struct{} // closed once the listener is gone\n}\n\nfunc (s *fakeServer) Do(path string) (*httptest.ResponseRecorder, error) {\n\ts.mu.Lock()\n\tif s.closed {\n\t\ts.mu.Unlock()\n\t\treturn nil, errors.New(\"connection refused\")\n\t}\n\ts.inflight.Add(1)\n\ts.mu.Unlock()\n\tdefer s.inflight.Done()\n\tw := httptest.NewRecorder()\n\tif s.noKeep.Load() {\n\t\tw.Header().Set(\"Connection\", \"close\") // net/http adds this when keep-alives are off\n\t}\n\ts.h.ServeHTTP(w, httptest.NewRequest(http.MethodGet, path, nil))\n\treturn w, nil\n}\n\nfunc (s *fakeServer) SetKeepAlivesEnabled(v bool) { s.noKeep.Store(!v) }\n\nfunc (s *fakeServer) Shutdown(ctx context.Context) error {\n\ts.mu.Lock()\n\ts.closed = true\n\ts.mu.Unlock()\n\tclose(s.shutdown)\n\tdone := make(chan struct{})\n\tgo func() { s.inflight.Wait(); close(done) }()\n\tselect {\n\tcase <-done:\n\t\treturn nil\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n}\n\nfunc (s *fakeServer) Close() error { return nil }\n\nfunc newRouter(lc *Lifecycle, entered chan<- struct{}, release <-chan struct{}) *gin.Engine {\n\tr := gin.New()\n\tr.GET(\"/readyz\", lc.Readyz)\n\tr.GET(\"/orders\", func(c *gin.Context) { c.String(http.StatusOK, \"orders\") })\n\tr.GET(\"/export\", func(c *gin.Context) {\n\t\tentered <- struct{}{}\n\t\t<-release // a slow request that is in flight when SIGTERM arrives\n\t\tc.String(http.StatusOK, \"export done\")\n\t})\n\treturn r\n}\n\nfunc run(name string, exportFinishes bool) {\n\tfmt.Println(\"==\", name)\n\tlc := &Lifecycle{}\n\tentered, release := make(chan struct{}), make(chan struct{})\n\tsrv := &fakeServer{h: newRouter(lc, entered, release), shutdown: make(chan struct{})}\n\tclock := &fakeClock{timers: map[chan time.Time]time.Duration{}}\n\tsigterm, steps, result := make(chan struct{}), make(chan string), make(chan error)\n\tgo func() {\n\t\tresult <- Drain(sigterm, lc, srv, clock, 5*time.Second, 20*time.Second, func(s string) { steps <- s })\n\t}()\n\tat := func(format string, args ...any) {\n\t\tfmt.Printf(\"t+%-3s \"+format+\"\\n\", append([]any{clock.Elapsed().String()}, args...)...)\n\t}\n\tget := func(path string) {\n\t\tw, err := srv.Do(path)\n\t\tif err != nil {\n\t\t\tat(\"GET %-7s %v\", path, err)\n\t\t\treturn\n\t\t}\n\t\tconn := w.Header().Get(\"Connection\")\n\t\tif conn == \"\" {\n\t\t\tconn = \"keep-alive\"\n\t\t}\n\t\tat(\"GET %-7s %d %s, connection %s\", path, w.Code, w.Body.String(), conn)\n\t}\n\n\tget(\"/readyz\")\n\texported := make(chan *httptest.ResponseRecorder)\n\tgo func() { w, _ := srv.Do(\"/export\"); exported <- w }()\n\t<-entered\n\n\tclose(sigterm)\n\tat(\"%s\", <-steps)\n\tget(\"/readyz\")\n\tget(\"/orders\")\n\n\tclock.Advance(5 * time.Second)\n\tat(\"%s\", <-steps)\n\t<-srv.shutdown\n\tget(\"/orders\")\n\n\tif exportFinishes {\n\t\tclose(release)\n\t\tw := <-exported\n\t\tat(\"in-flight /export finished: %d %s\", w.Code, w.Body.String())\n\t\tat(\"Drain returned %v\", <-result)\n\t\treturn\n\t}\n\tclock.Advance(20 * time.Second)\n\tat(\"Drain returned %v\", <-result)\n\tclose(release)\n\t<-exported\n}\n\nfunc main() {\n\tgin.SetMode(gin.TestMode)\n\trun(\"export finishes inside the budget\", true)\n\trun(\"export ignores the budget\", false)\n}","language":"go","title":"Model the sequence with a fake clock and a fake server","walkthrough":"Drain waits for sigterm to close, stores the draining flag that Lifecycle.Readyz reads, disables keep-alives, and only then asks the clock for the delay, so the step message proves the timer exists before main advances. During the delay /readyz answers 503 while /orders is still served, with Connection: close as net/http adds when keep-alives are off. After Advance(5s), Drain registers the budget timer and calls Shutdown; the fake closes its listener, so the next request is refused, and waits for in-flight requests. In the first run the export finishes and Shutdown returns nil. In the second, Advance(20s) fires the budget, the watcher cancels the context and Drain falls back to Close. main prints every line after a channel receive, so scheduling never changes the order."},{"body":"Readiness goes first because it is the only signal some balancers act on; return 503, since Kubernetes HTTP probes count every status from 200 to 399 as success, and keep liveness at 200 throughout, as the metrics-health lesson explains. The delay should exceed a direct health checker's probe period times its failure threshold plus endpoint propagation; five to ten seconds is common, and every Pod in a rollout pays it. SetKeepAlivesEnabled(false) closes idle HTTP/1.1 connections at once and makes each active one close after its current response; HTTP/2 connections get a GOAWAY when their last open stream finishes. Shutdown disables keep-alives too, so the explicit call matters only during the delay, which is the point: clients reconnect while the listener still accepts, and the balancer sends the new connections elsewhere. Shutdown closes listeners and idle connections, then waits for active ones; it does not wait for hijacked connections, and an open Server-Sent Events stream simply holds it until the budget expires, so register a RegisterOnShutdown function that tells streaming handlers to finish.","title":"Why the order is readiness, keep-alives, delay, Shutdown"},{"body":"Nothing in Drain changes for production. A real clock adapts time.After, *http.Server already has SetKeepAlivesEnabled, Shutdown and Close, and the Lifecycle value is injected into the Gin handler like any other dependency, so the model's tests keep covering the code that ships. The one new obligation is in main, which must not return while the drain is still running.","code":"type realClock struct{}\n\nfunc (realClock) After(d time.Duration) <-chan time.Time { return time.After(d) }\n\nfunc serve(srv *http.Server, lc *Lifecycle, delay, budget time.Duration) error {\n\tsigterm := make(chan struct{})\n\tsigs := make(chan os.Signal, 1)\n\tsignal.Notify(sigs, syscall.SIGTERM, os.Interrupt)\n\tgo func() { <-sigs; signal.Stop(sigs); close(sigterm) }()\n\n\tdrained := make(chan error, 1)\n\tgo func() {\n\t\tdrained <- Drain(sigterm, lc, srv, realClock{}, delay, budget, func(s string) { slog.Info(s) })\n\t}()\n\tif err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {\n\t\treturn err\n\t}\n\t// ListenAndServe returns as soon as Shutdown starts; requests are\n\t// still in flight, so wait for Drain before main may return.\n\treturn <-drained\n}","language":"go","title":"Wire the same Drain to a real signal and server","walkthrough":"Run this fragment in your own environment. signal.Stop after the first signal restores default handling, so a second Ctrl-C ends a stuck drain at once. The comment marks the classic bug: ListenAndServe returns http.ErrServerClosed the moment Shutdown begins, and a main that returns then exits with requests still running. If ListenAndServe fails for another reason, such as a port already in use, serve returns that error immediately. Do not derive request contexts from the signal, as the config-startup lesson warns."},{"body":"The grace period countdown starts when the Pod is deleted, before any preStop hook runs, and SIGKILL arrives when it ends, whatever the process is doing. Keep the arithmetic true whenever the delay or budget changes: delay plus Shutdown budget plus the time to close pools and flush telemetry must fit inside terminationGracePeriodSeconds. A preStop sleep is the other place a delay can live, useful when you cannot change the application, but it counts against the same grace period, so never stack it on top of an in-app delay by accident. Pair the sequence with a rollout strategy that keeps capacity, such as maxUnavailable 0 with a surge, as the rollout lesson describes. To verify it in a real cluster, run steady load through kubectl rollout restart and count errors; the target is zero, and the model keeps the ordering from regressing.","code":"# Pod template fragment: merge into a Deployment in your own cluster.\nspec:\n  terminationGracePeriodSeconds: 35   # delay 5s + Shutdown budget 20s + margin\n  containers:\n    - name: api\n      image: registry.example.com/notes-api@sha256:<digest>\n      readinessProbe:\n        httpGet: {path: /readyz, port: 8080}\n        periodSeconds: 2\n        failureThreshold: 1\n      # Only if the app cannot delay on SIGTERM itself. Distroless images have\n      # no shell, so use the sleep action, not exec: [\"sleep\", \"5\"].\n      # lifecycle:\n      #   preStop:\n      #     sleep:\n      #       seconds: 5","language":"yaml","title":"Fit the sequence inside the Pod's grace period","walkthrough":"Apply this in your own cluster, not in the app. The comment beside terminationGracePeriodSeconds is the budget to recheck on every change. A 2-second probe period with failureThreshold 1 lets anything polling /readyz see the 503 well within the 5-second delay. The commented preStop block is the alternative owner of the delay; the sleep action needs Kubernetes 1.30 or newer, where it is enabled by default, and an exec sleep would fail in an image without a shell."}],"takeaway":"On SIGTERM flip readiness to 503, disable keep-alives and keep serving through a drain delay, then Shutdown within a budget and Close after it; fit delay plus budget inside terminationGracePeriodSeconds and wait for the drain before main returns.","title":"Surviving a rolling deploy in Gin: fail readiness, keep serving through a drain delay, then Shutdown","unitID":"gin-edge","wrongAnswers":["Shutdown cancels in-flight requests unless it is delayed","SIGTERM arrives before the replacement Pod has started"]}],"revision":"2026-11-18.2","schemaVersion":1,"solutions":{},"units":[{"id":"gin-foundations","lessons":[{"conceptTags":["gin.first-service"],"explanation":"Gin is a router, a request context and a middleware chain built on top of net/http. A *gin.Engine is an ordinary http.Handler, so everything you know about http.Server, httptest and timeouts still applies. Start with a function that returns a configured engine: main can serve it, and a test can call it directly.","id":"gin.first-service","objective":"Build a Gin engine, register routes with a path parameter and exercise them without opening a port.","task":{"reading":{}},"title":"Your first Gin service: an engine, two routes and a test request"},{"conceptTags":["gin.path-parameters"],"explanation":"Every Gin route is a template stored in a radix tree. The router decides which handler runs, what c.Param returns and whether the client gets a redirect instead of your handler. Most routing bugs are not in handler code: they are a trailing slash, an encoded slash or two templates that cannot share a prefix. Learn the matching rules once and those bugs become predictable.","id":"gin.path-parameters","objective":"Declare Gin route templates with :param and *wildcard, predict how slashes and escapes resolve, and label metrics with c.FullPath().","task":{"reading":{}},"title":"Path parameters in Gin: :param takes one segment, *wildcard takes the rest, conflicts panic at boot"},{"conceptTags":["gin.query-and-forms"],"explanation":"Every query or form value reaches your handler as a string that may be missing, empty, repeated or malformed. Gin offers several helpers that look interchangeable but answer different questions. Choosing the wrong one turns limit=abc into limit 0, or a deliberately empty field into a default the client never asked for.","id":"gin.query-and-forms","objective":"Read query and form values with the Gin helper that matches the case, convert them with strconv and reject bad input with a clear 400.","task":{"reading":{}},"title":"Query strings and forms in Gin: tell absent from empty, parse numbers strictly, bound every limit"},{"conceptTags":["gin.route-groups"],"explanation":"r.Group(\"/api/v1\") looks like a folder that routes live in, with middleware guarding the door. It is really a registration helper: when you add a route, Gin copies the group's prefix and handler list into that route, and the group plays no part when requests arrive. That one fact explains the most common group bug and tells you how to test for it.","id":"gin.route-groups","objective":"Organize a Gin API into nested, versioned groups with scoped middleware and prove with r.Routes() that every route has the protection you intended.","task":{"reading":{}},"title":"Gin route groups: prefixes and middleware are copied at registration, so test the route table"},{"conceptTags":["gin.json-responses"],"explanation":"The bytes a handler writes are a public contract: field names, which fields exist, how characters are escaped, the Content-Type and the status. Gin has five JSON renderers that look interchangeable and are not, and c.JSON will happily publish every field of whatever struct you hand it, including the ones you add next year.","id":"gin.json-responses","objective":"Choose between c.JSON, PureJSON, IndentedJSON, SecureJSON and AsciiJSON by their exact output, set status codes deliberately and render a response DTO with correct omitempty and omitzero tags.","task":{"reading":{}},"title":"Gin JSON responses: know what each renderer writes and return a DTO, never your storage model"},{"conceptTags":["gin.binding-sources"],"explanation":"A single request carries input in four places: path parameters, the query string, headers and the body. Gin has a binder and a struct tag for each, and they compose well as long as you respect two rules the API does not advertise. Every binder validates the entire struct it fills, and a request body can be read only once unless you ask Gin to keep a copy.","id":"gin.binding-sources","objective":"Bind each request source with its own Gin binder and tag, predict what content-type-driven ShouldBind reads, and decode one body twice with ShouldBindBodyWithJSON.","task":{"reading":{}},"title":"Gin binding sources: bind path, query, headers and body separately, and cache the body to read it twice"},{"conceptTags":["gin.custom-validators"],"explanation":"Gin's binding tags cover shape: required, lengths, ranges, enumerations. Real input also has domain rules, such as a SKU format or an address that is required unless the customer picks the order up. Gin's validator accepts both kinds, but the default error text names Go structs and fields, which makes a poor API. This lesson adds the rules and a response format you can keep stable.","id":"gin.custom-validators","objective":"Register a custom tag and a struct-level rule on Gin's validator, validate slice elements with dive and convert validator errors into a stable field-level JSON response.","task":{"reading":{}},"title":"Custom validators in Gin: register domain rules once and return field errors clients can rely on"},{"conceptTags":["gin.middleware-basics"],"explanation":"Gin middleware is an ordinary handler that happens to run before others in the same chain. Most middleware bugs come from a wrong mental model of that chain: expecting Abort to return, expecting a middleware without c.Next to stop the request, or reading a status before the handler has chosen it. This lesson builds four realistic middleware functions and traces exactly what runs.","id":"gin.middleware-basics","objective":"Write Gin middleware that runs code after c.Next, stops the chain with Abort and return, shares typed values through c.Set and c.Get, and is ordered so logs see the final outcome.","task":{"reading":{}},"title":"Writing Gin middleware: what c.Next returns to, what Abort does not do, and typed request values"},{"conceptTags":["gin.file-uploads"],"explanation":"An upload is attacker-controlled bytes wrapped in attacker-controlled labels. The filename, the declared Content-Type and the size all come from the client, and so does the number of parts. c.FormFile makes accepting a file one line long, which is exactly why the limits, the type decision and the storage name have to be written deliberately around it.","id":"gin.file-uploads","objective":"Accept a multipart upload in Gin with a hard size cap, decide its type from its content, generate the storage name yourself and test it with a request built by mime/multipart.","task":{"reading":{}},"title":"File uploads in Gin: cap the request, sniff the bytes and never let the client name the file"},{"conceptTags":["gin.html-templates"],"explanation":"Gin can render server-side HTML with very little code, and Go's html/template does the hardest part, escaping, for you. What Gin leaves to you are the operational decisions: how templates reach the binary, what happens when a template fails halfway, whether a directory listing is exposed and how long browsers and CDNs may keep each file.","id":"gin.html-templates","objective":"Render html/template pages with c.HTML from templates parsed out of an embedded file system, serve embedded static assets with StaticFS and set cache headers per kind of asset.","task":{"reading":{}},"title":"Server-rendered HTML in Gin: embed the templates, trust contextual escaping, cache assets on purpose"},{"conceptTags":["gin.not-found-and-methods"],"explanation":"A Gin engine answers misses on its own: a plain-text 404 for unknown paths and, by default, the same 404 for a known path with the wrong method. API clients that expect JSON errors choke on the text, and a 404 for a wrong method sends whoever is debugging in the wrong direction. A few lines of configuration fix both, and the same lesson applies to redirects: the status code decides whether the method and body survive.","id":"gin.not-found-and-methods","objective":"Configure NoRoute, NoMethod and HandleMethodNotAllowed for consistent JSON 404 and 405 responses with a correct Allow header, and choose between 301, 302, 303, 307 and 308 for redirects.","task":{"reading":{}},"title":"404, 405 and redirects in Gin: answer misses in your own format and pick redirect codes by what must survive"}],"summary":"Engines, routes, parameters, groups, binding sources, validators, JSON, uploads, templates and 404/405 handling.","title":"Gin foundations","translationNote":"Every example runs against upstream Gin v1.12 through httptest in your native development environment. The app's teaching adapter does not promise every Gin API or network-server capability."},{"id":"gin","lessons":[{"conceptTags":["gin.routing-middleware"],"explanation":"A Gin engine is an HTTP adapter with a middleware chain. Group prefixes and registration order decide which handlers participate; the framework does not supply your business transaction. Follow one request before introducing authentication, metrics or error middleware. In particular, Abort stops pending handlers but does not return from the current Go function.","id":"gin.routing-middleware","objective":"Explain route groups, middleware order and the difference between Abort and return.","task":{"reading":{}},"title":"Gin routing and middleware: follow the chain and stop it deliberately"},{"conceptTags":["gin.binding-limits"],"explanation":"Binding converts a request into a Go value. It does not prove authorization or a business invariant, and it does not by itself impose your desired body-size budget. A robust handler limits input first, chooses whether errors are returned or immediately written, validates normalized values and only then calls the use case. Return one deliberate response instead of letting several layers compete to write it.","id":"gin.binding-limits","objective":"Reject oversized or invalid input before performing a business side effect.","task":{"reading":{}},"title":"Gin input: size limits, binding and business validation are separate"},{"conceptTags":["gin.context-workers"],"explanation":"Gin reuses contexts after a handler returns. Passing the original *gin.Context into a goroutine can observe another request’s mutable state. Copy is useful for limited read-only context access, but it does not extend the response writer’s lifetime, clone every referenced object or give detached work a durable owner. Prefer extracting immutable job input and handing it to a deliberately managed queue.","id":"gin.context-workers","objective":"Give background work a bounded owner without keeping a pooled Gin context alive.","task":{"reading":{}},"title":"Gin contexts and goroutines: extract a job, do not retain the response"},{"conceptTags":["gin.trusted-proxies"],"explanation":"A reverse proxy may supply the original client address, but a direct client can also send X-Forwarded-For. If a Go service trusts forwarding headers from every peer, address-based controls can be bypassed. Configure exactly which proxy origins are trusted and make the edge replace or sanitize incoming forwarding headers. An IP address remains a network observation, not a user credential.","id":"gin.trusted-proxies","objective":"Configure proxy trust explicitly and keep client IP separate from authentication.","task":{"reading":{}},"title":"Trusted proxies: forwarded headers are not proof of identity"},{"conceptTags":["gin.errors-testing"],"explanation":"Framework recovery can keep a panic from crashing a request-serving goroutine, but it cannot undo a committed database write or decide whether a remote operation succeeded. Expected application errors should travel through a deliberate mapping policy. Assign one layer to produce the response, and test both its status and public body rather than checking only that the handler returned.","id":"gin.errors-testing","objective":"Test handler contracts through ServeHTTP without confusing recovery with rollback.","task":{"reading":{}},"title":"Gin errors and tests: one response owner, explicit failure cases"},{"conceptTags":["gin.server-lifecycle"],"explanation":"A router handles requests, while net/http.Server owns listener behavior and connection budgets. A short r.Run example is useful for a tutorial, but a deployed service needs an explicit startup and shutdown owner. Readiness, request admission, long-lived streams, background workers and shared clients must fit the same lifecycle rather than each inventing its own stop signal.","id":"gin.server-lifecycle","objective":"Configure native server timeouts and distinguish HTTP drain from worker completion.","task":{"reading":{}},"title":"Gin in production: the http.Server owns budgets and shutdown"},{"conceptTags":["gin.auth-middleware"],"explanation":"Authentication middleware turns an Authorization header into one of two outcomes before any handler runs: a verified principal, or a refusal the client can act on. The bugs live at the edges of that job: a route registered outside the protected group, a MAC compared with ==, a 403 where the client needed a 401, or a debug log that quietly archives every credential it sees.","id":"gin.auth-middleware","objective":"Write middleware that verifies an HMAC-signed bearer token, stores a typed principal and answers 401 or 403 for the right reasons.","task":{"reading":{}},"title":"Bearer authentication in Gin: verify once at the group boundary, hand handlers a typed principal"},{"conceptTags":["gin.cors"],"explanation":"CORS is the protocol a server uses to tell a browser which other origins may read its responses. It relaxes the same-origin policy; it never tightens it. Done carelessly it either breaks a legitimate front end or lets any website read a signed-in user's data. Done correctly it is still not authentication, authorization or CSRF protection, and the server has to keep enforcing those on its own.","id":"gin.cors","objective":"Implement CORS middleware that answers preflights, echoes only allow-listed origins, sets Vary correctly and is never mistaken for access control.","task":{"reading":{}},"title":"CORS by hand in Gin: an exact origin allow-list, real preflights and Vary: Origin"},{"conceptTags":["gin.rate-limiting"],"explanation":"A rate limiter protects shared capacity from one noisy client. Three decisions matter more than the algorithm: what identifies a client, how much memory the limiter may use, and what a refused client is told. Choose the key badly and an attacker gets a fresh bucket on every request. Forget the memory bound and the limiter becomes the leak it was meant to prevent.","id":"gin.rate-limiting","objective":"Limit each client with golang.org/x/time/rate, pick a key clients cannot forge, bound the limiter map and refuse with 429 and Retry-After.","task":{"reading":{}},"title":"Rate limiting in Gin: a token bucket per identity, a bounded map and an honest Retry-After"},{"conceptTags":["gin.request-logging"],"explanation":"An access log is what you search during an incident. It is only useful if every line carries the same small set of fields, if one request can be followed across services by an ID, and if the log never becomes a second copy of your users' credentials. Gin's built-in Logger prints raw paths with query strings as text, so production services usually replace it with middleware built on log/slog.","id":"gin.request-logging","objective":"Add request-ID middleware and a structured slog access log that records low-cardinality routes, redacts credentials and can be tested byte for byte.","task":{"reading":{}},"title":"Request IDs and access logs in Gin: log the route template and the ID, never the credential"},{"conceptTags":["gin.timeouts-cancellation"],"explanation":"A request stuck on a slow dependency holds a goroutine, a connection and often a database slot. A deadline bounds that wait, but only if every call below the handler receives the context that carries it. Deadlines are cooperative: Go cannot stop a goroutine from outside, so the safe design lets the handler notice expiry and write the response itself instead of racing it from another goroutine.","id":"gin.timeouts-cancellation","objective":"Give each request a deadline that downstream calls inherit, map its expiry to 504, and avoid the timeout patterns that race on the response.","task":{"reading":{}},"title":"Request deadlines in Gin: one context budget, cooperative handlers, no writes from a second goroutine"},{"conceptTags":["gin.streaming-sse"],"explanation":"Server-Sent Events keep one HTTP response open and append small text events to it; the browser's EventSource parses them and reconnects on its own. The protocol is simple, and the engineering is all in the lifecycle. Every event must be flushed through buffers, idle streams need heartbeats, the handler must notice when the client leaves, and the server's write deadline must not cut the stream short.","id":"gin.streaming-sse","objective":"Stream SSE from a Gin handler that flushes events, sends heartbeats, ends when the client leaves and survives http.Server's WriteTimeout.","task":{"reading":{}},"title":"Server-Sent Events in Gin: flush every event, send heartbeats, stop on the request context"},{"conceptTags":["gin.metrics-health"],"explanation":"Health endpoints and request counters are how the platform and the on-call engineer see a service from outside. Each answers a narrow question: should this process be restarted, should it receive traffic right now, and how is each route behaving. Mixing up the first two causes restart storms. Labeling counters with raw paths makes the metrics system the next thing to fall over.","id":"gin.metrics-health","objective":"Separate liveness from readiness, check dependencies within a short budget, and count requests by route template and status class.","task":{"reading":{}},"title":"Health and metrics in Gin: simple liveness, budgeted readiness, counters keyed by route template"},{"conceptTags":["gin.conditional-requests"],"explanation":"A conditional GET lets a client that already holds a copy ask whether it is still current. When it is, the server answers 304 Not Modified with no body, which saves bandwidth and the client's parsing time. The mechanism has three parts: a validator on every response, a comparison on every request, and a Cache-Control policy that decides who may keep a copy. The policy is where private data leaks.","id":"gin.conditional-requests","objective":"Serve ETag and Last-Modified validators, answer conditional requests with 304, and choose Cache-Control so private data never lands in a shared cache.","task":{"reading":{}},"title":"Conditional GETs in Gin: strong ETags from response bytes, 304 Not Modified and safe Cache-Control"}],"summary":"Middleware, bounded input, authentication, CORS, rate limits, logging, timeouts, streaming, health, caching and shutdown.","title":"Gin in production","translationNote":"Worked upstream Gin examples for your native development environment. The app's teaching adapter does not promise every Gin API or network-server capability."},{"id":"gin-project","lessons":[{"conceptTags":["gin.project-layout"],"explanation":"One main.go holding handlers, SQL and business rules works until the first test, the second developer or the second storage backend. This unit grows a single notes API over nine lessons, so this first lesson fixes where each piece lives. Later lessons then add CRUD, pagination, problem details, idempotency and versioning without moving code between packages.","id":"gin.project-layout","objective":"Organize a Gin API into cmd/api, httpapi, notes and store packages whose imports point toward the domain, with all concrete wiring in main.","task":{"reading":{}},"title":"Lay out a Gin service so every import points toward the domain"},{"conceptTags":["gin.handler-dependencies"],"explanation":"A handler that reaches for a package-level database variable works on the first day and fights you afterwards: tests share state, parallel tests race, and no signature tells a reviewer what the handler can touch. Passing dependencies through a constructor makes them visible, replaceable and checked by the compiler. This lesson does that for the notes API, including the clock and the ID source.","id":"gin.handler-dependencies","objective":"Write handlers as methods on a struct built by a constructor, depend on small consumer-defined interfaces and swap in a fake store for tests.","task":{"reading":{}},"title":"Give Gin handlers their dependencies through a struct, not globals or context keys"},{"conceptTags":["gin.crud-resource"],"explanation":"CRUD looks like boilerplate until a client depends on the details: whether create tells it where the new note lives, whether PUT without a body field clears it, whether PATCH with false can unpin a note, and whether a duplicate title is a 400 or a 409. This lesson pins down each answer for the notes resource, on top of a mutex-protected in-memory store behind the Store interface.","id":"gin.crud-resource","objective":"Implement create, read, replace, patch and delete for notes with correct status codes, a Location header and presence-aware PATCH fields.","task":{"reading":{}},"title":"Full CRUD on one resource: exact status codes, a Location header and PUT versus PATCH"},{"conceptTags":["gin.pagination-filtering"],"explanation":"A GET /notes that returns every row is fine with ten notes and an outage with ten million. Pagination bounds the work per request, but the naive offset version skips or repeats rows when data changes between pages, and a sort parameter pasted into SQL is an injection point. This lesson adds listing, filtering and sorting to the notes API with both failure modes closed.","id":"gin.pagination-filtering","objective":"Serve stable pages of notes with keyset cursors, cap the page size and accept only allow-listed filter and sort parameters.","task":{"reading":{}},"title":"Paginate with opaque cursors, a bounded limit and a total order; filter only through allow-lists"},{"conceptTags":["gin.problem-details"],"explanation":"By now each notes handler writes its own gin.H{\"error\": ...}. Clients parse several shapes, someone eventually returns err.Error() and leaks a database host, and nobody can list which statuses an endpoint produces. RFC 9457 supplies a standard envelope. A taxonomy in the domain and one mapping function supply the discipline. The errors-testing lesson established one response owner; this lesson gives that owner a contract.","id":"gin.problem-details","objective":"Return application/problem+json for every failure by mapping a small domain error taxonomy to HTTP statuses in a single Gin middleware.","task":{"reading":{}},"title":"One error envelope: RFC 9457 problem details mapped from domain errors in one middleware"},{"conceptTags":["gin.idempotency-keys"],"explanation":"A mobile client sends POST /notes, the connection drops before the 201 arrives, and the client retries. Without help the server creates a second note. HTTP defines PUT and DELETE as idempotent; POST is not, so the client supplies a unique key and the server promises that one key yields at most one effect and one stored response. This lesson adds that promise to the notes API.","id":"gin.idempotency-keys","objective":"Add Idempotency-Key handling to POST /notes so retries replay the original response, conflicting reuse is rejected and in-flight duplicates wait.","task":{"reading":{}},"title":"Make POST safe to retry with Idempotency-Key: fingerprint, reserve, replay and expire"},{"conceptTags":["gin.optimistic-concurrency"],"explanation":"Two people open the same note. One adds a line; the other fixes the title from the copy loaded earlier, and that second save quietly erases the first edit. Each request was valid on its own. The bug is that the server never asked which version the client was editing. HTTP already has the vocabulary for that question: ETag, If-Match, 412 Precondition Failed and 428 Precondition Required.","id":"gin.optimistic-concurrency","objective":"Version the notes resource, expose the version as an ETag and require If-Match on writes so a stale client cannot overwrite a newer edit.","task":{"reading":{}},"title":"Stop lost updates with versions, ETag and If-Match: 428 when missing, 412 when stale"},{"conceptTags":["gin.api-tests"],"explanation":"Tests that call a handler function directly miss the bugs that live between handlers: middleware order, error mapping, headers and the exact JSON a client parses. Sending requests through the router production uses, with a fake store behind it, tests the API contract in milliseconds. A table turns the next case into a few lines, and asserting whole bodies is what catches the regression that a status check waves through.","id":"gin.api-tests","objective":"Write table-driven tests that send requests through the real Gin router with fakes and assert status, contract headers and semantically compared JSON bodies.","task":{"reading":{}},"title":"Table-driven API tests through the real router: status, headers and JSON compared by meaning"},{"conceptTags":["gin.config-startup"],"explanation":"The last piece of the notes API is the code that runs first. A typo in an environment variable should stop a deploy with a clear message, not start a server with a default timeout, a debug-mode router or a proxy list that trusts the whole internet. This lesson builds the configuration loader, then assembles every package from the earlier lessons in cmd/api/main.go.","id":"gin.config-startup","objective":"Load and validate configuration from the environment, fail fast with every problem listed, and wire store, service, handlers, engine and http.Server with signal-driven shutdown.","task":{"reading":{}},"title":"Start from validated configuration and wire the whole service in one composition root"}],"summary":"Layout, dependencies, CRUD, pagination, problem details, idempotency keys, optimistic concurrency, API tests and startup.","title":"Gin project: a complete REST API","translationNote":"One service grows lesson by lesson. The models run in memory; a deployment adds a database, TLS and observability in your own environment."},{"id":"gin-data","lessons":[{"conceptTags":["gin.context-fallback"],"explanation":"store.Query(c) compiles because *gin.Context implements context.Context, and in a default Gin engine it quietly throws away cancellation, deadlines and tracing values. The context passed to data access decides whether a query stops when its client leaves and whether background work outlives the response. Gin hands you two candidates, and only one of them is a real request context.","id":"gin.context-fallback","objective":"Predict what *gin.Context returns as a context.Context under each ContextWithFallback setting and give stores and background work a context that is actually canceled, or deliberately not.","task":{"reading":{}},"title":"*gin.Context is a pooled struct, not your request context: pass c.Request.Context() to stores and goroutines"},{"conceptTags":["gin.patch-merge"],"explanation":"A client that wants to clear a due date sends {\"due\": null}; a client that only renames a note leaves due out entirely. If the server cannot tell those requests apart, it either ignores the clear or wipes a field nobody mentioned. JSON Merge Patch gives the three cases exact meanings, and Gin's struct binding cannot see one of them.","id":"gin.patch-merge","objective":"Implement an RFC 7396 merge-patch endpoint in Gin that distinguishes absent from null, enforces application/merge-patch+json with 415, and validates the merged result before storing it.","task":{"reading":{}},"title":"PATCH with JSON Merge Patch in Gin: keep absent, null and value apart, then validate the merged resource"},{"conceptTags":["gin.safe-filters"],"explanation":"List endpoints accumulate filters one release at a time: a status here, a search box there, a second sort key for the dashboard. Each one is a chance to splice a value into SQL text, to let a percent sign widen a search, or to send IN () to the database. Build the query in one function that owns every placeholder, and test that function without a database.","id":"gin.safe-filters","objective":"Write a pure function that turns a Gin list request into SQL text and arguments, with allow-listed sorts, a placeholder for every value, escaped LIKE patterns, bounded IN lists and a unique tiebreaker.","task":{"reading":{}},"title":"Gin list filters to parameterized SQL: parse strictly, bound IN lists, escape LIKE, end with a tiebreaker"},{"conceptTags":["gin.batched-includes"],"explanation":"A client asks for /posts?include=author,tags so that it can render a feed in one request. The obvious implementation looks up each post's author inside the loop that builds the response, and a page of fifty posts quietly becomes a hundred and one queries. The cost should depend on how many relations were requested, never on how many rows the page holds.","id":"gin.batched-includes","objective":"Serve optional related data on a Gin list endpoint with one batched lookup per relation, bounded concurrent loads and deterministic output, and prove the query count by counting store calls.","task":{"reading":{}},"title":"?include= without N+1 in Gin: one batched loader per relation, a bounded errgroup and list-order output"},{"conceptTags":["gin.response-cache"],"explanation":"A popular public endpoint renders the same page of articles thousands of times a minute, and each render costs a query and a JSON encode. Caching the finished response inside the service removes that work, but only if the cache never answers differently from the handler: not for another user, not for another query string and not after a write.","id":"gin.response-cache","objective":"Build a Gin middleware that caches public GET responses under a route-template key, never stores per-user responses, coalesces concurrent misses with singleflight and stays correct across writes, TTLs and conditional requests.","task":{"reading":{}},"title":"Cache public GETs in Gin: key by route template, bypass identity, coalesce misses, invalidate on write"},{"conceptTags":["gin.streaming-import"],"explanation":"A bulk import receives the largest bodies your service will ever see, from clients that may have produced part of the file wrong. Reading it whole turns file size into memory, and one bad row into an unexplained 400. Newline-delimited JSON lets the handler work one record at a time: bound the request, bound each line, judge each row on its own, and tell the client exactly which lines were written.","id":"gin.streaming-import","objective":"Build an NDJSON import endpoint that bounds the body and each line, validates rows one at a time and returns a per-line report whose status matches what was written.","task":{"reading":{}},"title":"NDJSON imports in Gin: cap the body, decode one bounded line at a time, report each row by its line number"},{"conceptTags":["gin.streaming-export"],"explanation":"An export of a million rows should cost the server one page of rows at a time, not a million rows of memory and a long silence before the first byte. Writing CSV straight into c.Writer and flushing after every page achieves that. It also changes the error model: once the first page is on the wire the status line has gone, so a database failure on page forty can no longer become a 500, and the handler needs another way to tell the client the file is incomplete.","id":"gin.streaming-export","objective":"Stream a large CSV from a Gin handler page by page with a safe download filename and formula-safe cells, and make a failure after the first byte visible to the client.","task":{"reading":{}},"title":"Streaming CSV exports in Gin: keyset pages, two flushes, formula-safe cells and an abort on late failure"},{"conceptTags":["gin.async-jobs"],"explanation":"Some requests ask for work that takes longer than any sensible request budget: a monthly report, a re-index, a large import. Holding the connection open ties up a goroutine, a proxy slot and the client's patience, and a timeout halfway leaves the client unsure whether anything happened. The asynchronous pattern splits the work from the request: the POST validates and enqueues, answers 202 Accepted with the URL of a job resource, and the client polls that resource until it reports a result or a failure.","id":"gin.async-jobs","objective":"Accept slow work with 202 and a job Location, bound it with a queue and a fixed worker pool, refuse overload with 503 and Retry-After, and keep jobs running after the request ends.","task":{"reading":{}},"title":"Long work behind 202 Accepted in Gin: a bounded queue, fixed workers, a job resource and an honest 503"},{"conceptTags":["gin.webhook-receiver"],"explanation":"A webhook endpoint is a public URL that anyone can POST to, called by a sender that retries whatever it believes failed. Three things matter more than the business logic: proving the request came from the sender unaltered, refusing old requests replayed by someone who captured one, and processing each event once although it may arrive several times. The status code is an instruction to the sender's retry machinery, so choose it as carefully as the verification.","id":"gin.webhook-receiver","objective":"Receive signed webhooks in Gin by authenticating the raw body before binding, rejecting replays, deduplicating deliveries and choosing status codes that make the sender retry only when a retry can help.","task":{"reading":{}},"title":"Signed webhooks in Gin: verify the raw bytes, reject stale timestamps, dedupe event IDs, answer fast"}],"summary":"Request contexts, JSON Merge Patch, safe filters, batched includes, response caches, streaming import and export, async jobs and signed webhooks.","title":"Gin and your data","translationNote":"Stores are in-memory models driven through httptest. Point the same handlers at your own isolated database in a native development environment."},{"id":"gin-edge","lessons":[{"conceptTags":["gin.upstream-clients"],"explanation":"Most Gin services are also HTTP clients: they call a payment provider, an inventory service or a search cluster while their own caller waits. Every such call borrows the caller's time, a pooled connection and memory for the reply. Done naively, one slow or misbehaving upstream turns into piled-up goroutines, exhausted sockets and error responses that quote another team's database errors to your users.","id":"gin.upstream-clients","objective":"Call an upstream HTTP API from a Gin handler through a shared, budgeted http.Client and map every failure to your own 404, 502 or 504 without leaking upstream details.","task":{"reading":{}},"title":"Upstream calls from Gin: one shared client, the request deadline, a bounded body and your own error codes"},{"conceptTags":["gin.retries-breakers"],"explanation":"A retry turns a transient failure into a success and a persistent failure into extra load at the worst possible moment. Whether a retry helps depends on three questions: is it safe to send the request twice, is the failure likely to clear soon, and how much extra traffic is the fleet already sending. This lesson builds the client side of those answers behind a Gin handler, with a seeded random source and an injected clock so every wait is reproducible.","id":"gin.retries-breakers","objective":"Wrap upstream calls in a retry policy that respects idempotency, Retry-After and a shared budget, and use a circuit breaker so Gin answers 503 quickly while a dependency is down.","task":{"reading":{}},"title":"Retrying upstream calls from Gin: only when safe, jittered backoff, a retry budget and a circuit breaker"},{"conceptTags":["gin.compression"],"explanation":"JSON, CSV and HTML often shrink several times under gzip, which matters on mobile links and metered egress. A compression middleware sits between every handler and the network, so its bugs appear everywhere at once: a missing Vary header serves gzip to a client that cannot read it, a stale Content-Length truncates bodies, a compressed event stream stalls, and a page that mixes a secret with reflected input becomes a BREACH oracle.","id":"gin.compression","objective":"Write a gzip middleware for Gin that negotiates Accept-Encoding correctly and skips responses that must not be compressed, and accept gzip request bodies without a decompression-bomb hole.","task":{"reading":{}},"title":"Gzip in Gin by hand: negotiate q-values, wrap the writer, add Vary and know what never to compress"},{"conceptTags":["gin.downloads-ranges"],"explanation":"A download endpoint looks like one line, c.File(path), and that line hides most of the behavior: byte ranges for resumed and parallel downloads, conditional requests, HEAD, the content type and the filename the browser saves. Knowing what Gin delegates to net/http and what it adds decides whether a large export resumes after a dropped connection or starts over, and whether a user-chosen filename can break the response header.","id":"gin.downloads-ranges","objective":"Serve downloadable files from Gin with correct Range, If-Range, ETag and HEAD behavior, a Content-Disposition built by mime.FormatMediaType and file access confined to an os.Root.","task":{"reading":{}},"title":"File downloads in Gin: ServeContent for ranges and validators, a safe Content-Disposition, files opened by ID"},{"conceptTags":["gin.content-negotiation"],"explanation":"Content negotiation lets one URL return the representation each client prefers: JSON for an API client, CSV for a spreadsheet import, HTML for a browser. Gin offers c.NegotiateFormat and c.Negotiate for this, and reading their v1.12.0 source shows that they implement much less of the HTTP rules than their names suggest. The gaps are easy to close, but only once you know where they are.","id":"gin.content-negotiation","objective":"Serve JSON, CSV and HTML from one Gin handler with q-value-aware negotiation, a 406 that lists what is available, Vary: Accept for caches and a ?format= override where URLs must name the representation.","task":{"reading":{}},"title":"Content negotiation in Gin: what NegotiateFormat really matches, 406 in your format and Vary: Accept"},{"conceptTags":["gin.api-versioning"],"explanation":"A breaking change to a response shape cannot be deployed in place: some clients will keep sending yesterday's requests for months. The route-groups lesson put /v1 and /v2 groups side by side. This lesson adds what makes a second version manageable: a domain type that belongs to neither version, adapters that own each wire shape, standard headers that tell clients when v1 ends, and a route-table test that stops anyone from deleting v1 early.","id":"gin.api-versioning","objective":"Serve two API versions from one service through per-version DTO adapters, mark v1 with Deprecation, Sunset and successor-version links, and test that v1 routes survive until the announced date.","task":{"reading":{}},"title":"API versions in Gin: one service under /v1 and /v2, an adapter per version, and a v1 that announces its sunset"},{"conceptTags":["gin.contract-drift"],"explanation":"An OpenAPI document is a promise that clients, generated SDKs and gateway configurations build on, while the router is what actually answers. Nothing connects the two unless you write the check: a handler added on Friday never reaches the document, an operation deleted from code lingers in the SDK, and a handler that starts returning 422 contradicts a spec that says 400. A small test that reads both sides and prints sorted differences keeps them together.","id":"gin.contract-drift","objective":"Write a test that converts engine.Routes() to OpenAPI path templates, reports routes and operations that exist on only one side, and checks recorded status codes against declared responses.","task":{"reading":{}},"title":"Keep the OpenAPI document and the Gin router honest: diff routes, operations and status codes in a test"},{"conceptTags":["gin.admin-listener"],"explanation":"A CPU profile or a goroutine dump from a live process can end an incident in minutes, so production services should be able to produce them. The same endpoints in the wrong hands publish the command line, internal function names and memory statistics, and let anyone start a 30-second CPU profile on demand. The safe arrangement is structural: a second Gin engine that serves only diagnostics, hosted by its own http.Server on an address the internet cannot reach.","id":"gin.admin-listener","objective":"Mount net/http/pprof and expvar on an admin-only Gin engine behind a network and token guard, and prove with httptest that the public engine does not serve them.","task":{"reading":{}},"title":"Debug endpoints in Gin: pprof and expvar on a separate admin engine and listener, never on the public router"},{"conceptTags":["gin.release-builds"],"explanation":"The binary you test with go run is not the one you ship. A release build differs in Gin's mode, in what the toolchain stamps into the executable, in how it links and in the image around it. Each difference has a failure attached: request headers in debug logs, an incident where nobody can say which commit is running, a container that will not start because a C library is missing. This lesson follows the build from the mode switch to the final image.","id":"gin.release-builds","objective":"Build a Gin service for production with release mode, -trimpath, -ldflags -X and CGO_ENABLED=0, report its identity from runtime/debug build info, and package it in a minimal non-root image.","task":{"reading":{}},"title":"Shipping a Gin binary: release mode, a /version endpoint from build info, static builds and a non-root image"},{"conceptTags":["gin.rolling-deploys"],"explanation":"During a rolling deploy every old replica is told to stop while traffic is still arriving. Calling Shutdown the moment SIGTERM lands closes the listener before every load balancer has heard the replica is leaving, and the requests they still send meet a refused connection. The fix is an ordered sequence with one owner, and because it is about time and ordering, it should be modeled with an injected clock and tested like any other code.","id":"gin.rolling-deploys","objective":"Implement and test a SIGTERM sequence that flips readiness to 503, keeps serving while load balancers stop routing, disables keep-alives, and shuts the http.Server down within a grace period the platform honors.","task":{"reading":{}},"title":"Surviving a rolling deploy in Gin: fail readiness, keep serving through a drain delay, then Shutdown"}],"summary":"Upstream clients, retries and circuit breakers, compression, ranged downloads, content negotiation, versioning, contract tests, admin endpoints, release builds and rolling deploys.","title":"Gin in the wider system","translationNote":"Upstreams, listeners and signals are modeled in-process. Real deployments, load balancers and clusters belong to your own environment."}]}