Standard Library, HTTP & Systems Design in Go·Q443·Medium
http.Server.Serve runs an accept loop; for every accepted net.Conn it starts one goroutine ( go c.serve(ctx) ). With HTTP/1.1 keep-alive, that goroutine reads requests…
Standard Library, HTTP & Systems Design in Go·Q444·Medium
Since Go 1.22, patterns have the form [METHOD ][HOST]/[PATH] : "GET /items/{id}" — method + a single-segment wildcard, read via r.PathValue("id") . GET also matches HEAD…
Standard Library, HTTP & Systems Design in Go·Q445·Hard
Middleware is just func(http.Handler) http.Handler . To capture the status you wrap the ResponseWriter . The pitfall: the concrete writer implements optional interfaces…
Standard Library, HTTP & Systems Design in Go·Q446·Hard
The package-level helper creates an http.Server with zero timeouts , meaning a client can hold a connection forever (Slowloris: dribble headers one byte at a time and…
Standard Library, HTTP & Systems Design in Go·Q447·Hard
Pooling lives in http.Transport , not Client . The Transport keeps idle keep-alive connections keyed by scheme+host+proxy. Both are safe for concurrent use and should be…
Standard Library, HTTP & Systems Design in Go·Q448·Medium
The body is a stream over the underlying connection. Until it is closed, the Transport cannot reuse or free the connection — forgetting Close leaks a goroutine and a…
Standard Library, HTTP & Systems Design in Go·Q449·Medium
Server: each request carries r.Context() , which is canceled when the client closes the connection, when an HTTP/2 stream is reset, or when ServeHTTP returns. Pass it to…
Standard Library, HTTP & Systems Design in Go·Q450·Medium
func h(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello")) w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) } The…
Standard Library, HTTP & Systems Design in Go·Q451·Hard
type Addr struct{ City string } type User struct { Name string `json:"name"` password string // unexported Age int `json:"age,omitempty"` Tags []string…
Standard Library, HTTP & Systems Design in Go·Q452·Hard
var m map[string]any json.Unmarshal([]byte(`{"id": 12345678901234567890, "n": 1}`), &m) fmt.Printf("%T %v\n", m["n"], m["id"]) _, ok := m["n"].(int) fmt.Println(ok)…
Standard Library, HTTP & Systems Design in Go·Q453·Hard
If MarshalJSON has a pointer receiver , only *T implements json.Marshaler . Marshaling a non-addressable T value (e.g. json.Marshal(t) , a value in a map, or a value…
Standard Library, HTTP & Systems Design in Go·Q454·Medium
Unmarshal works on a complete []byte and fails if there is trailing garbage. Decoder reads from an io.Reader , buffers internally, and can decode a stream of values…
Standard Library, HTTP & Systems Design in Go·Q455·Medium
type Resp struct { Items []int `json:"items"` Meta map[string]int `json:"meta"` Ptr *int `json:"ptr"` } var a []int b := []int{} x, _ := json.Marshal(Resp{Items: a}) y,…
Standard Library, HTTP & Systems Design in Go·Q456·Hard
*sql.DB is not a connection — it is a concurrency-safe pool , created once with sql.Open (which doesn't even connect; call PingContext ). Each query checks out a…
Standard Library, HTTP & Systems Design in Go·Q457·Medium
Transactions pin a single connection; all statements must use the *sql.Tx , not db (using db inside a tx runs on another connection and can deadlock with…
Standard Library, HTTP & Systems Design in Go·Q458·Hard
for { n, err := r.Read(buf) if err != nil { break } process(buf[:n]) } The contract: Read may return n > 0 and a non-nil error in the same call (including io.EOF ).…
Standard Library, HTTP & Systems Design in Go·Q459·Hard
The power of io.Reader / io.Writer is composition: io.TeeReader (read and copy to a writer), io.MultiWriter (fan-out writes), io.LimitReader , io.Pipe (connect a…
Standard Library, HTTP & Systems Design in Go·Q460·Medium
Scanner: the default max token size is 64 KB ( bufio.MaxScanTokenSize ). A longer line makes Scan() return false, and unless you check sc.Err() (which is…
Standard Library, HTTP & Systems Design in Go·Q461·Hard
Goal: on SIGINT/SIGTERM (Kubernetes sends SIGTERM, then SIGKILL after the grace period), stop accepting connections, let in-flight requests finish, stop workers, and…
Standard Library, HTTP & Systems Design in Go·Q462·Medium
log/slog (Go 1.21) separates the front-end *slog.Logger from a pluggable slog.Handler ( TextHandler , JSONHandler , or third-party). Records have a time, level, message…
Standard Library, HTTP & Systems Design in Go·Q463·Hard
t1 := time.Now() t2 := t1.Round(0) // strips monotonic reading fmt.Println(t1 == t2, t1.Equal(t2)) loc, _ := time.LoadLocation("Asia/Kolkata") t3 := t2.In(loc)…
Standard Library, HTTP & Systems Design in Go·Q464·Hard
A time.Ticker fires until you call Stop() ; always defer t.Stop() . Before Go 1.23, an unstopped Ticker/Timer was never garbage-collected, and time.After inside a hot…
Standard Library, HTTP & Systems Design in Go·Q465·Medium
retries := 3 // d := retries * time.Second // compile error: mismatched types int and time.Duration d := time.Duration(retries) * time.Second fmt.Println(d) const n = 3…
Standard Library, HTTP & Systems Design in Go·Q466·Hard
type Config struct { Port int host string } c := Config{Port: 80} v := reflect.ValueOf(c) fmt.Println(v.Field(0).CanSet()) p := reflect.ValueOf(&c).Elem()…
Standard Library, HTTP & Systems Design in Go·Q467·Hard
This tests walking struct fields, reading tags, handling pointers and Kinds, and producing errors with errors.Join . func Validate(s any) error { v := reflect.ValueOf(s)…
Standard Library, HTTP & Systems Design in Go·Q468·Hard
Token bucket: capacity b tokens, refilled at r per second; each request consumes one; allows bursts up to b . Compute tokens lazily from elapsed time — no background…
Standard Library, HTTP & Systems Design in Go·Q469·Hard
Classic O(1) LRU: a hash map from key to a node in a doubly linked list ( container/list ); move to front on access, evict from back when over capacity. TTL is checked…
Standard Library, HTTP & Systems Design in Go·Q470·Medium
When a hot key expires, hundreds of concurrent requests all miss and hit the database simultaneously (thundering herd). golang.org/x/sync/singleflight deduplicates…
Standard Library, HTTP & Systems Design in Go·Q471·Hard
Requirements: topics, concurrent publish, subscribe/unsubscribe at any time, and a publisher must never block on a slow consumer. Each subscriber gets a buffered channel…
Standard Library, HTTP & Systems Design in Go·Q472·Hard
golang.org/x/sync/errgroup is the idiomatic tool: WithContext cancels the shared context on the first error, SetLimit bounds concurrency, and Wait returns the first…
Standard Library, HTTP & Systems Design in Go·Q473·Medium
For handlers , use httptest.NewRecorder() and httptest.NewRequest — no network, fast, and you inspect the recorded status, headers and body. Route through your real mux…
Standard Library, HTTP & Systems Design in Go·Q474·Hard
SSE is a long-lived text/event-stream response where the server writes data: ...\n\n frames and flushes each one. Two things usually break it: (1) a middleware wrapper…
Standard Library, HTTP & Systems Design in Go·Q475·Hard
Retry only idempotent requests (GET, HEAD, PUT, DELETE, or POST with an idempotency key), and only on transient failures: network errors, 429, 502/503/504. A request…
Standard Library, HTTP & Systems Design in Go·Q476·Hard
httputil.ReverseProxy handles hop-by-hop header removal, streaming, trailers, HTTP/2, protocol upgrades (WebSockets) and error handling. Go 1.20 added the Rewrite hook,…
Standard Library, HTTP & Systems Design in Go·Q477·Hard
Tests using real time.Sleep are slow and flaky. testing/synctest (experimental in 1.24 behind GOEXPERIMENT=synctest , stable in Go 1.25 as synctest.Test ) runs a…