Lesson 05 · 55 minutes
Call and serve HTTP from Go
- Write an HTTP client with a timeout and check the status and headers
- Serve a JSON endpoint from a local server
- Cancel a slow request with a context
The lab folder as it stands after this lesson. Unzip it in ~/krlab.
More
The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.
Scenario
Your team runs a small internal status service, and a script must read it: which services are up, who owns the answer, and what happens when the service is slow. The first version of such a script uses http.Get, and one day it hangs for ever on a server that never answers. You will first learn the client and the server on a lab server of your own. Then you write a probe that checks a second set of routes, with a timeout, and reports what it finds.
Recall
Which exit code means "wrong use of the command line" by habit, and which means a failure while running?
2 means wrong use, and 1 means a failure while running. 0 is success.
What is the difference between `errors.Is` and comparing the text of an error?
errors.Is finds a known error value even inside wrappers, so it still works when you add context. The text changes when you add context, so a text comparison breaks.
The idea
| Piece | Meaning |
|---|---|
http.Client | Sends requests. Its Timeout limits the whole exchange, including reading the body. |
http.Server | Listens on an address and sends each request to a handler. |
| Handler | A function with a ResponseWriter to write the answer and a Request to read from. |
context.Context | A value that carries a deadline or a cancel signal through your calls. |
A context lets you say "stop after one second" once, at the top, and every function below obeys. Create one with context.WithTimeout, and always call the cancel function that it returns.
Always bind a test server to 127.0.0.1. It then answers only your own machine.
- Client → http.Server: GET /api/hosts
- http.Server → Handler: the mux picks the route
- Handler → http.Server: status, headers and body
- http.Server → Client: the response
- Client: check the status, then decode the body
Worked example
1. Write the server
curl is a command-line tool that sends a web request. A module can hold several programs: make two, server and client, in two folders, and the folders urlparts and redirect for later steps and probe for your turn.
mkdir -p ~/krlab/go/web/server ~/krlab/go/web/client ~/krlab/go/web/urlparts ~/krlab/go/web/redirect ~/krlab/go/web/probe
cd ~/krlab/go/web
go mod init krlab/webgo mod init writes this go.mod. The lab zip holds it with go 1.22, so that it builds on every Go from 1.22:
go.mod
module krlab/web
go 1.22Write server/main.go. A route maps a path of the URL to a function. http.NewServeMux makes the table of routes, and HandleFunc adds one. Each handler is a function with two inputs: w http.ResponseWriter to write the answer, and r *http.Request, a pointer to the request (lesson 4, step 4). The server starts with three routes:
| Route | Answer |
|---|---|
/health | The text ok. |
/api/hosts | JSON and the header X-Lab. |
/slow | Waits five seconds, but stops early when the client leaves. |
These names are new:
| Name | Job |
|---|---|
w.Header().Set(k, v) | Sets a header of the answer. Do it before you write the body. |
json.NewEncoder(w).Encode(v) | Writes the value v as JSON into the answer. |
select | Waits for the first of several events (channels: lesson 6). |
time.After(d) | Gives a channel that receives a value after the time d (channels: lesson 6). |
[]byte("ok\n") | Turns the text into bytes, which w.Write takes. |
log.Println | Prints a line with the time. |
srv.ListenAndServe() | Starts the server. It does not return until the server fails, and then it gives the error. |
log.Fatal(err) | Prints the error and ends the program with exit code 1. |
web/server/main.go
package main
import (
"encoding/json"
"log"
"net/http"
"time"
)
type Host struct {
Name string `json:"name"`
Port int `json:"port"`
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok\n"))
})
mux.HandleFunc("GET /api/hosts", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Lab", "krbox")
json.NewEncoder(w).Encode([]Host{{"web1", 80}, {"db1", 3306}})
})
mux.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(5 * time.Second):
w.Write([]byte("done\n"))
case <-r.Context().Done():
log.Println("slow: client left:", r.Context().Err())
}
})
srv := &http.Server{
Addr: "127.0.0.1:8201",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
}
log.Println("listening on", srv.Addr)
log.Fatal(srv.ListenAndServe())
}The pattern "GET /health" (Go 1.22 and later) limits a route to one method. &http.Server{...} builds the value and takes its address in one step. ReadHeaderTimeout stops a client that opens a connection and then sends nothing. A handler can do little about a failed w.Write, so these handlers ignore its error. A tool that writes a file must check it.
2. Start it and test it with curl
go run ./server starts the server and keeps running. Run it in this terminal. Open a second terminal for the other commands. In curl, -s is silent and -i prints the response headers.
go run ./server2026/11/21 08:40:29 listening on 127.0.0.1:8201If you see bind: address already in use, an earlier server still runs, or another program uses the port. Press Ctrl+C in the terminal of the old server, or find the program with ss -ltn | grep 8201 (ss -ltn lists the TCP ports that listen on your machine, and grep keeps the lines with 8201) (on macOS, lsof -i :8201).
curl -si 127.0.0.1:8201/api/hostsHTTP/1.1 200 OK
Content-Type: application/json
X-Lab: krbox
Date: Sat, 21 Nov 2026 08:40:31 GMT
Content-Length: 55
[{"name":"web1","port":80},{"name":"db1","port":3306}]3. Write the client
Write client/main.go. A context (see above) carries the deadline. The shared client has a 3-second timeout, and get builds a request that carries a context. The program checks the status before it decodes, and it closes the body with defer. The work is in run, which returns an error, and main calls os.Exit once, so the defer calls in run always run (lesson 4). These names are new:
| Name | Job |
|---|---|
context.Background() | The empty context, with no deadline. You add a deadline to it with WithTimeout. |
time.Now() | The time now. |
time.Since(t) | Gives the time that has passed since t. .Round(d) rounds that time to a multiple of d. |
*http.Response | A pointer to the response. get returns it. |
io.LimitReader(r, n) | Reads at most n bytes. The client keeps the body to 1 MB: 1<<20 is 1,048,576 bytes. |
web/client/main.go
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
type Host struct {
Name string `json:"name"`
Port int `json:"port"`
}
var client = &http.Client{Timeout: 3 * time.Second}
func get(ctx context.Context, url string) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
return client.Do(req)
}
func run() error {
base := "http://127.0.0.1:8201"
resp, err := get(context.Background(), base+"/api/hosts")
if err != nil {
return err
}
defer resp.Body.Close()
fmt.Println("status:", resp.Status)
fmt.Println("x-lab:", resp.Header.Get("X-Lab"))
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("unexpected status %s", resp.Status)
}
var hosts []Host
body := io.LimitReader(resp.Body, 1<<20)
if err := json.NewDecoder(body).Decode(&hosts); err != nil {
return err
}
fmt.Printf("%+v\n", hosts)
r2, err := get(context.Background(), base+"/nope")
if err != nil {
return err
}
fmt.Println("status:", r2.Status)
r2.Body.Close()
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
start := time.Now()
_, err = get(ctx, base+"/slow")
fmt.Println("slow:", err)
fmt.Println("took", time.Since(start).Round(100*time.Millisecond))
return nil
}
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}4. Run the client
In the second terminal, go to the module folder first.
cd ~/krlab/go/web
go run ./clientstatus: 200 OK
x-lab: krbox
[{Name:web1 Port:80} {Name:db1 Port:3306}]
status: 404 Not Found
slow: Get "http://127.0.0.1:8201/slow": context deadline exceeded
took 1sA 404 is not a Go error: the request worked and the server said no. Your code must check StatusCode. The call to /slow stopped after one second, though the client allows three. The context was the shorter limit.
Look at the first terminal. The server noticed that the client left and stopped its own work.
2026/11/21 08:40:32 slow: client left: context canceled- Client → Server: GET /slow, with a context of one second
- Server: the handler waits 5 s, or for the client
- Client: one second passes: context deadline exceeded
- Client → Server: the connection closes
- Server: r.Context().Done() fires: client left
5. Take a URL apart
A program that checks only its own machine must read the host of a URL. The package net/url does this. url.Parse splits a URL into parts. Hostname() gives the host without the port and without the brackets of an IPv6 address, and Port() gives the port.
web/urlparts/main.go
package main
import (
"fmt"
"net/url"
)
func main() {
for _, raw := range []string{"http://127.0.0.1:8201/api/hosts", "http://[::1]:8201/x"} {
u, err := url.Parse(raw)
if err != nil {
fmt.Println("error:", err)
continue
}
fmt.Println(u.Scheme, u.Hostname(), u.Port(), u.Path)
}
}go run ./urlpartshttp 127.0.0.1 8201 /api/hosts
http ::1 8201 /x6. Do not follow a redirect
A redirect is an answer such as 302 with a Location header: "ask there instead". By default the client follows up to 10 of them, even to another host. A tool that must stay on its own machine must not do that.
First add three routes to the server: /old redirects to /health, and /api/services and /admin are for your turn. Put this code before the line mux.HandleFunc("GET /slow", ..., then stop the server with Ctrl+C and start it again with go run ./server. The whole file is at the end of this step.
mux.HandleFunc("GET /api/services", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Owner", "secops")
w.Write([]byte(`[{"name":"mail","up":true},{"name":"vpn","up":false},{"name":"wiki","up":true},{"name":"ci","up":false},{"name":"vault","up":false}]`))
})
mux.HandleFunc("GET /admin", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "forbidden", http.StatusForbidden)
})
mux.HandleFunc("GET /old", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/health", http.StatusFound)
})http.Error(w, text, code) sends a status code and a text. http.Redirect(w, r, to, code) sends a 3xx answer with the header Location: to. The field CheckRedirect of the client is a function that runs before each redirect. If it returns http.ErrUseLastResponse, the client stops and gives you the 3xx answer. This program uses both kinds of client on the route /old. %q prints the header in quotes, so an empty value is visible.
web/redirect/main.go
package main
import (
"fmt"
"net/http"
"time"
)
func main() {
follow := &http.Client{Timeout: 3 * time.Second}
stop := &http.Client{
Timeout: 3 * time.Second,
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
}
for _, c := range []*http.Client{follow, stop} {
resp, err := c.Get("http://127.0.0.1:8201/old")
if err != nil {
fmt.Println("error:", err)
continue
}
resp.Body.Close()
fmt.Printf("%d %q\n", resp.StatusCode, resp.Header.Get("Location"))
}
}go run ./redirect200 ""
302 "/health"The first client followed the redirect and got the answer of /health. The second stopped at the 302 and shows where it was sent. Lesson 10 uses this in a tool that must refuse foreign hosts.
The finished file: server/main.go
web/server/main.go
package main
import (
"encoding/json"
"log"
"net/http"
"time"
)
type Host struct {
Name string `json:"name"`
Port int `json:"port"`
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok\n"))
})
mux.HandleFunc("GET /api/hosts", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Lab", "krbox")
json.NewEncoder(w).Encode([]Host{{"web1", 80}, {"db1", 3306}})
})
mux.HandleFunc("GET /api/services", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("X-Owner", "secops")
w.Write([]byte(`[{"name":"mail","up":true},{"name":"vpn","up":false},{"name":"wiki","up":true},{"name":"ci","up":false},{"name":"vault","up":false}]`))
})
mux.HandleFunc("GET /admin", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "forbidden", http.StatusForbidden)
})
mux.HandleFunc("GET /old", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/health", http.StatusFound)
})
mux.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(5 * time.Second):
w.Write([]byte("done\n"))
case <-r.Context().Done():
log.Println("slow: client left:", r.Context().Err())
}
})
srv := &http.Server{
Addr: "127.0.0.1:8201",
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
}
log.Println("listening on", srv.Addr)
log.Fatal(srv.ListenAndServe())
}7. Stop the server and run the client again
Press Ctrl+C in the first terminal, then run the client.
go run ./clienterror: Get "http://127.0.0.1:8201/api/hosts": dial tcp 127.0.0.1:8201: connect: connection refusedA stopped server gives a clear error at once. A server that is up but silent is the hard case, and the timeout is for that.
Your turn
Your lead adds two routes to the lab server and asks for a probe. You added them to server/main.go in step 6: /api/services (JSON, with a header X-Owner) and /admin. There are no steps here: use what the worked example showed.
In ~/krlab/go/web/probe, write a program that does these things against http://127.0.0.1:8201 while the server runs:
- Print the status code of
/health,/adminand/nothing, one line for each, aspath code. - Fetch
/api/servicesand decode the JSON into a slice of structs with the fieldsnameandup. Printowner:and the value of the headerX-Owner. Printdown:with the number of services whoseupis false, thenfirst:and the name of the first service that is down. - Fetch
/slowwith a context that ends after 300 ms. Print/slow timeoutwhen the error iscontext.DeadlineExceeded.
Use one http.Client with a timeout, check the status before you decode, and close every body. Run the probe, then stop the server.
Check yourself
Why is `http.Get(url)` a poor choice in a scanner?
It uses http.DefaultClient, which has no timeout. A host that accepts the connection and never answers blocks the call for ever. Make your own http.Client with a Timeout.
The server returns 500. Is `err` from `client.Do` nil or not?
It is nil. Do returns an error only when no response came (network failure, timeout). A 4xx or 5xx status is a valid response, so check resp.StatusCode.
What happens if you forget `resp.Body.Close()`?
The connection cannot return to the pool, so connections and file descriptors leak. A tool that makes thousands of requests then runs out of descriptors.
Why does the `/slow` handler read `r.Context().Done()`?
The context ends when the client disconnects. The handler can then stop its work at once, and not spend time on an answer that nobody reads.
Field notes
- Set a
Timeouton the client and also time limits on the server:ReadHeaderTimeoutat least, andReadTimeoutandWriteTimeoutfor most services. A server without them is open to slow-client attacks (Slowloris is the best known). - Reuse one
http.Clientfor the whole program. It keeps a pool of connections. A new client for each request throws the pool away and opens a new connection each time. - Do not turn off TLS checks with
InsecureSkipVerify: trueto make an error go away. It removes the protection of HTTPS. For a lab with its own certificate, add that certificate to ax509.CertPool. - Limit what you read.
io.LimitReaderstops a hostile server from sending you gigabytes. Limit redirects too: the client follows 10 by default, andCheckRedirectchanges that (step 6). - Set a
User-Agentthat names your tool and gives a contact. An operator who sees your traffic in a log can then tell a test from an attack.