The net/http package provides production-grade HTTP clients and servers—no framework required for simple APIs. Compare with Express in Node.js or Spring in Java.
Handler pattern
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "ok")
})
http.ListenAndServe(":8080", nil)
Handlers receive ResponseWriter and *Request. Use http.Server with timeouts in production—not the default zero timeouts.
Playground note
Long-running servers need local setup—this lesson prints handler concepts; run go run . locally to test with curl.
Important interview questions and answers
- Q: Default ServeMux?
A:http.DefaultServeMux—prefer explicit mux in production to avoid accidental route registration. - Q: Context in handlers?
A: User.Context()for cancellation tied to client disconnect.
Self-check
- Which function registers a route on DefaultServeMux?
- Why set Server ReadTimeout?
Tip: Set ReadHeaderTimeout and ReadTimeout on http.Server—defaults allow slowloris-style resource exhaustion.
Interview prep
- Default ServeMux risks?
Global registration—prefer explicit mux in production to avoid accidental routes.
- Handler context?
Use r.Context() for cancellation when client disconnects.