Skip to Content
Skip to content
Go for Beginners: Write Reliable Programs and Small Services
Beginner
Courses
Go for Beginners: Write Reliable Programs and Small Services

Build and Test a Small net/http Server

Write net/http handlers, return JSON and status codes, test routes in memory with httptest, and compile a standalone binary. After this, you can ship and test a small Go web service.

Course content

Sign in to save your progress.

Course Home

One of Go's biggest strengths is that you can build and unit-test a real HTTP API using only the standard library—no Express, Flask, or external router required. In Go 1.22+, the built-in http.ServeMux even supports HTTP method matching and path parameters like "GET /items/{id}", and net/http/httptest lets you test every route in memory in under a millisecond.

Skip ahead

If you already build routers with http.NewServeMux(), extract r.PathValue, test handlers with httptest.NewRecorder(), and build static binaries with CGO_ENABLED=0, take the section quiz or move on to "Pointers and Memory Basics."

Experiment 1: Method routing and path parameters with http.NewServeMux

Always create your own mux := http.NewServeMux() inside a newRouter() helper instead of calling the global http.HandleFunc. Two reasons: third-party packages can register unexpected debug endpoints on the global http.DefaultServeMux, and returning an http.Handler from newRouter() lets your unit tests exercise the exact same routing table:

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
)

func newRouter() http.Handler {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /items/{id}", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		fmt.Fprintf(w, `{"id":%q}`, r.PathValue("id"))
	})
	return mux
}

func main() {
	h := newRouter()

	rec1 := httptest.NewRecorder()
	h.ServeHTTP(rec1, httptest.NewRequest("GET", "/items/42", nil))
	fmt.Printf("item status=%d ct=%s body=%s\n", rec1.Code, rec1.Header().Get("Content-Type"), rec1.Body.String())

	rec2 := httptest.NewRecorder()
	h.ServeHTTP(rec2, httptest.NewRequest("POST", "/items/42", nil))
	fmt.Printf("post status=%d\n", rec2.Code)
}
item status=200 ct=application/json body={"id":"42"}
post status=405

Look at what "GET /items/{id}" gave you for free: GET /items/42 extracted "42" via r.PathValue("id"), and POST /items/42 was rejected automatically with 405 Method Not Allowed without a single if r.Method != http.MethodGet boilerplate block.

Experiment 2: Header ordering—why headers set after WriteHeader disappear

A subtle net/http rule trips up almost every newcomer: once you call w.WriteHeader(status)—or write the first body byte with w.Write(...), which implicitly calls w.WriteHeader(200)—Go commits the HTTP status line and headers. Any w.Header().Set(...) call after that is silently ignored:

// Wrong: Content-Type is ignored because WriteHeader already ran!
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")

// Right: always set headers BEFORE WriteHeader or Write
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"ok"}`))

Experiment 3: Writing a fast unit test with httptest.NewRecorder

You do not need to start a server on port 8080 or run curl to test your routes. Call h.ServeHTTP(rec, req) directly in main_test.go:

func TestItemsRoute(t *testing.T) {
	h := newRouter()

	req := httptest.NewRequest(http.MethodGet, "/items/42", nil)
	rec := httptest.NewRecorder()
	h.ServeHTTP(rec, req)

	if rec.Code != http.StatusOK {
		t.Fatalf("status = %d, want 200", rec.Code)
	}
	if rec.Body.String() != `{"id":"42"}` {
		t.Fatalf("body = %q, want %q", rec.Body.String(), `{"id":"42"}`)
	}
}
$ go test -v .
=== RUN   TestItemsRoute
--- PASS: TestItemsRoute (0.00s)
PASS

Experiment 4: Compiling a standalone static binary

When you are ready to deploy your HTTP server to a Linux server or minimal container, disable cgo and strip debug tables so the binary has zero shared-library dependencies:

$ CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o status-server .

Common mistakes

  • Forgetting return after http.Error(w, "bad request", 400): http.Error writes the error response, but it does not exit your handler—if you forget return, the rest of the handler keeps running and appends a second body!
  • Setting Content-Type after w.WriteHeader: Silently ignored, so clients receive text/plain instead of application/json.
  • Shipping http.ListenAndServe(":8080", h) directly to production: Leaves server timeouts at infinity; in Go Intermediate, you will wrap your router in an explicit &http.Server{ReadHeaderTimeout: 5 * time.Second}.

💡 Tip

Put newRouter() in its own function and keep main() down to 3–5 lines. That single habit makes every endpoint in your service trivially testable with httptest.

What happens if you skip this step

If you test routes only by restarting the server and clicking in a browser, regressions in status codes, JSON formatting, or missing return statements after http.Error slip straight into production.

Your handler calls http.Error(w, "invalid id", http.StatusBadRequest) inside an if block, forgets the return statement, and then encodes a 200 JSON payload underneath. What does the client actually receive?

About

Write net/http handlers, return JSON and status codes, test routes in memory with httptest, and compile a standalone binary. After this, you can ship and test a small Go web service.

Duration
5 min
Last update
11/27/2026
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.