ZetCode

Go httptest

last modified November 19, 2026 Go 1.27

In this article we show how to test HTTP code in Go with the net/http/httptest package. We test handlers with a response recorder, write table-driven tests, check status codes, headers and JSON, test routes and middleware, run a real test server and test an HTTP client against a fake service.

All examples in this article were run with Go 1.27.0 on Linux. The test servers listen on random loopback ports, so the port numbers in the outputs differ from run to run.

The httptest package

An HTTP handler is a function or type that writes a response to an http.ResponseWriter for an *http.Request. Testing it through a real server and network would be slow and awkward. The httptest package provides two tools instead:

NewRequest builds an incoming server request for the tests. The testing article introduces go test and table-driven tests; the HTTP server article shows how handlers are written.

Testing a handler

We create a module with go mod init example.com/app and put a small handler into the app package. All files of this article live in this one directory.

hello.go
package app

import (
    "fmt"
    "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {

    name := r.URL.Query().Get("name")
    if name == "" {
        name = "there"
    }

    fmt.Fprintf(w, "Hello, %s!\n", name)
}

The handler greets the name from the query string, or a default name when there is none.

hello_test.go
package app

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

func TestHello(t *testing.T) {

    req := httptest.NewRequest("GET", "/hello?name=Lucia", nil)
    rec := httptest.NewRecorder()

    helloHandler(rec, req)

    if rec.Code != http.StatusOK {
        t.Errorf("status = %d, want %d", rec.Code, http.StatusOK)
    }

    want := "Hello, Lucia!\n"
    if got := rec.Body.String(); got != want {
        t.Errorf("body = %q, want %q", got, want)
    }
}

The test calls the handler directly, without a server.

req := httptest.NewRequest("GET", "/hello?name=Lucia", nil)
rec := httptest.NewRecorder()

NewRequest creates a request as a server would receive it. Unlike http.NewRequest, it does not return an error; it panics on an invalid target, which in a test is a bug anyway. The third argument is the request body.

helloHandler(rec, req)

Since the recorder is an http.ResponseWriter, we can pass it to the handler like any other writer.

if rec.Code != http.StatusOK {

Afterwards, rec.Code holds the status code and rec.Body the written body. A handler that writes no status explicitly gets 200 OK, as with a real server.

$ go test -v -run TestHello
=== RUN   TestHello
--- PASS: TestHello (0.00s)
PASS
ok  	example.com/app	0.002s

Table-driven tests

To test the handler with several inputs, we put the cases into a table and run each one as a subtest.

hello_names_test.go
package app

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

func TestHelloNames(t *testing.T) {

    tests := []struct {
        name   string
        target string
        want   string
    }{
        {"with name", "/hello?name=Lucia", "Hello, Lucia!\n"},
        {"without name", "/hello", "Hello, there!\n"},
        {"empty name", "/hello?name=", "Hello, there!\n"},
        {"escaped name", "/hello?name=Jan%20Novak", "Hello, Jan Novak!\n"},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {

            req := httptest.NewRequest("GET", tt.target, nil)
            rec := httptest.NewRecorder()

            helloHandler(rec, req)

            if got := rec.Body.String(); got != tt.want {
                t.Errorf("body = %q, want %q", got, tt.want)
            }
        })
    }
}

Each row has a name, a request target and the expected body.

t.Run(tt.name, func(t *testing.T) {

t.Run starts a subtest with its own name and result. A failure in one case does not stop the others, and a single case can be run with -run, for example -run 'TestHelloNames/empty'.

{"escaped name", "/hello?name=Jan%20Novak", "Hello, Jan Novak!\n"},

The query string is decoded by the net/url package before the handler sees it, so %20 becomes a space. Spaces in subtest names are replaced with underscores in the output.

$ go test -v -run TestHelloNames
=== RUN   TestHelloNames
=== RUN   TestHelloNames/with_name
=== RUN   TestHelloNames/without_name
=== RUN   TestHelloNames/empty_name
=== RUN   TestHelloNames/escaped_name
--- PASS: TestHelloNames (0.00s)
    --- PASS: TestHelloNames/with_name (0.00s)
    --- PASS: TestHelloNames/without_name (0.00s)
    --- PASS: TestHelloNames/empty_name (0.00s)
    --- PASS: TestHelloNames/escaped_name (0.00s)
PASS
ok  	example.com/app	0.002s

Methods and headers

Now the handler accepts only GET and sets the content type. A request with another method gets 405 Method Not Allowed and an Allow header.

hello.go
package app

import (
    "fmt"
    "net/http"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {

    if r.Method != http.MethodGet {
        w.Header().Set("Allow", http.MethodGet)
        http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
        return
    }

    name := r.URL.Query().Get("name")
    if name == "" {
        name = "there"
    }

    w.Header().Set("Content-Type", "text/plain; charset=utf-8")
    fmt.Fprintf(w, "Hello, %s!\n", name)
}

http.Error writes a plain-text error message with the given status code. Headers must be set before the status is written.

hello_method_test.go
package app

import (
    "io"
    "net/http"
    "net/http/httptest"
    "testing"
)

func TestHelloMethods(t *testing.T) {

    req := httptest.NewRequest("POST", "/hello", nil)
    rec := httptest.NewRecorder()

    helloHandler(rec, req)

    res := rec.Result()
    defer res.Body.Close()

    if res.StatusCode != http.StatusMethodNotAllowed {
        t.Errorf("status = %d, want %d", res.StatusCode, http.StatusMethodNotAllowed)
    }

    if got := res.Header.Get("Allow"); got != "GET" {
        t.Errorf("Allow = %q, want %q", got, "GET")
    }

    body, err := io.ReadAll(res.Body)
    if err != nil {
        t.Fatal(err)
    }

    t.Logf("%s %q", res.Status, body)
}

This test checks the response the way an HTTP client would see it.

res := rec.Result()
defer res.Body.Close()

Result returns the recorded response as an *http.Response, with StatusCode, Status, Header and a readable Body. Helper functions written for client responses can then check recorded responses too.

body, err := io.ReadAll(res.Body)
if err != nil {
    t.Fatal(err)
}

t.Fatal marks the test as failed and stops it at once, while t.Errorf lets it continue. t.Logf prints a message that go test shows with -v or when the test fails.

$ go test -v -run TestHelloMethods
=== RUN   TestHelloMethods
    hello_method_test.go:33: 405 Method Not Allowed "method not allowed\n"
--- PASS: TestHelloMethods (0.00s)
PASS
ok  	example.com/app	0.003s

Testing a JSON handler

The next handler creates users from a JSON request body. The users live in a store protected by a mutex, because a server calls handlers from many goroutines.

users.go
package app

import (
    "encoding/json"
    "fmt"
    "net/http"
    "sync"
)

type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
}

type userStore struct {
    mu    sync.Mutex
    users []User
}

func (s *userStore) create(w http.ResponseWriter, r *http.Request) {

    var u User
    if err := json.NewDecoder(r.Body).Decode(&u); err != nil || u.Name == "" {
        http.Error(w, "invalid user", http.StatusBadRequest)
        return
    }

    s.mu.Lock()
    u.ID = len(s.users) + 1
    s.users = append(s.users, u)
    s.mu.Unlock()

    w.Header().Set("Content-Type", "application/json")
    w.Header().Set("Location", fmt.Sprintf("/users/%d", u.ID))
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(u)
}

The create method decodes the body, rejects invalid input with 400 Bad Request, and answers 201 Created with a Location header and the new user as JSON.

users_test.go
package app

import (
    "encoding/json"
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"
)

func TestCreateUser(t *testing.T) {

    store := &userStore{}

    body := strings.NewReader(`{"name": "Lucia"}`)
    req := httptest.NewRequest("POST", "/users", body)
    rec := httptest.NewRecorder()

    store.create(rec, req)

    if rec.Code != http.StatusCreated {
        t.Fatalf("status = %d, want %d", rec.Code, http.StatusCreated)
    }

    if got := rec.Header().Get("Location"); got != "/users/1" {
        t.Errorf("Location = %q, want %q", got, "/users/1")
    }

    var u User
    if err := json.NewDecoder(rec.Body).Decode(&u); err != nil {
        t.Fatal(err)
    }

    if u != (User{ID: 1, Name: "Lucia"}) {
        t.Errorf("user = %+v", u)
    }
}

func TestCreateUserInvalid(t *testing.T) {

    store := &userStore{}

    for _, body := range []string{`{"name": ""}`, `{"name": `, `[]`} {

        req := httptest.NewRequest("POST", "/users", strings.NewReader(body))
        rec := httptest.NewRecorder()

        store.create(rec, req)

        if rec.Code != http.StatusBadRequest {
            t.Errorf("%s: status = %d, want %d", body, rec.Code, http.StatusBadRequest)
        }
    }
}

Each test creates its own store, so the tests do not depend on each other.

body := strings.NewReader(`{"name": "Lucia"}`)
req := httptest.NewRequest("POST", "/users", body)

The request body is any io.Reader; a string reader is the simplest one.

if u != (User{ID: 1, Name: "Lucia"}) {

We decode the recorded body back into a User and compare it as a struct. Comparing decoded values is more robust than comparing JSON text, which depends on field order and spacing.

for _, body := range []string{`{"name": ""}`, `{"name": `, `[]`} {

The second test sends an empty name, broken JSON and a value of the wrong type; all three must be rejected.

$ go test -v -run TestCreateUser
=== RUN   TestCreateUser
--- PASS: TestCreateUser (0.00s)
=== RUN   TestCreateUserInvalid
--- PASS: TestCreateUserInvalid (0.00s)
PASS
ok  	example.com/app	0.007s

Testing routes

Handlers that read path values, such as {id}, depend on the router. The next file adds a handler that returns one user and a function that builds the router.

routes.go
package app

import (
    "encoding/json"
    "net/http"
    "strconv"
)

func (s *userStore) get(w http.ResponseWriter, r *http.Request) {

    id, err := strconv.Atoi(r.PathValue("id"))

    s.mu.Lock()
    defer s.mu.Unlock()

    if err != nil || id < 1 || id > len(s.users) {
        http.NotFound(w, r)
        return
    }

    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(s.users[id-1])
}

func newMux() *http.ServeMux {

    store := &userStore{}

    mux := http.NewServeMux()
    mux.HandleFunc("GET /hello", helloHandler)
    mux.HandleFunc("POST /users", store.create)
    mux.HandleFunc("GET /users/{id}", store.get)

    return mux
}

newMux registers the handlers with method and path patterns. r.PathValue("id") returns the {id} part of the path, but only for requests that went through the mux.

routes_test.go
package app

import (
    "net/http/httptest"
    "strings"
    "testing"
)

func TestRoutes(t *testing.T) {

    mux := newMux()

    req := httptest.NewRequest("POST", "/users", strings.NewReader(`{"name": "Lucia"}`))
    rec := httptest.NewRecorder()
    mux.ServeHTTP(rec, req)

    if rec.Code != 201 {
        t.Fatalf("create user: status = %d", rec.Code)
    }

    tests := []struct {
        method, target string
        status         int
        body           string
    }{
        {"GET", "/users/1", 200, `{"id":1,"name":"Lucia"}` + "\n"},
        {"GET", "/users/2", 404, "404 page not found\n"},
        {"GET", "/users/abc", 404, "404 page not found\n"},
        {"DELETE", "/users/1", 405, "Method Not Allowed\n"},
        {"GET", "/hello?name=Tom", 200, "Hello, Tom!\n"},
    }

    for _, tt := range tests {
        t.Run(tt.method+" "+tt.target, func(t *testing.T) {

            rec := httptest.NewRecorder()
            mux.ServeHTTP(rec, httptest.NewRequest(tt.method, tt.target, nil))

            if rec.Code != tt.status || rec.Body.String() != tt.body {
                t.Errorf("got %d %q, want %d %q",
                    rec.Code, rec.Body.String(), tt.status, tt.body)
            }
        })
    }
}

The test sends every request through mux.ServeHTTP, so the patterns, path values and method checks are all part of the test.

req := httptest.NewRequest("POST", "/users", strings.NewReader(`{"name": "Lucia"}`))
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)

The first request creates a user that the cases below can read. A failed setup stops the test with t.Fatalf.

{"DELETE", "/users/1", 405, "Method Not Allowed\n"},

The 404 and 405 responses come from the mux itself; no handler of ours runs for them. Calling store.get directly would skip the router and PathValue would return an empty string; a test that does so must set the value with req.SetPathValue.

$ go test -v -run TestRoutes
=== RUN   TestRoutes
=== RUN   TestRoutes/GET_/users/1
=== RUN   TestRoutes/GET_/users/2
=== RUN   TestRoutes/GET_/users/abc
=== RUN   TestRoutes/DELETE_/users/1
=== RUN   TestRoutes/GET_/hello?name=Tom
--- PASS: TestRoutes (0.00s)
    --- PASS: TestRoutes/GET_/users/1 (0.00s)
    --- PASS: TestRoutes/GET_/users/2 (0.00s)
    --- PASS: TestRoutes/GET_/users/abc (0.00s)
    --- PASS: TestRoutes/DELETE_/users/1 (0.00s)
    --- PASS: TestRoutes/GET_/hello?name=Tom (0.00s)
PASS
ok  	example.com/app	0.002s

Testing middleware

Middleware wraps a handler and decides whether to call it. This one requires a bearer token in the Authorization header.

auth.go
package app

import "net/http"

func requireToken(token string, next http.Handler) http.Handler {

    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

        if r.Header.Get("Authorization") != "Bearer "+token {
            w.Header().Set("WWW-Authenticate", "Bearer")
            http.Error(w, "unauthorized", http.StatusUnauthorized)
            return
        }

        next.ServeHTTP(w, r)
    })
}

Without the right token, the middleware answers 401 Unauthorized and never calls the next handler.

auth_test.go
package app

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

func TestRequireToken(t *testing.T) {

    tests := []struct {
        name   string
        header string
        status int
        called bool
    }{
        {"no header", "", 401, false},
        {"wrong token", "Bearer guess", 401, false},
        {"wrong scheme", "Basic s3cret", 401, false},
        {"valid token", "Bearer s3cret", 200, true},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {

            called := false
            next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
                called = true
            })

            req := httptest.NewRequest("GET", "/admin", nil)
            if tt.header != "" {
                req.Header.Set("Authorization", tt.header)
            }
            rec := httptest.NewRecorder()

            requireToken("s3cret", next).ServeHTTP(rec, req)

            if rec.Code != tt.status || called != tt.called {
                t.Errorf("status = %d, called = %t; want %d, %t",
                    rec.Code, called, tt.status, tt.called)
            }
        })
    }
}

The test checks both the status code and whether the wrapped handler ran.

called := false
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    called = true
})

Instead of a real handler, the middleware wraps a stub that only records the call. This tests the middleware alone; for 401 responses, called must stay false.

$ go test -v -run TestRequireToken
=== RUN   TestRequireToken
=== RUN   TestRequireToken/no_header
=== RUN   TestRequireToken/wrong_token
=== RUN   TestRequireToken/wrong_scheme
=== RUN   TestRequireToken/valid_token
--- PASS: TestRequireToken (0.00s)
    --- PASS: TestRequireToken/no_header (0.00s)
    --- PASS: TestRequireToken/wrong_token (0.00s)
    --- PASS: TestRequireToken/wrong_scheme (0.00s)
    --- PASS: TestRequireToken/valid_token (0.00s)
PASS
ok  	example.com/app	0.002s

A real test server

A recorder does not test what happens on the wire: connections, status lines or headers added by the server. httptest.NewServer starts the whole router on a real port.

server_test.go
package app

import (
    "io"
    "net/http"
    "net/http/httptest"
    "strings"
    "testing"
)

func TestServer(t *testing.T) {

    ts := httptest.NewServer(newMux())
    defer ts.Close()

    t.Log("server listening at", ts.URL)

    client := ts.Client()

    res, err := client.Post(ts.URL+"/users", "application/json",
        strings.NewReader(`{"name": "Lucia"}`))
    if err != nil {
        t.Fatal(err)
    }
    res.Body.Close()

    location := res.Header.Get("Location")
    t.Log("POST /users:", res.Status, location)

    res, err = client.Get(ts.URL + location)
    if err != nil {
        t.Fatal(err)
    }
    defer res.Body.Close()

    body, err := io.ReadAll(res.Body)
    if err != nil {
        t.Fatal(err)
    }

    t.Logf("GET %s: %s %s", location, res.Status, body)

    if res.StatusCode != http.StatusOK {
        t.Errorf("status = %d, want %d", res.StatusCode, http.StatusOK)
    }
}

The test creates a user and then follows the Location header to read it, just like a real client.

ts := httptest.NewServer(newMux())
defer ts.Close()

NewServer listens on a random port of the loopback interface and serves the handler in the background. ts.URL holds the base address, for example http://127.0.0.1:43887. Close shuts the server down and waits for running requests.

client := ts.Client()

ts.Client returns an http.Client configured for the test server. For a plain HTTP server, http.DefaultClient would work too; for a TLS server it would not, as we show below.

$ go test -v -run TestServer
=== RUN   TestServer
    server_test.go:16: server listening at http://127.0.0.1:43887
    server_test.go:28: POST /users: 201 Created /users/1
    server_test.go:41: GET /users/1: 200 OK {"id":1,"name":"Lucia"}
--- PASS: TestServer (0.00s)
PASS
ok  	example.com/app	0.003s

Testing an HTTP client

httptest.NewServer is just as useful in the other direction: testing code that calls an HTTP API. The following client reads the current temperature from a weather service.

weather.go
package app

import (
    "context"
    "encoding/json"
    "fmt"
    "net/http"
    "net/url"
)

type WeatherClient struct {
    BaseURL string
    HTTP    *http.Client
}

func (c *WeatherClient) Temperature(ctx context.Context, city string) (float64, error) {

    query := url.Values{"city": {city}}
    target := c.BaseURL + "/current?" + query.Encode()

    req, err := http.NewRequestWithContext(ctx, "GET", target, nil)
    if err != nil {
        return 0, err
    }
    req.Header.Set("Accept", "application/json")

    res, err := c.HTTP.Do(req)
    if err != nil {
        return 0, err
    }
    defer res.Body.Close()

    if res.StatusCode != http.StatusOK {
        return 0, fmt.Errorf("weather service: %s", res.Status)
    }

    var data struct {
        Temp float64 `json:"temp"`
    }
    if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
        return 0, err
    }

    return data.Temp, nil
}

The base URL and the http.Client are fields rather than constants, so a test can point the client at a fake service. The HTTP client article covers requests with a context.

weather_test.go
package app

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

func newWeatherClient(t *testing.T, h http.HandlerFunc) *WeatherClient {

    t.Helper()

    ts := httptest.NewServer(h)
    t.Cleanup(ts.Close)

    return &WeatherClient{BaseURL: ts.URL, HTTP: ts.Client()}
}

func TestTemperature(t *testing.T) {

    client := newWeatherClient(t, func(w http.ResponseWriter, r *http.Request) {

        t.Logf("%s %s, Accept: %s", r.Method, r.URL, r.Header.Get("Accept"))

        if r.URL.Path != "/current" || r.URL.Query().Get("city") != "New York" {
            http.NotFound(w, r)
            return
        }

        w.Header().Set("Content-Type", "application/json")
        fmt.Fprintln(w, `{"city": "New York", "temp": 21.5}`)
    })

    temp, err := client.Temperature(t.Context(), "New York")
    if err != nil {
        t.Fatal(err)
    }

    if temp != 21.5 {
        t.Errorf("temperature = %v, want 21.5", temp)
    }
}

The fake service checks the request and answers with canned JSON.

func newWeatherClient(t *testing.T, h http.HandlerFunc) *WeatherClient {

    t.Helper()

    ts := httptest.NewServer(h)
    t.Cleanup(ts.Close)

The helper starts a server for a handler and returns a client for it. t.Cleanup registers ts.Close to run when the test ends, so callers need no defer. t.Helper makes failures report the caller's line instead of the helper's.

t.Logf("%s %s, Accept: %s", r.Method, r.URL, r.Header.Get("Accept"))

The handler runs on the server, but it can still use t. The log line shows the request the client sent: the space in the city name was encoded as +.

temp, err := client.Temperature(t.Context(), "New York")

t.Context returns a context that is canceled when the test ends.

$ go test -v -run 'TestTemperature$'
=== RUN   TestTemperature
    weather_test.go:24: GET /current?city=New+York, Accept: application/json
--- PASS: TestTemperature (0.00s)
PASS
ok  	example.com/app	0.003s

Errors and timeouts

A fake server makes failures easy to produce: error statuses, broken responses or a service that does not answer in time.

weather_errors_test.go
package app

import (
    "context"
    "errors"
    "net/http"
    "testing"
    "time"
)

func TestTemperatureStatus(t *testing.T) {

    client := newWeatherClient(t, func(w http.ResponseWriter, r *http.Request) {
        http.Error(w, "try later", http.StatusServiceUnavailable)
    })

    _, err := client.Temperature(t.Context(), "Oslo")
    if err == nil {
        t.Fatal("expected an error")
    }

    t.Log(err)
}

func TestTemperatureTimeout(t *testing.T) {

    client := newWeatherClient(t, func(w http.ResponseWriter, r *http.Request) {
        select {
        case <-time.After(2 * time.Second):
        case <-r.Context().Done():
        }
    })

    ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond)
    defer cancel()

    _, err := client.Temperature(ctx, "Oslo")
    if !errors.Is(err, context.DeadlineExceeded) {
        t.Fatalf("err = %v, want a deadline error", err)
    }

    t.Log(err)
}

The two tests reuse the helper from the previous section.

http.Error(w, "try later", http.StatusServiceUnavailable)

The first fake service always fails, and the client must return an error that includes the status.

select {
case <-time.After(2 * time.Second):
case <-r.Context().Done():
}

The second service is slow. It also returns as soon as the client gives up: ts.Close waits for running handlers, and a handler that ignored the canceled request would delay the test by two seconds.

if !errors.Is(err, context.DeadlineExceeded) {

The client's context expires after 100 ms. The returned error wraps context.DeadlineExceeded; the test duration shows that it did not wait for the slow handler.

$ go test -v -run 'TestTemperature(Status|Timeout)'
=== RUN   TestTemperatureStatus
    weather_errors_test.go:22: weather service: 503 Service Unavailable
--- PASS: TestTemperatureStatus (0.00s)
=== RUN   TestTemperatureTimeout
    weather_errors_test.go:42: Get "http://127.0.0.1:35587/current?city=Oslo": context deadline exceeded
--- PASS: TestTemperatureTimeout (0.10s)
PASS
ok  	example.com/app	0.105s

A TLS test server

Code that requires HTTPS can be tested with a TLS server. The httptest package generates a certificate for it.

tls_test.go
package app

import (
    "crypto/x509"
    "errors"
    "io"
    "log"
    "net/http"
    "net/http/httptest"
    "testing"
)

func TestTLS(t *testing.T) {

    ts := httptest.NewUnstartedServer(newMux())
    ts.Config.ErrorLog = log.New(io.Discard, "", 0)
    ts.StartTLS()
    defer ts.Close()

    t.Log("server listening at", ts.URL)

    res, err := ts.Client().Get(ts.URL + "/hello?name=TLS")
    if err != nil {
        t.Fatal(err)
    }
    defer res.Body.Close()

    body, err := io.ReadAll(res.Body)
    if err != nil {
        t.Fatal(err)
    }

    t.Logf("%s %s %q", res.Proto, res.Status, body)

    _, err = http.Get(ts.URL + "/hello")

    var authErr x509.UnknownAuthorityError
    if !errors.As(err, &authErr) {
        t.Fatalf("err = %v, want an unknown authority error", err)
    }

    t.Log("default client:", err)
}

The test talks to the server with two clients: one that trusts the test certificate and the default one.

ts := httptest.NewUnstartedServer(newMux())
ts.Config.ErrorLog = log.New(io.Discard, "", 0)
ts.StartTLS()

NewUnstartedServer creates the server without starting it, so it can be configured first; StartTLS starts it with HTTPS. httptest.NewTLSServer does both in one call. Here we discard the server's error log, which would otherwise report the handshake rejected by the default client.

res, err := ts.Client().Get(ts.URL + "/hello?name=TLS")

ts.Client trusts the server's certificate, so the request succeeds.

var authErr x509.UnknownAuthorityError
if !errors.As(err, &authErr) {

The default client does not know the test certificate authority and refuses the connection. This is why tests should use ts.Client, and never turn certificate checks off.

$ go test -v -run TestTLS
=== RUN   TestTLS
    tls_test.go:20: server listening at https://127.0.0.1:39229
    tls_test.go:33: HTTP/1.1 200 OK "Hello, TLS!\n"
    tls_test.go:42: default client: Get "https://127.0.0.1:39229/hello": tls: failed to verify certificate: x509: certificate signed by unknown authority
--- PASS: TestTLS (0.01s)
PASS
ok  	example.com/app	0.015s

Running the whole suite

Finally, we run all tests at once. The -race option enables the race detector, which checks for unsynchronized access to shared data, for example to the user store; -cover reports how many statements the tests executed. Without -v, go test prints only the summary and the output of failing tests.

$ go test -race -cover
PASS
coverage: 97.9% of statements
ok  	example.com/app	1.221s

Source

Go httptest package - reference
Go testing package - reference
Go net/http package - reference

In this article we have tested HTTP code in Go with the httptest package: handlers with a response recorder, table-driven tests, methods and headers, JSON, routes, middleware, a real test server, an HTTP client against a fake service, errors, timeouts and TLS. The testing article covers the basics of go test, and the HTTP server and HTTP client articles show the code being tested.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Go tutorials.