These are the notes for Go episode 61. Raju wants his menu online, and browsers speak HTTP. We first look at the raw text a real HTTP client sends over TCP and answer it by hand, see why nobody does that, and then build the server the Go way: the http.Handler interface, http.HandlerFunc, the http.ServeMux router with Go 1.22 patterns and r.PathValue, query and form values, status codes and headers in the right order, http.FileServer, http.ListenAndServe, and tests with httptest.
All outputs are from real runs (Go 1.24.7, linux/amd64). Ports and log timestamps change between runs.
Facts and sources
- Routing Enhancements for Go 1.22 (go.dev blog): Go 1.22 "brings two enhancements to the
net/httppackage's router: method matching and wildcards". A trailing...wildcard (/files/{pathname...}) matches "all the remaining segments of the path";req.PathValue("id")returns a wildcard's value; when the method doesn't match, the server replies405 Method Not Allowedwith anAllowheader; the most specific pattern wins (/posts/latestbeats/posts/{id}); two overlapping patterns where neither is more specific conflict, and registering both panics. - Everything else is from the real runs below.
What HTTP really sends
HTTP (HyperText Transfer Protocol) is a set of text rules carried over a TCP connection (episode 60). Real-life example: a letter to the restaurant.
| Letter | HTTP | Example |
|---|---|---|
| "Please send: the menu" | request line: method + path + version | GET /menu HTTP/1.1 |
| notes on the envelope | headers: Name: value lines |
Host: 127.0.0.1:38677 |
| the letter inside | body (optional) | a posted form |
| the reply's stamp | status code | 200 OK, 404 Not Found |
A method is the action: GET fetches, POST sends data, PUT/PATCH change, DELETE removes, HEAD is GET without the body. The path names the thing (/menu).
package main
import (
"bufio"
"fmt"
"io"
"net"
"net/http"
"strings"
)
func main() {
ln, _ := net.Listen("tcp", "127.0.0.1:0") // a plain TCP server
go func() {
c, _ := ln.Accept()
defer c.Close()
r := bufio.NewReader(c)
for { // print what the client really sent, line by line
line, _ := r.ReadString('\n')
if line == "\r\n" {
break // an empty line ends the headers
}
fmt.Printf(" client sent: %q\n", line)
}
body := "masala chai ₹20\n"
fmt.Fprintf(c, "HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: %d\r\n\r\n%s", len(body), body)
}()
resp, err := http.Get("http://" + ln.Addr().String() + "/menu") // a real HTTP client
if err != nil {
fmt.Println(err)
return
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
fmt.Println("status:", resp.Status, "| type:", resp.Header.Get("Content-Type"))
fmt.Println("body:", strings.TrimSpace(string(b)))
}
Real output:
client sent: "GET /menu HTTP/1.1\r\n"
client sent: "Host: 127.0.0.1:38677\r\n"
client sent: "User-Agent: Go-http-client/1.1\r\n"
client sent: "Accept-Encoding: gzip\r\n"
status: 200 OK | type: text/plain; charset=utf-8
body: masala chai ₹20
Hostis the address the client asked for;User-Agentnames the client program;Accept-Encoding: gzipsays it accepts compressed replies.- Every line ends with
\r\n; an empty line ends the headers. - The reply: a status line (
HTTP/1.1 200 OK), headers (Content-Type,Content-Length= the body size in bytes:₹alone is 3 bytes in UTF-8), an empty line, then the body.
Doing this by hand for every page means handling keep-alive, chunked bodies, HTTP/2, malformed requests and much more. net/http does all of it.
http.Handler and http.HandlerFunc
type Handler interface {
ServeHTTP(ResponseWriter, *Request)
}
Real-life example: the server is the doorman who opens every letter; a Handler is the cook who knows one job; w (http.ResponseWriter) is the reply pad; r (*http.Request) is the parsed order slip (r.Method, r.URL, r.Header, r.Body, r.Context()).
http.HandlerFunc is a function type with a ServeHTTP method that calls the function itself, so http.HandlerFunc(f) turns any func(http.ResponseWriter, *http.Request) into a Handler.
package main
import (
"fmt"
"net/http"
"net/http/httptest"
)
// menu is a Handler: anything with a ServeHTTP method.
type menu struct{ prices map[string]int }
func (m menu) ServeHTTP(w http.ResponseWriter, r *http.Request) {
for item, p := range m.prices {
fmt.Fprintf(w, "%s ₹%d\n", item, p)
}
}
// hello is a plain function with the same shape...
func hello(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to Raju's! You asked for %s %s\n", r.Method, r.URL.Path)
}
func main() {
var h http.Handler = menu{prices: map[string]int{"masala chai": 20}}
var g http.Handler = http.HandlerFunc(hello) // ...made into a Handler
for _, x := range []http.Handler{h, g} {
rec := httptest.NewRecorder() // a fake ResponseWriter that remembers
req := httptest.NewRequest("GET", "/menu", nil)
x.ServeHTTP(rec, req)
fmt.Printf("%d %q\n", rec.Code, rec.Body.String())
}
}
Real output:
200 "masala chai ₹20\n"
200 "Welcome to Raju's! You asked for GET /menu\n"
httptest.NewRecorder() is a fake ResponseWriter that records the status (rec.Code), headers and body; httptest.NewRequest builds a request without a network. If you never call WriteHeader, the first write sends 200 OK.
http.ServeMux and Go 1.22 patterns
A router (multiplexer, "mux") picks which handler gets each request by matching patterns. http.ServeMux is the standard one, and it is itself a Handler.
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
)
var prices = map[string]int{"1": 20, "2": 25}
func main() {
mux := http.NewServeMux() // the router: pattern -> handler
mux.HandleFunc("GET /menu", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "1 masala chai ₹20, 2 ginger chai ₹25")
})
mux.HandleFunc("GET /menu/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id") // the part of the path matched by {id}
p, ok := prices[id]
if !ok {
http.Error(w, "no item "+id, http.StatusNotFound)
return
}
fmt.Fprintf(w, "item %s costs ₹%d\n", id, p)
})
mux.HandleFunc("GET /photos/{path...}", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "photo file:", r.PathValue("path"))
})
srv := httptest.NewServer(mux) // a real server on a free port, for testing
defer srv.Close()
for _, t := range []string{"GET /menu", "GET /menu/2", "GET /menu/9",
"GET /photos/diwali/stall.jpg", "DELETE /menu", "GET /bill"} {
method, path, _ := strings.Cut(t, " ")
req, _ := http.NewRequest(method, srv.URL+path, nil)
resp, _ := http.DefaultClient.Do(req)
b, _ := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Printf("%-28s -> %d %s", t, resp.StatusCode, b)
if a := resp.Header.Get("Allow"); a != "" {
fmt.Printf("%-32s Allow: %s\n", "", a)
}
}
}
Real output:
GET /menu -> 200 1 masala chai ₹20, 2 ginger chai ₹25
GET /menu/2 -> 200 item 2 costs ₹25
GET /menu/9 -> 404 no item 9
GET /photos/diwali/stall.jpg -> 200 photo file: diwali/stall.jpg
DELETE /menu -> 405 Method Not Allowed
Allow: GET, HEAD
GET /bill -> 404 404 page not found
Pattern rules (Go 1.22+): [METHOD ][HOST]/path, with wildcards in braces.
| Pattern | Matches | Notes |
|---|---|---|
GET /menu |
GET /menu (and HEAD /menu) |
method patterns; a wrong method → 405 + Allow |
GET /menu/{id} |
/menu/2, not /menu/1/extra |
{id} is exactly one segment; r.PathValue("id") |
GET /photos/{path...} |
/photos/diwali/stall.jpg |
... = all remaining segments |
/static/ |
everything below /static/ |
a trailing slash matches the whole subtree |
/{$} |
only / |
{$} = end of path |
/menu/latest vs /menu/{id} |
/menu/latest wins |
most specific wins |
/posts/{id} + /{resource}/latest |
— | conflict: panics at registration |
mux.HandleFunc(pattern, f) registers a function; mux.Handle(pattern, h) registers a Handler. http.Error(w, msg, code) writes a plain-text error with that status. Before Go 1.22 the standard mux had no methods or wildcards, which is why routers like chi and gorilla/mux became popular (episode 65 compares them).
Input and output: query, forms, status and headers
- The query string is the part of the URL after
?:/search?q=ginger+chai.r.URL.Query().Get("q")returns"ginger chai"(+decodes to a space). r.FormValue("item")reads a field from a posted form (application/x-www-form-urlencodedor multipart) or the query;r.PostFormValuereads only the body.http.PostForm(url, values)is the client side.- A status code tells the client what happened:
200 OK,201 Created,204 No Content,400 Bad Request,404 Not Found,405 Method Not Allowed,500 Internal Server Error. Use thehttp.StatusXxxconstants. - Order matters: headers → status → body.
w.Header().Set(...), thenw.WriteHeader(code), thenw.Write/fmt.Fprintf(w, ...). The first write sends the status and headers; later changes are ignored.
package main
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
)
func search(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query().Get("q") // ?q=ginger -> "ginger"
fmt.Fprintf(w, "searching for %q\n", q)
}
func order(w http.ResponseWriter, r *http.Request) {
item := r.FormValue("item") // from the posted form (or the query)
if item == "" {
http.Error(w, "item is required", http.StatusBadRequest) // 400
return
}
w.Header().Set("Content-Type", "text/plain; charset=utf-8") // headers first
w.Header().Set("Location", "/orders/42")
w.WriteHeader(http.StatusCreated) // then the status: 201
fmt.Fprintf(w, "order 42: %s\n", item) // then the body
}
func late(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "oops") // writing the body sends 200 OK right away
w.WriteHeader(http.StatusTeapot)
w.Header().Set("X-Too-Late", "yes")
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /search", search)
mux.HandleFunc("POST /orders", order)
mux.HandleFunc("GET /late", late)
srv := httptest.NewServer(mux)
defer srv.Close()
r1, _ := http.Get(srv.URL + "/search?q=ginger+chai")
r2, _ := http.PostForm(srv.URL+"/orders", url.Values{"item": {"2 samosa"}})
r3, _ := http.PostForm(srv.URL+"/orders", url.Values{})
r4, _ := http.Get(srv.URL + "/late")
for _, resp := range []*http.Response{r1, r2, r3, r4} {
b, _ := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Printf("%d %-24s | Location=%q X-Too-Late=%q\n", resp.StatusCode, strings.TrimSpace(string(b)),
resp.Header.Get("Location"), resp.Header.Get("X-Too-Late"))
}
}
Real output (stdout, then the server's log on stderr):
200 searching for "ginger chai" | Location="" X-Too-Late=""
201 order 42: 2 samosa | Location="/orders/42" X-Too-Late=""
400 item is required | Location="" X-Too-Late=""
200 oops | Location="" X-Too-Late=""
2026/11/13 05:41:04 http: superfluous response.WriteHeader call from main.late (main.go:31)
late wrote the body first, so the client got 200 (not 418, http.StatusTeapot) and no X-Too-Late header, and the server logged a superfluous WriteHeader warning. The Location header on a 201 tells the client where the new thing lives.
http.FileServer and http.ListenAndServe
package main
import (
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
)
func main() {
dir, _ := os.MkdirTemp("", "static") // a folder with the shop's files
os.WriteFile(filepath.Join(dir, "menu.txt"), []byte("masala chai ₹20\n"), 0o644)
mux := http.NewServeMux()
files := http.FileServer(http.Dir(dir)) // serves files from that folder
mux.Handle("GET /static/", http.StripPrefix("/static/", files))
srv := httptest.NewServer(mux)
defer srv.Close()
for _, p := range []string{"/static/menu.txt", "/static/secret.txt"} {
resp, _ := http.Get(srv.URL + p)
b, _ := io.ReadAll(resp.Body)
resp.Body.Close()
fmt.Printf("%-20s %d %s %q\n", p, resp.StatusCode, resp.Header.Get("Content-Type"), b)
}
busy, _ := net.Listen("tcp", ":8080") // someone already uses port 8080
defer busy.Close()
err := http.ListenAndServe(":8080", mux) // normally blocks forever
fmt.Println("ListenAndServe returned:", err)
}
Real output:
/static/menu.txt 200 text/plain; charset=utf-8 "masala chai ₹20\n"
/static/secret.txt 404 text/plain; charset=utf-8 "404 page not found\n"
ListenAndServe returned: listen tcp :8080: bind: address already in use
http.FileServer(http.Dir(dir))serves the files insidedir(content type from the file name; it refuses paths that climb out of the folder with..).http.StripPrefix("/static/", h)removes the prefix beforehsees the path, so/static/menu.txt→menu.txt.http.ListenAndServe(addr, handler)listens onaddrand serves forever; it returns only on failure, so the usual form islog.Fatal(http.ListenAndServe(":8080", mux)).nilas the handler meanshttp.DefaultServeMux(prefer your own mux).":8080"means port 8080 on every network interface;"127.0.0.1:8080"only on loopback.- The default server has no timeouts: episode 62 fixes that with
http.Server.
Testing handlers with httptest
// $ go test -v
// ---- menu.go ----
package shop
import (
"fmt"
"net/http"
)
func Item(w http.ResponseWriter, r *http.Request) {
switch id := r.PathValue("id"); id {
case "1":
fmt.Fprintln(w, "masala chai ₹20")
default:
http.Error(w, "no item "+id, http.StatusNotFound)
}
}
// ---- menu_test.go ----
package shop
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestItem(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("GET /menu/{id}", Item)
for _, tc := range []struct {
path string
want int
}{{"/menu/1", 200}, {"/menu/7", 404}, {"/menu/1/extra", 404}} {
rec := httptest.NewRecorder() // no network at all
mux.ServeHTTP(rec, httptest.NewRequest("GET", tc.path, nil))
if rec.Code != tc.want {
t.Errorf("%s: got %d, want %d", tc.path, rec.Code, tc.want)
}
t.Logf("%-14s %d %q", tc.path, rec.Code, rec.Body.String())
}
}
Real output:
$ go test -v
=== RUN TestItem
menu_test.go:21: /menu/1 200 "masala chai ₹20\n"
menu_test.go:21: /menu/7 404 "no item 7\n"
menu_test.go:21: /menu/1/extra 404 "404 page not found\n"
--- PASS: TestItem (0.00s)
PASS
ok shop 0.005s
| Tool | What it is | Use it for |
|---|---|---|
httptest.NewRecorder() |
a fake ResponseWriter |
testing one handler or mux directly: fast, no network |
httptest.NewRequest(method, target, body) |
a server-side request without a network | input for ServeHTTP |
httptest.NewServer(h) |
a real HTTP server on a free loopback port (srv.URL) |
testing clients, middleware, real connections |
Mini project: Raju's menu server
GET /menu,GET /menu/{id}(404 if missing).POST /orderswith a form: 400 if no item, otherwise 201 +Location.GET /orders/{id}returns the saved order.GET /static/serves a photos folder.- A table test for every route.
Solution
menu.go:
// Raju's menu server (Go episode 61 mini project).
package main
import (
"fmt"
"log"
"net/http"
"strconv"
"sync"
)
type Shop struct {
mu sync.Mutex
menu map[string]int // id -> price
names map[string]string
orders map[int]string
next int
}
func NewShop() *Shop {
return &Shop{
menu: map[string]int{"1": 20, "2": 25},
names: map[string]string{"1": "masala chai", "2": "ginger chai"},
orders: map[int]string{},
next: 1,
}
}
func (s *Shop) Routes(static string) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /menu", s.listMenu)
mux.HandleFunc("GET /menu/{id}", s.item)
mux.HandleFunc("POST /orders", s.createOrder)
mux.HandleFunc("GET /orders/{id}", s.getOrder)
mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.Dir(static))))
return mux
}
func (s *Shop) listMenu(w http.ResponseWriter, r *http.Request) {
for _, id := range []string{"1", "2"} {
fmt.Fprintf(w, "%s %s ₹%d\n", id, s.names[id], s.menu[id])
}
}
func (s *Shop) item(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
p, ok := s.menu[id]
if !ok {
http.Error(w, "no item "+id, http.StatusNotFound)
return
}
fmt.Fprintf(w, "%s ₹%d\n", s.names[id], p)
}
func (s *Shop) createOrder(w http.ResponseWriter, r *http.Request) {
item := r.FormValue("item")
if item == "" {
http.Error(w, "item is required", http.StatusBadRequest)
return
}
s.mu.Lock() // many requests run at once: protect the map
id := s.next
s.next++
s.orders[id] = item
s.mu.Unlock()
w.Header().Set("Location", "/orders/"+strconv.Itoa(id))
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, "order %d: %s\n", id, item)
}
func (s *Shop) getOrder(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
http.Error(w, "order id must be a number", http.StatusBadRequest)
return
}
s.mu.Lock()
item, ok := s.orders[id]
s.mu.Unlock()
if !ok {
http.NotFound(w, r)
return
}
fmt.Fprintf(w, "order %d: %s\n", id, item)
}
func main() {
shop := NewShop()
log.Println("Raju's menu on http://localhost:8080/menu")
log.Fatal(http.ListenAndServe(":8080", shop.Routes("photos")))
}
menu_test.go:
package main
import (
"net/http/httptest"
"net/url"
"strings"
"testing"
)
func TestRoutes(t *testing.T) {
h := NewShop().Routes(t.TempDir())
form := url.Values{"item": {"2 samosa"}}.Encode()
for _, tc := range []struct {
method, path, body string
want int
}{
{"GET", "/menu", "", 200},
{"GET", "/menu/2", "", 200},
{"GET", "/menu/9", "", 404},
{"DELETE", "/menu", "", 405},
{"HEAD", "/menu", "", 200},
{"POST", "/orders", form, 201},
{"POST", "/orders", "", 400},
{"GET", "/orders/1", "", 200},
{"GET", "/orders/abc", "", 400},
{"GET", "/static/none.jpg", "", 404},
} {
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
if tc.body != "" {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != tc.want {
t.Errorf("%s %s: got %d, want %d (%q)", tc.method, tc.path, rec.Code, tc.want, rec.Body.String())
}
}
}
Real run:
$ go vet . && go test -v .
=== RUN TestRoutes
--- PASS: TestRoutes (0.00s)
PASS
ok menu 0.005s
Handlers run concurrently (each request on its own goroutine), so the orders map is protected with a sync.Mutex (episode 45). go run . then opening http://localhost:8080/menu in a browser shows the menu.
Common mistakes (and the real messages)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
WriteHeader after writing the body |
http: superfluous response.WriteHeader call from main.late (main.go:31) |
the status was already sent | headers → status → body |
Header().Set after writing |
the header never arrives | headers were already sent | set headers first |
no return after http.Error |
error text followed by the normal body | the handler keeps going | return right after |
/menu/{id} for /menu/1/extra |
404 page not found |
{id} matches one segment |
{rest...} |
| two overlapping patterns | panic when registering | neither is more specific | make one more specific |
ignoring ListenAndServe's error |
the program just exits | e.g. listen tcp :8080: bind: address already in use |
log.Fatal(...) |
| unprotected shared map in handlers | fatal error: concurrent map writes |
handlers run in parallel | a mutex (or one owner goroutine) |
Practice
- Add
GET /{$}that answers "Welcome to Raju's" only for/. - Make
GET /menu/{id}answerapplication/jsonwith{"name": ..., "price": ...}(hint:encoding/json, episode 35). - What status should
POST /ordersreturn for an item that doesn't exist on the menu? Why? - Use
httptest.NewServerto test thatDELETE /menureturns anAllowheader.
Solutions
1. mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Welcome to Raju's") }) — without {$}, GET / would match every path.
2.
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]any{"name": s.names[id], "price": p})
3. 400 Bad Request (or 422 Unprocessable Content): the request itself is wrong, not the server; 404 would suggest /orders doesn't exist.
4.
srv := httptest.NewServer(NewShop().Routes(t.TempDir()))
defer srv.Close()
req, _ := http.NewRequest("DELETE", srv.URL+"/menu", nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != 405 || resp.Header.Get("Allow") == "" {
t.Errorf("got %d, Allow=%q", resp.StatusCode, resp.Header.Get("Allow"))
}
Quick quiz
1. The mux has GET /menu/{id} and POST /menu. What does DELETE /menu/2 get? (From the video.)
A. 200 from item · B. 404 page not found · C. 405 Method Not Allowed · D. a panic
Answer
C. The path matches GET /menu/{id} but not the method, so the mux answers 405 with Allow: GET, HEAD.
2. A handler calls fmt.Fprintln(w, "hi") and nothing else. What status does the client get?
Answer
200 OK: the first write sends 200 if no status was set.
3. What does http.HandlerFunc(f) do?
Answer
Converts a function with the handler signature into a value of a type that has ServeHTTP, i.e. an http.Handler.
Interview questions
- What is
http.Handler? An interface withServeHTTP(ResponseWriter, *Request); everything innet/http(muxes, file servers, middleware) is a Handler. - Why does
http.HandlerFuncexist? It's an adapter so plain functions can be used as Handlers. - What changed in
ServeMuxin Go 1.22? Method matching (GET /x), wildcards ({id},{rest...},{$}),r.PathValue, precedence by specificity, 405 withAllow. - In what order do you write a response? Headers, then
WriteHeader(status), then the body. r.URL.Query()vsr.FormValue? Query reads only the URL's query string;FormValueparses the body form too (and falls back to the query).- How do you test a handler?
httptest.NewRecorder+httptest.NewRequestand callServeHTTP;httptest.NewServerfor a real server. - Is a handler called concurrently? Yes, each request runs on its own goroutine; protect shared state.
- What does
ListenAndServereturn? Only a non-nil error, when it fails to start or stops; wrap it inlog.Fatal.
Glossary
| Term | Meaning | Example |
|---|---|---|
| HTTP | text rules for requests and responses over TCP | GET /menu HTTP/1.1 |
| Request / response | what the client sends / what the server answers | GET request, 200 response |
| Method | the action of a request | GET, POST, DELETE, HEAD |
| Path | which thing is asked for | /menu/2 |
| Request line / status line | the first line of a request / response | HTTP/1.1 200 OK |
| Header | a Name: value line of metadata |
Content-Type: text/plain |
| Body | the data after the headers | a posted form |
| Status code | a number saying how it went | 200, 201, 400, 404, 405, 500 |
Content-Length |
body size in bytes | ₹ = 3 bytes |
User-Agent |
names the client program | Go-http-client/1.1 |
net/http |
Go's HTTP client and server package | http.Get, http.ListenAndServe |
http.Handler |
interface with ServeHTTP |
menu struct |
ServeHTTP |
the method that answers a request | func (m menu) ServeHTTP(w, r) |
http.ResponseWriter |
where a handler writes the response | w.WriteHeader(201) |
*http.Request |
the parsed request | r.Method, r.URL.Path |
http.HandlerFunc |
adapter: function → Handler | http.HandlerFunc(hello) |
| Router / mux | picks a handler by pattern | http.NewServeMux() |
http.ServeMux |
the standard router | mux.HandleFunc("GET /menu", f) |
| Pattern | what a route matches | GET /menu/{id} |
| Wildcard | a named blank in a pattern | {id}, {path...}, {$} |
r.PathValue |
a wildcard's value | r.PathValue("id") → "2" |
| 405 Method Not Allowed | path exists, wrong method | Allow: GET, HEAD |
| Query string | the part of a URL after ? |
?q=ginger+chai |
r.URL.Query().Get |
reads a query value | "ginger chai" |
| Form value | a field sent in a form | r.FormValue("item") |
http.Error |
writes a plain-text error with a status | http.Error(w, "...", 400) |
Location header |
where a new resource lives | /orders/42 |
| Superfluous WriteHeader | a second/late WriteHeader that is ignored |
server log warning |
http.FileServer |
serves files from a folder | http.FileServer(http.Dir(d)) |
http.StripPrefix |
removes a path prefix before a handler | /static/ |
http.ListenAndServe |
runs a server on an address | log.Fatal(http.ListenAndServe(":8080", mux)) |
httptest.NewRecorder |
fake ResponseWriter for tests | rec.Code, rec.Body |
httptest.NewRequest |
request for tests, no network | httptest.NewRequest("GET", "/menu", nil) |
httptest.NewServer |
a real test server on a free port | srv.URL |
Summary
- HTTP is text over TCP: request line (method + path), headers, body; response: status, headers, body.
http.Handler(ServeHTTP(w, r)) is the core;http.HandlerFuncadapts functions.http.ServeMuxroutes by method and path with wildcards ({id},{rest...},{$}) read byr.PathValue; wrong methods get 405.- Read input from
r.URL.Query()andr.FormValue; write headers → status → body. http.FileServer+StripPrefixserve folders;http.ListenAndServeruns it all (wrap inlog.Fatal).httptesttests handlers without a network.
Next episode: HTTP servers in production: http.Server timeouts, why the defaults are unsafe, graceful shutdown, request contexts, body limits, TLS and HTTP/2.