An HTTP server with net/http

net/http is the server and the client of the standard library. A handler is a function that writes a response and reads a request, a mux maps paths to handlers, and a server runs them. This lesson starts a server on port zero and asks it for a page in the same program, so the program runs to the end; a real service calls srv.ListenAndServe() and blocks until the process is stopped.

A handler and a server

The mux registers GET /hello, the listener takes a free port from the kernel, and Serve runs in a goroutine. The client is the same http.Get a browser uses, and the shutdown at the end is the graceful stop the last lesson of this part takes apart. The status line and the body are the response.

package main import ( "context" "fmt" "io" "net" "net/http" "time" ) func main() { mux := http.NewServeMux() mux.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "hello from the server") }) ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { panic(err) } srv := &http.Server{Handler: mux} go srv.Serve(ln) resp, err := http.Get("http://" + ln.Addr().String() + "/hello") if err != nil { panic(err) } body, err := io.ReadAll(resp.Body) resp.Body.Close() if err != nil { panic(err) } fmt.Println("status:", resp.Status) fmt.Print("body: ", string(body)) ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() if err := srv.Shutdown(ctx); err != nil { panic(err) } fmt.Println("server stopped") }

go build -o app main.go && ./app

status: 200 OK
body: hello from the server
server stopped

Port zero asks the kernel for a free port, which is why the address is read from the listener instead of written as :8080; a test does the same to run servers in parallel. The handler wrote the body with Fprintln and the server added the Content-Type by sniffing the first bytes, which is why the response is a text page.

What the handler receives

The request carries the method, the path, the query string, the headers and a body. r.URL.Path is the decoded path, r.URL.RawQuery the part after the question mark, and r.Header.Get reads a header case-insensitively. The handler below echoes four of them back, and the client sets its own User-Agent.

package main import ( "context" "fmt" "io" "net" "net/http" "time" ) func main() { mux := http.NewServeMux() mux.HandleFunc("GET /echo", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "method=%s path=%s query=%s ua=%s\n", r.Method, r.URL.Path, r.URL.RawQuery, r.Header.Get("User-Agent")) }) ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { panic(err) } srv := &http.Server{Handler: mux} go srv.Serve(ln) defer func() { ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() _ = srv.Shutdown(ctx) }() req, err := http.NewRequest("GET", "http://"+ln.Addr().String()+"/echo?x=1", nil) if err != nil { panic(err) } req.Header.Set("User-Agent", "lesson-client") resp, err := http.DefaultClient.Do(req) if err != nil { panic(err) } body, err := io.ReadAll(resp.Body) resp.Body.Close() if err != nil { panic(err) } fmt.Print("body: ", string(body)) }

go build -o app main.go && ./app

body: method=GET path=/echo query=x=1 ua=lesson-client

The query stayed a string: a handler that needs a parameter calls r.URL.Query().Get("x"), which decodes and returns the first value. The body is not read here, and a handler that does not read it must still let the server close it; the pattern match and its path values are the next lesson.

Status and headers

A handler sets headers before it writes the status and the body, in that order. WriteHeader sends the status once; a second call is ignored, and a body written before it forces a 200. The handler below creates a note, answers 201 and names its content type, and the client reads all three.

package main import ( "context" "fmt" "io" "net" "net/http" "time" ) func main() { mux := http.NewServeMux() mux.HandleFunc("POST /notes", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(http.StatusCreated) fmt.Fprintln(w, "created") }) ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { panic(err) } srv := &http.Server{Handler: mux} go srv.Serve(ln) defer func() { ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() _ = srv.Shutdown(ctx) }() resp, err := http.Post("http://"+ln.Addr().String()+"/notes", "text/plain", nil) if err != nil { panic(err) } body, err := io.ReadAll(resp.Body) resp.Body.Close() if err != nil { panic(err) } fmt.Println("status:", resp.Status) fmt.Println("content-type:", resp.Header.Get("Content-Type")) fmt.Print("body: ", string(body)) }

go build -o app main.go && ./app

status: 201 Created
content-type: text/plain; charset=utf-8
body: created

The status came from the constant and the content type from the header, and the body is what the handler wrote. A handler that returns JSON sets application/json and encodes, which the API lessons do; the mux already answered 405 for the GET that was not registered and 404 for a path it does not know.

The protocol below

HTTP is text. The program below opens a TCP connection, writes a request by hand and reads the response with http.ReadResponse, which is what a client library does internally. The status line, the headers and the body are all there, and the content length is the one the server computed for the body.

package main import ( "bufio" "context" "fmt" "io" "net" "net/http" "time" ) func main() { mux := http.NewServeMux() mux.HandleFunc("GET /hello", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "hello from the server") }) ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { panic(err) } srv := &http.Server{Handler: mux} go srv.Serve(ln) defer func() { ctx, cancel := context.WithTimeout(context.Background(), time.Second) defer cancel() _ = srv.Shutdown(ctx) }() conn, err := net.Dial("tcp", ln.Addr().String()) if err != nil { panic(err) } defer conn.Close() fmt.Fprintf(conn, "GET /hello HTTP/1.1\r\nHost: %s\r\nConnection: close\r\n\r\n", ln.Addr()) resp, err := http.ReadResponse(bufio.NewReader(conn), nil) if err != nil { panic(err) } defer resp.Body.Close() body, err := io.ReadAll(resp.Body) if err != nil { panic(err) } fmt.Println("proto:", resp.Proto) fmt.Println("status:", resp.StatusCode) fmt.Println("content-length:", resp.ContentLength) fmt.Print("body: ", string(body)) }

go build -o app main.go && ./app

proto: HTTP/1.1
status: 200
content-length: 22
body: hello from the server

Twenty-two bytes is the greeting and its newline. The Host header is required in HTTP/1.1 and the Connection: close made the server close the socket after the response, which is why the read finished. A raw view is how a proxy or a curl-like tool is written, and how a protocol bug is found.

One process, many requests

The server runs every request in its own goroutine, so a handler that sleeps slows only that request. That is also the danger: a handler that writes a shared map or a global counter races, and the race detector is the check. A request has a context that is cancelled when the client goes away, and r.Context() is the context a handler passes to its database and its outbound calls.

The program above uses a listener it owns so the lesson can stop it; http.ListenAndServe(":8080", mux) is the one-line version for a service, and Server.Shutdown the graceful stop. The next lessons build the mux, the handlers and the middleware of a real API.

Exercises

  1. Change the address to :8080 and start the program twice. What does the second process print, and which call returns that error?
  2. Remove the Content-Type header and read the response header the server sniffed. Which type did it choose, and why?
  3. Write a query with two values for the same key and read them with r.URL.Query()["x"]. What does Get return, and what does the slice hold?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is an http.Handler?

    Answer

    Anything with a ServeHTTP method

    HandleFunc adapts a function to it.

  2. What does port zero ask the kernel for?

    Answer

    A free port

    The address is read from the listener.

  3. What does http.Server.Serve do?

    Answer

    Accepts requests on the listener until Shutdown

    It runs in a goroutine here.

  4. Where is the query string on a request?

    Answer

    r.URL.RawQuery, or r.URL.Query()

    Query decodes and parses it.

  5. What is the order of a response?

    Answer

    Set headers, then WriteHeader, then the body

    Headers after the status are ignored.

  6. What does WriteHeader do a second time?

    Answer

    Is ignored

    The status goes out once.

  7. What does http.ReadResponse read?

    Answer

    A response from a reader such as a TCP connection

    It parses the status line, headers and body.

  8. How does the server handle two requests at once?

    Answer

    One goroutine per request

    A shared map in a handler therefore races.

  9. Where does a handler get its cancellation?

    Answer

    r.Context()

    It is cancelled when the client goes away.

  10. What is the one-line server call?

    Answer

    http.ListenAndServe(":8080", mux)

    It blocks until the process stops.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev