{"id":428,"date":"2026-05-21T09:00:00","date_gmt":"2026-05-21T03:30:00","guid":{"rendered":"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/"},"modified":"2026-05-21T09:00:00","modified_gmt":"2026-05-21T03:30:00","slug":"go-httptest-handlers","status":"publish","type":"post","link":"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/","title":{"rendered":"Go httptest: Test HTTP Handlers Step by Step"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This lesson follows <a href=\"https:\/\/smitabharat.com\/blog\/go-table-driven-tests-benchmarks\/\">Go table-driven tests and benchmarks<\/a>, so we reuse the same table style. We also build on <a href=\"https:\/\/smitabharat.com\/blog\/go-http-server-beginners\/\">Go HTTP server basics<\/a> and <a href=\"https:\/\/smitabharat.com\/blog\/go-rest-api-tutorial\/\">Go REST API for beginners<\/a>. If those ideas are new, read them first.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What Is Go httptest?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">In short, <code>net\/http\/httptest<\/code> gives you tools to test HTTP code quickly. It has two main helpers. The first is <code>httptest.NewRecorder<\/code>, which acts like a fake response writer. The second is <code>httptest.NewServer<\/code>, which starts a real server on a random local port.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Think of a flight simulator. Pilots practise takeoffs and landings without leaving the ground. Similarly, Go httptest lets your handler &#8220;take off&#8221; many times without any real network, so tests are fast and safe.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Why Go httptest Matters<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Speed<\/strong>: a recorder test runs in microseconds, since no network is used.<\/li>\n\n\n\n<li><strong>Reliability<\/strong>: no port clashes, no firewalls and no waiting for a server to start.<\/li>\n\n\n\n<li><strong>Full control<\/strong>: you choose the method, path, headers and body of every request.<\/li>\n\n\n\n<li><strong>Easy checks<\/strong>: you can inspect the status code, headers and body in one place.<\/li>\n\n\n\n<li><strong>Safe refactoring<\/strong>: you can change the code inside a handler and keep the same tests.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Because of this, nearly every Go web project uses <code>httptest<\/code> 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.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">How Go httptest Works<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">First, you build a request with <code>httptest.NewRequest<\/code>. Next, you create a recorder with <code>httptest.NewRecorder<\/code>. Then you call <code>handler.ServeHTTP(rec, req)<\/code>. Finally, you read <code>rec.Code<\/code>, <code>rec.Header()<\/code> and <code>rec.Body<\/code> to check the result.<\/p>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><a href=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-diagram-1.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-diagram-1-1024x640.png\" alt=\"Go httptest diagram showing a fake request, a recorder, the handler call and the result checks\" class=\"wp-image-403\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-diagram-1-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-diagram-1-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-diagram-1-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-diagram-1-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-diagram-1-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">A test builds a fake request, passes it with a recorder to the handler, and then reads the status code, headers and body from the recorder.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The Request and the Recorder<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>NewRequest<\/code> 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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What to Check in a Response<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A recorder keeps several things you can inspect. The table below lists the most useful ones.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>What to check<\/th><th>How to read it<\/th><th>Example<\/th><\/tr><\/thead><tbody><tr><td>Status code<\/td><td><code>rec.Code<\/code><\/td><td><code>200<\/code>, <code>404<\/code><\/td><\/tr><tr><td>Headers<\/td><td><code>rec.Header().Get(\"Content-Type\")<\/code><\/td><td><code>application\/json<\/code><\/td><\/tr><tr><td>Body text<\/td><td><code>rec.Body.String()<\/code><\/td><td><code>book not found<\/code><\/td><\/tr><tr><td>Decoded JSON<\/td><td><code>json.NewDecoder(rec.Body).Decode(&amp;v)<\/code><\/td><td>A <code>Book<\/code> struct<\/td><\/tr><tr><td>Full result<\/td><td><code>rec.Result()<\/code><\/td><td>A normal <code>*http.Response<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>rec.Result()<\/code> when you need a real <code>*http.Response<\/code>, for example to read cookies.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Path Values in Go 1.22 and Later<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Since Go 1.22, the standard mux supports patterns such as <code>GET \/books\/{id}<\/code>. The handler reads the value with <code>r.PathValue(\"id\")<\/code>. Because the mux does the matching, you should test through the mux, not through a single handler function. Otherwise <code>PathValue<\/code> returns an empty string.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Go httptest: Recorder vs Test Server<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Both tools test HTTP code, but they work differently. The table below compares them.<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><thead><tr><th>Feature<\/th><th>NewRecorder<\/th><th>NewServer<\/th><\/tr><\/thead><tbody><tr><td>Real network port<\/td><td>No<\/td><td>Yes, on localhost<\/td><\/tr><tr><td>Speed<\/td><td>Fastest<\/td><td>Slower, but still quick<\/td><\/tr><tr><td>Tests middleware and routing<\/td><td>Yes, through the mux<\/td><td>Yes<\/td><\/tr><tr><td>Tests an HTTP client<\/td><td>No<\/td><td>Yes<\/td><\/tr><tr><td>Best for<\/td><td>Handler logic<\/td><td>Client code and full flows<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<figure class=\"wp-block-image aligncenter size-large\"><a href=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-diagram-2.png\"><img loading=\"lazy\" decoding=\"async\" width=\"1024\" height=\"640\" src=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-diagram-2-1024x640.png\" alt=\"Go httptest diagram comparing NewRecorder with NewServer\" class=\"wp-image-404\" srcset=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-diagram-2-1024x640.png 1024w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-diagram-2-300x188.png 300w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-diagram-2-768x480.png 768w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-diagram-2-1536x960.png 1536w, https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-diagram-2-2048x1280.png 2048w\" sizes=\"auto, (max-width: 1024px) 100vw, 1024px\" \/><\/a><figcaption class=\"wp-element-caption\">The recorder calls the handler directly inside the test, while the test server opens a local port and receives real HTTP calls.<\/figcaption><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>NewServer<\/code> when you test code that makes HTTP calls, such as an API client.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Go httptest Hands-On: Test a Book API<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s test a tiny book API. It has two routes: <code>GET \/books\/{id}<\/code> and <code>POST \/books<\/code>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 1: The Handlers<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>type Book struct {\n\tID    string `json:\"id\"`\n\tTitle string `json:\"title\"`\n}\n\ntype Store struct {\n\tmu    sync.RWMutex\n\tbooks map[string]Book\n}\n\nfunc NewStore() *Store {\n\treturn &amp;Store{books: map[string]Book{\"1\": {ID: \"1\", Title: \"Go in Action\"}}}\n}\n\nfunc (s *Store) Routes() http.Handler {\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"GET \/books\/{id}\", s.getBook)\n\tmux.HandleFunc(\"POST \/books\", s.createBook)\n\treturn mux\n}\n\nfunc (s *Store) getBook(w http.ResponseWriter, r *http.Request) {\n\ts.mu.RLock()\n\tb, ok := s.books[r.PathValue(\"id\")]\n\ts.mu.RUnlock()\n\tif !ok {\n\t\thttp.Error(w, \"book not found\", http.StatusNotFound)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application\/json\")\n\tjson.NewEncoder(w).Encode(b)\n}\n\nfunc (s *Store) createBook(w http.ResponseWriter, r *http.Request) {\n\tvar b Book\n\tif err := json.NewDecoder(r.Body).Decode(&amp;b); err != nil || b.ID == \"\" || b.Title == \"\" {\n\t\thttp.Error(w, \"id and title are required\", http.StatusBadRequest)\n\t\treturn\n\t}\n\ts.mu.Lock()\n\ts.books[b.ID] = b\n\ts.mu.Unlock()\n\tw.WriteHeader(http.StatusCreated)\n}<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Step 2: Test a GET Request with the Recorder<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Next, we test the happy path. We build a request, call the routes, and then decode the JSON body.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func TestGetBook(t *testing.T) {\n\th := NewStore().Routes()\n\n\treq := httptest.NewRequest(http.MethodGet, \"\/books\/1\", nil)\n\trec := httptest.NewRecorder()\n\th.ServeHTTP(rec, req)\n\n\tif rec.Code != http.StatusOK {\n\t\tt.Fatalf(\"status = %d, want %d\", rec.Code, http.StatusOK)\n\t}\n\tvar got Book\n\tif err := json.NewDecoder(rec.Body).Decode(&amp;got); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif got.Title != \"Go in Action\" {\n\t\tt.Errorf(\"title = %q, want %q\", got.Title, \"Go in Action\")\n\t}\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Here, <code>t.Fatalf<\/code> stops the test at once, because checking the body makes no sense after a wrong status. In contrast, <code>t.Errorf<\/code> records a failure and keeps going.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 3: Combine Go httptest with a Table<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func TestCreateBookValidation(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tbody string\n\t\twant int\n\t}{\n\t\t{\"valid book\", `{\"id\":\"2\",\"title\":\"Learning Go\"}`, http.StatusCreated},\n\t\t{\"missing title\", `{\"id\":\"3\"}`, http.StatusBadRequest},\n\t\t{\"bad json\", `{oops`, http.StatusBadRequest},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\th := NewStore().Routes()\n\t\t\treq := httptest.NewRequest(http.MethodPost, \"\/books\", strings.NewReader(tt.body))\n\t\t\trec := httptest.NewRecorder()\n\t\t\th.ServeHTTP(rec, req)\n\t\t\tif rec.Code != tt.want {\n\t\t\t\tt.Errorf(\"status = %d, want %d\", rec.Code, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Notice that each subtest creates a fresh store. As a result, one case can never change the data of another.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 4: A Full Server Test<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Finally, we start a real test server and use the normal HTTP client against it.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func TestFullServer(t *testing.T) {\n\tsrv := httptest.NewServer(NewStore().Routes())\n\tdefer srv.Close()\n\n\tresp, err := http.Get(srv.URL + \"\/books\/99\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer resp.Body.Close()\n\tbody, _ := io.ReadAll(resp.Body)\n\tif resp.StatusCode != http.StatusNotFound {\n\t\tt.Errorf(\"status = %d, want 404\", resp.StatusCode)\n\t}\n\tt.Logf(\"body: %s\", strings.TrimSpace(string(body)))\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>srv.URL<\/code> value holds an address such as <code>http:\/\/127.0.0.1:41233<\/code>. Also, <code>defer srv.Close()<\/code> shuts the server down when the test ends. Now run <code>go test -v<\/code> and look at the real output.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>=== RUN   TestGetBook\n--- PASS: TestGetBook (0.00s)\n=== RUN   TestCreateBookValidation\n=== RUN   TestCreateBookValidation\/valid_book\n=== RUN   TestCreateBookValidation\/missing_title\n=== RUN   TestCreateBookValidation\/bad_json\n--- PASS: TestCreateBookValidation (0.00s)\n    --- PASS: TestCreateBookValidation\/valid_book (0.00s)\n    --- PASS: TestCreateBookValidation\/missing_title (0.00s)\n    --- PASS: TestCreateBookValidation\/bad_json (0.00s)\n=== RUN   TestFullServer\n    books_test.go:67: body: book not found\n--- PASS: TestFullServer (0.00s)\nPASS<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step 5: Test Middleware with Go httptest<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func requireKey(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tif r.Header.Get(\"X-API-Key\") != \"secret\" {\n\t\t\thttp.Error(w, \"unauthorized\", http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(w, r)\n\t})\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>func TestRequireKey(t *testing.T) {\n\tok := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(http.StatusNoContent)\n\t})\n\th := requireKey(ok)\n\n\ttests := []struct {\n\t\tname string\n\t\tkey  string\n\t\twant int\n\t}{\n\t\t{\"no key\", \"\", http.StatusUnauthorized},\n\t\t{\"wrong key\", \"nope\", http.StatusUnauthorized},\n\t\t{\"right key\", \"secret\", http.StatusNoContent},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\treq := httptest.NewRequest(http.MethodGet, \"\/\", nil)\n\t\t\tif tt.key != \"\" {\n\t\t\t\treq.Header.Set(\"X-API-Key\", tt.key)\n\t\t\t}\n\t\t\trec := httptest.NewRecorder()\n\t\t\th.ServeHTTP(rec, req)\n\t\t\tif rec.Code != tt.want {\n\t\t\t\tt.Errorf(\"status = %d, want %d\", rec.Code, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Running <code>go test -v -run RequireKey<\/code> prints three passing subtests: <code>no_key<\/code>, <code>wrong_key<\/code> and <code>right_key<\/code>. This idea works for logging, rate limiting and token checks too. For example, you can reuse it for the JWT middleware from earlier lessons.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Common Mistakes with Go httptest<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Calling the handler instead of the mux<\/strong>: path values stay empty, so the test gives wrong results. Therefore, always call <code>Routes()<\/code>.<\/li>\n\n\n\n<li><strong>Sharing one store across subtests<\/strong>: cases then affect each other. Instead, create fresh data in each subtest.<\/li>\n\n\n\n<li><strong>Forgetting to close the server<\/strong>: the port stays open until the test binary exits. So use <code>defer srv.Close()<\/code>.<\/li>\n\n\n\n<li><strong>Checking only the status code<\/strong>: a 200 with the wrong JSON is still a bug. Also check the body and headers.<\/li>\n\n\n\n<li><strong>Reading the body twice<\/strong>: a recorder body is a buffer, and a second read may give nothing. So read it once and keep the value.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Best Practices for Go httptest<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Prefer the recorder for handlers<\/strong>, because it is the fastest option.<\/li>\n\n\n\n<li><strong>Test errors as much as success<\/strong>, since users hit error paths often.<\/li>\n\n\n\n<li><strong>Use small helper functions<\/strong> for building requests, because they cut repeated lines.<\/li>\n\n\n\n<li>**Set the <code>Content-Type<\/code> header** in requests that send JSON, so you match real clients.<\/li>\n\n\n\n<li>**Run with <code>go test -race<\/code>**, since handlers often run in many goroutines.<\/li>\n\n\n\n<li><strong>Use interfaces for databases<\/strong>, so tests can pass a fake store instead of a real one.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Practice Task<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">To practise Go httptest, add a <code>DELETE \/books\/{id}<\/code> 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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Hint: use <code>delete(s.books, id)<\/code> inside a write lock. After that, send a GET request in the same test and check that it now returns 404.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Official Resources<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">These pages describe the package and the handler types used in this lesson.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><a href=\"https:\/\/pkg.go.dev\/net\/http\/httptest\">net\/http\/httptest package documentation<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/pkg.go.dev\/net\/http\">net\/http package documentation<\/a><\/li>\n\n\n\n<li><a href=\"https:\/\/go.dev\/blog\/routing-enhancements\">Routing enhancements for Go 1.22<\/a><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Quick Recap<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Go httptest tests HTTP code without a real network.<\/li>\n\n\n\n<li><code>NewRequest<\/code> builds a fake request, and <code>NewRecorder<\/code> captures the response.<\/li>\n\n\n\n<li>Call the mux, not a single handler, when the route uses path values.<\/li>\n\n\n\n<li>Use <code>NewServer<\/code> when you test a client or a full flow.<\/li>\n\n\n\n<li>Combine Go httptest with table-driven tests for many status codes.<\/li>\n\n\n\n<li>Create fresh data in each subtest and close any test server.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next?<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Next up: <a href=\"https:\/\/smitabharat.com\/blog\/go-race-detector-data-races\/\">Go race detector and data races<\/a><\/p>\n\n","protected":false},"excerpt":{"rendered":"<p>Go httptest is a standard library package that lets you test HTTP handlers without opening a real port. In this post, you will learn&hellip;<\/p>\n","protected":false},"author":1,"featured_media":402,"comment_status":"","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_swapz_level":"","_swapz_series_part":0,"_swapz_hide_toc":false,"_swapz_hide_featured":false,"_swapz_description":"","footnotes":""},"categories":[15],"tags":[44,11,78,77],"swapz_series":[],"class_list":["post-428","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-go-lang","tag-go-http-server","tag-go-lang","tag-go-testing","tag-intermediate"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.9 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Go httptest: Test HTTP Handlers Step by Step<\/title>\n<meta name=\"description\" content=\"Learn Go httptest step by step: fake requests, record responses, test routes and JSON, and combine it with table-driven tests.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Go httptest: Test HTTP Handlers Step by Step\" \/>\n<meta property=\"og:description\" content=\"Learn Go httptest step by step: fake requests, record responses, test routes and JSON, and combine it with table-driven tests.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/\" \/>\n<meta property=\"og:site_name\" content=\"Smita Bharat - Blog\" \/>\n<meta property=\"article:published_time\" content=\"2026-05-21T03:30:00+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-featured.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2400\" \/>\n\t<meta property=\"og:image:height\" content=\"1260\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Smita\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Smita\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"10 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-httptest-handlers\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-httptest-handlers\\\/\"},\"author\":{\"name\":\"Smita\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"headline\":\"Go httptest: Test HTTP Handlers Step by Step\",\"datePublished\":\"2026-05-21T03:30:00+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-httptest-handlers\\\/\"},\"wordCount\":1454,\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-httptest-handlers\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-httptest-handlers-featured.png\",\"keywords\":[\"Go HTTP Server\",\"Go Lang\",\"Go Testing\",\"Intermediate\"],\"articleSection\":[\"Go Lang\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-httptest-handlers\\\/\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-httptest-handlers\\\/\",\"name\":\"Go httptest: Test HTTP Handlers Step by Step\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-httptest-handlers\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-httptest-handlers\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-httptest-handlers-featured.png\",\"datePublished\":\"2026-05-21T03:30:00+00:00\",\"description\":\"Learn Go httptest step by step: fake requests, record responses, test routes and JSON, and combine it with table-driven tests.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-httptest-handlers\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-httptest-handlers\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-httptest-handlers\\\/#primaryimage\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-httptest-handlers-featured.png\",\"contentUrl\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/wp-content\\\/uploads\\\/2026\\\/10\\\/go-httptest-handlers-featured.png\",\"width\":2400,\"height\":1260,\"caption\":\"Go httptest featured image: fake request, recorder and test server cards\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/go-httptest-handlers\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Go httptest: Test HTTP Handlers Step by Step\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#website\",\"url\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/\",\"name\":\"Smita Bharat Blog\",\"description\":\"Golang &amp; Backend Development Tutorials and Interview Questions\",\"publisher\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\"},\"alternateName\":\"Smita Bharat\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/27a1b1067d396703215c54acedbfd339\",\"name\":\"Smita\",\"logo\":{\"@id\":\"https:\\\/\\\/smitabharat.com\\\/blog\\\/#\\\/schema\\\/person\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/smitabharat.com\\\/blog\"]}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Go httptest: Test HTTP Handlers Step by Step","description":"Learn Go httptest step by step: fake requests, record responses, test routes and JSON, and combine it with table-driven tests.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/","og_locale":"en_US","og_type":"article","og_title":"Go httptest: Test HTTP Handlers Step by Step","og_description":"Learn Go httptest step by step: fake requests, record responses, test routes and JSON, and combine it with table-driven tests.","og_url":"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/","og_site_name":"Smita Bharat - Blog","article_published_time":"2026-05-21T03:30:00+00:00","og_image":[{"width":2400,"height":1260,"url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-featured.png","type":"image\/png"}],"author":"Smita","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Smita","Est. reading time":"10 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/#article","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/"},"author":{"name":"Smita","@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"headline":"Go httptest: Test HTTP Handlers Step by Step","datePublished":"2026-05-21T03:30:00+00:00","mainEntityOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/"},"wordCount":1454,"publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-featured.png","keywords":["Go HTTP Server","Go Lang","Go Testing","Intermediate"],"articleSection":["Go Lang"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/","url":"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/","name":"Go httptest: Test HTTP Handlers Step by Step","isPartOf":{"@id":"https:\/\/smitabharat.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/#primaryimage"},"image":{"@id":"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/#primaryimage"},"thumbnailUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-featured.png","datePublished":"2026-05-21T03:30:00+00:00","description":"Learn Go httptest step by step: fake requests, record responses, test routes and JSON, and combine it with table-driven tests.","breadcrumb":{"@id":"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/#primaryimage","url":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-featured.png","contentUrl":"https:\/\/smitabharat.com\/blog\/wp-content\/uploads\/2026\/10\/go-httptest-handlers-featured.png","width":2400,"height":1260,"caption":"Go httptest featured image: fake request, recorder and test server cards"},{"@type":"BreadcrumbList","@id":"https:\/\/smitabharat.com\/blog\/go-httptest-handlers\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/smitabharat.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Go httptest: Test HTTP Handlers Step by Step"}]},{"@type":"WebSite","@id":"https:\/\/smitabharat.com\/blog\/#website","url":"https:\/\/smitabharat.com\/blog\/","name":"Smita Bharat Blog","description":"Golang &amp; Backend Development Tutorials and Interview Questions","publisher":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339"},"alternateName":"Smita Bharat","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/smitabharat.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/27a1b1067d396703215c54acedbfd339","name":"Smita","logo":{"@id":"https:\/\/smitabharat.com\/blog\/#\/schema\/person\/image\/"},"sameAs":["https:\/\/smitabharat.com\/blog"]}]}},"_links":{"self":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/428","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/comments?post=428"}],"version-history":[{"count":0,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/posts\/428\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media\/402"}],"wp:attachment":[{"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/media?parent=428"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/categories?post=428"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/tags?post=428"},{"taxonomy":"swapz_series","embeddable":true,"href":"https:\/\/smitabharat.com\/blog\/wp-json\/wp\/v2\/swapz_series?post=428"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}