Net HTTP Essentials
Built-in HTTP server and client idioms. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Search across all documentation pages
Built-in HTTP server and client idioms. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Register a path handler on DefaultServeMux.
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
})
// GET /health -> okExplicit Server for timeouts.
srv := &http.Server{
Addr: ":8080",
ReadHeaderTimeout: 5 * time.Second,
}
// err := srv.ListenAndServe()Outbound requests with context.
// req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
// res, err := http.DefaultClient.Do(req)
// defer res.Body.Close()Wrap Handler for cross-cutting behavior.
func withLog(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
next.ServeHTTP(w, r)
})
}Decode and encode JSON bodies.
// json.NewDecoder(r.Body).Decode(&in)
// json.NewEncoder(w).Encode(out)Method + path patterns on ServeMux (Go 1.22+).
// mux.HandleFunc("GET /items/{id}", h)
// id := r.PathValue("id")Set response headers before write.
// w.Header().Set("Content-Type", "application/json")
// w.WriteHeader(http.StatusCreated)Parse query and form fields.
// _ = r.ParseForm()
// q := r.FormValue("q")Read and write cookies.
// http.SetCookie(w, &http.Cookie{Name: "s", Value: "x", Path: "/"})Client redirect helper.
// http.Redirect(w, r, "/login", http.StatusFound)Serve static files.
// http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))Bound handler duration.
// http.TimeoutHandler(h, 2*time.Second, "timeout")Unit-test handlers with httptest.
// rr := httptest.NewRecorder()
// h.ServeHTTP(rr, req)
// rr.Code == 200Always close client response bodies.
// defer res.Body.Close()Graceful shutdown with context.
// _ = srv.Shutdown(ctx)Stack versions: Go 1.26.x · chi/gin/echo latest (verify at build)
Reviewed by Chris St. John·Last updated Jul 19, 2026