HTTP Mock Server For Tests

Spin up an in-process stub server with canned JSON responses, track request counts atomically, and exercise not-found paths.

GoCli Tooling

Code

gosnippet
53 lines
package main

import (
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"sync/atomic"
)

type StubResponse struct {
	Status int
	Body   string
}

func NewStubServer(responses map[string]StubResponse, hits *int64) *httptest.Server {
	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if hits != nil {
			atomic.AddInt64(hits, 1)
		}
		response, ok := responses[r.URL.Path]
		if !ok {
			http.NotFound(w, r)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(response.Status)
		_, _ = io.WriteString(w, response.Body)
	}))
}

func main() {
	var hits int64
	server := NewStubServer(map[string]StubResponse{
		"/users/1": {Status: http.StatusOK, Body: `{"id":1,"name":"ada"}`},
		"/health":  {Status: http.StatusOK, Body: `{"status":"ok"}`},
	}, &hits)
	defer server.Close()

	for _, requestPath := range []string{"/users/1", "/health", "/missing"} {
		response, err := http.Get(server.URL + requestPath)
		if err != nil {
			panic(err)
		}
		body, err := io.ReadAll(response.Body)
		response.Body.Close()
		if err != nil {
			panic(err)
		}
		fmt.Printf("%s -> %d %s\n", requestPath, response.StatusCode, string(body))
	}
	fmt.Println("total requests:", atomic.LoadInt64(&hits))
}

What the code does

Count the functions NewStubServer and main as the entire surface area of HTTP Mock Server For Tests.

for _, requestPath := range []string{"/users/1", "/health", "/missing"} is the loop that carries the per-item work. Every err != nil branch (2 sites) calls panic(err) — the run stops at the first failure instead of continuing in a broken state. defer schedules the cleanup, and the scheduled call fires no matter how the function exits.

Points of care

  • Failures abort via panic(err) — nothing is returned for the caller to check, and nothing in the snippet recovers.

Applying it

Entry signature: func NewStubServer(responses map[string]StubResponse, hits *int64) *httptest.Server

Running the file prints labeled results such as total requests: — each operation’s effect is visible in the output.

The demo flow inside main is NewStubServer — run the file to see it end to end.

Statements that matter

if err != nil {
panic(err)
}
defer server.Close()

Interactive Tools for This Topic

FAQ

Does the snippet panic on failure?
It stops. All 2 `if err != nil` branches ends in `panic(err)` — nothing continues past a failed call.
What does HTTP Mock Server For Tests print when run?
Running the file directly is enough — expect labeled output lines such as `total requests:`.