Skip to main content

The Server Calls You

A Go web server is built from handlers: functions with the shape func(w http.ResponseWriter, r *http.Request). The server accepts connections and calls your handler once per request — r holds everything about the request, and whatever you write into w becomes the response.

A real server starts with http.ListenAndServe(":8080", mux) and runs forever. The examples here use httptest.NewServer instead — a real server on a random free port that the program can start, use and stop, so every example runs and finishes by itself.


A First Handler

The smallest possible handler writes a line of text. Everything an API does — JSON, status codes, routing — happens inside this same function shape.

Hello from a handler

The handler writes into w; the client reads exactly that as the response body, with status 200 OK filled in automatically.

Prompt
Write a Go program with the smallest HTTP handler that writes a hello line, serve it with an httptest server, send one GET request and print the response status and body.
Output: Go program and captured output

Answering with JSON

An API handler does three things: set the Content-Type header, choose a status code, and encode the data. json.NewEncoder(w).Encode(value) writes JSON straight into the response.

Order matters: headers must be set before the body is written.

A JSON endpoint

The handler encodes a struct directly into the response writer. The client receives valid JSON and the right content type — this is the skeleton of every endpoint in the rest of this group.

Prompt
Write a Go program with a handler that answers with a JSON-encoded User struct using json.NewEncoder and a Content-Type header, serve it with httptest, request it and print the status, content type and JSON body.
Output: Go program and captured output