Testing Go net/http handlers

Featured image for sharing metadata for article

When writing Go web services, it's very likely that you'll be unit testing the HTTP handlers, as well as doing some wider integration tests on your application.

Something nice about Go is the httptest package in the standard library, providing a very handy means to test HTTP logic.

This means that if we had the following, very straightforward handler:

func Handler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("tracing-id", r.Header.Get("tracing-id"))
	w.WriteHeader(401)
}

We can then write the following unit test:

func Test_Handler_status(t *testing.T) {
	rr := httptest.NewRecorder()
	req := httptest.NewRequest("GET", "/apis", nil)
	req.Header.Add("tracing-id", "123")

	Handler(rr, req)

	if rr.Result().StatusCode != 401 {
		t.Errorf("Status code returned, %d, did not match expected code %d", rr.Result().StatusCode, 401)
	}
	if rr.Result().Header.Get("tracing-id") != "123" {
		t.Errorf("Header value for `tracing-id`, %s, did not match expected value %s", rr.Result().Header.Get("tracing-id"), "123")
	}
}

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #go.

Also on:

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.