Go httptest is a standard library package that lets you test HTTP handlers without opening a real port. In this post, you will learn how to send fake requests, read the responses and check status codes and bodies. Then we will test a small book API from start to finish.
This lesson follows Go table-driven tests and benchmarks, so we reuse the same table style. We also build on Go HTTP server basics and Go REST API for beginners. If those ideas are new, read them first.
What Is Go httptest?
In short, net/http/httptest gives you tools to test HTTP code quickly. It has two main helpers. The first is httptest.NewRecorder, which acts like a fake response writer. The second is httptest.NewServer, which starts a real server on a random local port.
Think of a flight simulator. Pilots practise takeoffs and landings without leaving the ground. Similarly, Go httptest lets your handler “take off” many times without any real network, so tests are fast and safe.
You can call the handler directly, because a handler is just a function. As a result, you do not need a browser, curl or a running program. For example, a full test of a login route can fit in ten lines. The idea behind Go httptest is simple: if you can build a request, you can test the answer.
Why Go httptest Matters
Handlers sit at the edge of your app, and they decide what users see. So bugs there are easy to notice. Here is what Go httptest gives you.
- Speed: a recorder test runs in microseconds, since no network is used.
- Reliability: no port clashes, no firewalls and no waiting for a server to start.
- Full control: you choose the method, path, headers and body of every request.
- Easy checks: you can inspect the status code, headers and body in one place.
- Safe refactoring: you can change the code inside a handler and keep the same tests.
Because of this, nearly every Go web project uses httptest for handler tests. In fact, many teams run thousands of these tests in a few seconds. That speed matters, because fast tests get run often. Also, slow tests are the ones that people skip before a release.
How Go httptest Works
First, you build a request with httptest.NewRequest. Next, you create a recorder with httptest.NewRecorder. Then you call handler.ServeHTTP(rec, req). Finally, you read rec.Code, rec.Header() and rec.Body to check the result.

Notice that nothing leaves your computer. In other words, the whole round trip happens inside one Go process. As a result, Go httptest tests rarely fail because of the network, and they run the same way on your laptop and in CI.
The Request and the Recorder
The NewRequest function never returns an error, which keeps tests short. It panics only when you pass a broken URL. Meanwhile, the recorder keeps everything the handler writes, so you can read it later.
What to Check in a Response
A recorder keeps several things you can inspect. The table below lists the most useful ones.
| What to check | How to read it | Example |
|---|---|---|
| Status code | rec.Code | 200, 404 |
| Headers | rec.Header().Get("Content-Type") | application/json |
| Body text | rec.Body.String() | book not found |
| Decoded JSON | json.NewDecoder(rec.Body).Decode(&v) | A Book struct |
| Full result | rec.Result() | A normal *http.Response |
In most tests, the status code and the body are enough. However, check the header too when the content type matters to your clients. Also, call rec.Result() when you need a real *http.Response, for example to read cookies.
Path Values in Go 1.22 and Later
Since Go 1.22, the standard mux supports patterns such as GET /books/{id}. The handler reads the value with r.PathValue("id"). Because the mux does the matching, you should test through the mux, not through a single handler function. Otherwise PathValue returns an empty string.
Go httptest: Recorder vs Test Server
Both tools test HTTP code, but they work differently. The table below compares them.
| Feature | NewRecorder | NewServer |
|---|---|---|
| Real network port | No | Yes, on localhost |
| Speed | Fastest | Slower, but still quick |
| Tests middleware and routing | Yes, through the mux | Yes |
| Tests an HTTP client | No | Yes |
| Best for | Handler logic | Client code and full flows |

So when should you use which? Start with the recorder for handlers because it is simple and quick. Later, add one or two server tests for the paths that matter most. On the other hand, use NewServer when you test code that makes HTTP calls, such as an API client.
Go httptest Hands-On: Test a Book API
Now let’s test a tiny book API. It has two routes: GET /books/{id} and POST /books.
Step 1: The Handlers
First, here is the code we want to test. The store keeps books in a map and uses a read-write mutex to stay safe.
type Book struct {
ID string `json:"id"`
Title string `json:"title"`
}
type Store struct {
mu sync.RWMutex
books map[string]Book
}
func NewStore() *Store {
return &Store{books: map[string]Book{"1": {ID: "1", Title: "Go in Action"}}}
}
func (s *Store) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /books/{id}", s.getBook)
mux.HandleFunc("POST /books", s.createBook)
return mux
}
func (s *Store) getBook(w http.ResponseWriter, r *http.Request) {
s.mu.RLock()
b, ok := s.books[r.PathValue("id")]
s.mu.RUnlock()
if !ok {
http.Error(w, "book not found", http.StatusNotFound)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(b)
}
func (s *Store) createBook(w http.ResponseWriter, r *http.Request) {
var b Book
if err := json.NewDecoder(r.Body).Decode(&b); err != nil || b.ID == "" || b.Title == "" {
http.Error(w, "id and title are required", http.StatusBadRequest)
return
}
s.mu.Lock()
s.books[b.ID] = b
s.mu.Unlock()
w.WriteHeader(http.StatusCreated)
}
Step 2: Test a GET Request with the Recorder
Next, we test the happy path. We build a request, call the routes, and then decode the JSON body.
func TestGetBook(t *testing.T) {
h := NewStore().Routes()
req := httptest.NewRequest(http.MethodGet, "/books/1", nil)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", rec.Code, http.StatusOK)
}
var got Book
if err := json.NewDecoder(rec.Body).Decode(&got); err != nil {
t.Fatal(err)
}
if got.Title != "Go in Action" {
t.Errorf("title = %q, want %q", got.Title, "Go in Action")
}
}
Here, t.Fatalf stops the test at once, because checking the body makes no sense after a wrong status. In contrast, t.Errorf records a failure and keeps going.
Step 3: Combine Go httptest with a Table
Now we combine the table style from the last lesson with the POST route. Each row sends a different body and expects a different status code.
func TestCreateBookValidation(t *testing.T) {
tests := []struct {
name string
body string
want int
}{
{"valid book", `{"id":"2","title":"Learning Go"}`, http.StatusCreated},
{"missing title", `{"id":"3"}`, http.StatusBadRequest},
{"bad json", `{oops`, http.StatusBadRequest},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := NewStore().Routes()
req := httptest.NewRequest(http.MethodPost, "/books", strings.NewReader(tt.body))
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != tt.want {
t.Errorf("status = %d, want %d", rec.Code, tt.want)
}
})
}
}
Notice that each subtest creates a fresh store. As a result, one case can never change the data of another.
Step 4: A Full Server Test
Finally, we start a real test server and use the normal HTTP client against it.
func TestFullServer(t *testing.T) {
srv := httptest.NewServer(NewStore().Routes())
defer srv.Close()
resp, err := http.Get(srv.URL + "/books/99")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusNotFound {
t.Errorf("status = %d, want 404", resp.StatusCode)
}
t.Logf("body: %s", strings.TrimSpace(string(body)))
}
The srv.URL value holds an address such as http://127.0.0.1:41233. Also, defer srv.Close() shuts the server down when the test ends. Now run go test -v and look at the real output.
=== RUN TestGetBook
--- PASS: TestGetBook (0.00s)
=== RUN TestCreateBookValidation
=== RUN TestCreateBookValidation/valid_book
=== RUN TestCreateBookValidation/missing_title
=== RUN TestCreateBookValidation/bad_json
--- PASS: TestCreateBookValidation (0.00s)
--- PASS: TestCreateBookValidation/valid_book (0.00s)
--- PASS: TestCreateBookValidation/missing_title (0.00s)
--- PASS: TestCreateBookValidation/bad_json (0.00s)
=== RUN TestFullServer
books_test.go:67: body: book not found
--- PASS: TestFullServer (0.00s)
PASS
All tests pass in a few milliseconds. In addition, you now test the routes, the JSON and the status codes without starting any program by hand.
Step 5: Test Middleware with Go httptest
Middleware is also just a function that wraps a handler. So you can test it the same way. Here is a small check that rejects requests without the right API key.
func requireKey(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("X-API-Key") != "secret" {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
Now we test three cases with one table: no key, a wrong key and the right key. We pass a tiny handler that returns 204, so we only test the middleware.
func TestRequireKey(t *testing.T) {
ok := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
h := requireKey(ok)
tests := []struct {
name string
key string
want int
}{
{"no key", "", http.StatusUnauthorized},
{"wrong key", "nope", http.StatusUnauthorized},
{"right key", "secret", http.StatusNoContent},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
if tt.key != "" {
req.Header.Set("X-API-Key", tt.key)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != tt.want {
t.Errorf("status = %d, want %d", rec.Code, tt.want)
}
})
}
}
Running go test -v -run RequireKey prints three passing subtests: no_key, wrong_key and right_key. This idea works for logging, rate limiting and token checks too. For example, you can reuse it for the JWT middleware from earlier lessons.
Common Mistakes with Go httptest
- Calling the handler instead of the mux: path values stay empty, so the test gives wrong results. Therefore, always call
Routes(). - Sharing one store across subtests: cases then affect each other. Instead, create fresh data in each subtest.
- Forgetting to close the server: the port stays open until the test binary exits. So use
defer srv.Close(). - Checking only the status code: a 200 with the wrong JSON is still a bug. Also check the body and headers.
- Reading the body twice: a recorder body is a buffer, and a second read may give nothing. So read it once and keep the value.
Best Practices for Go httptest
- Prefer the recorder for handlers, because it is the fastest option.
- Test errors as much as success, since users hit error paths often.
- Use small helper functions for building requests, because they cut repeated lines.
- **Set the
Content-Typeheader** in requests that send JSON, so you match real clients. - **Run with
go test -race**, since handlers often run in many goroutines. - Use interfaces for databases, so tests can pass a fake store instead of a real one.
Practice Task
To practise Go httptest, add a DELETE /books/{id} route. It should return 204 when the book exists and 404 when it does not. Then write a table test with at least three cases.
Hint: use delete(s.books, id) inside a write lock. After that, send a GET request in the same test and check that it now returns 404.
Official Resources
These pages describe the package and the handler types used in this lesson.
- net/http/httptest package documentation
- net/http package documentation
- Routing enhancements for Go 1.22
Quick Recap
- Go httptest tests HTTP code without a real network.
NewRequestbuilds a fake request, andNewRecordercaptures the response.- Call the mux, not a single handler, when the route uses path values.
- Use
NewServerwhen you test a client or a full flow. - Combine Go httptest with table-driven tests for many status codes.
- Create fresh data in each subtest and close any test server.
What’s Next?
By now, you can test handlers quickly. However, handlers run in many goroutines at once, and that can hide a nasty kind of bug. So next, we will learn how the race detector finds data races.
Next up: Go race detector and data races


