Gin project: a complete REST API · 5 MIN READ
Table-driven API tests through the real router: status, headers and JSON compared by meaning
Write table-driven tests that send requests through the real Gin router with fakes and assert status, contract headers and semantically compared JSON bodies.
Tests that call a handler function directly miss the bugs that live between handlers: middleware order, error mapping, headers and the exact JSON a client parses. Sending requests through the router production uses, with a fake store behind it, tests the API contract in milliseconds. A table turns the next case into a few lines, and asserting whole bodies is what catches the regression that a status check waves through.
gin · A MAP OF THE IDEA
- Build router with fakes
- Send table row requests
- Assert status and headers
- Compare decoded bodies
Useful when
- Tests the real middleware chain and error mapping in milliseconds.
- Whole-body comparison catches leaks and accidental fields.
- New cases are one table row, so regressions get reproduced cheaply.
Watch out
- float64 decoding loses precision for integers above 2^53.
- Fakes do not prove the real store works; keep separate integration tests.
Implementation & operation cost: A fake per dependency, a test helper and the discipline to inject time and IDs everywhere.
Test the router, fake only the edges
In these tests everything a request touches in production is real except the outermost dependencies. The engine, the problems middleware, the handlers and the notes service are the production code, built through the same constructors main uses. The store, the clock and the ID source are fakes injected as the dependencies lesson showed, which makes every body deterministic. Each case builds its own fake and router, so cases share nothing and can run in parallel. Assert three things per response: the status, every header that is part of the contract such as Location, Content-Type, ETag or Retry-After, and the entire body as a JSON value. A storage adapter gets its own integration tests against a real database; mixing the two makes API tests slow and flaky.
handler_test.go: the table and the assertions
The test file lives next to the handlers but uses the external package httpapi_test, so it can only call what main can call: NewRouter, NewHandler and the notes constructors. That keeps the tests honest about the public wiring. TestMain sets Gin's mode once, because SetMode writes a process-wide variable and parallel subtests must not race on it.
package httpapi_test
import (
"encoding/json"
"errors"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"reflect"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"example.com/notes-api/internal/httpapi"
"example.com/notes-api/internal/notes"
)
func TestMain(m *testing.M) {
gin.SetMode(gin.TestMode) // process-wide: set once, before any test builds an engine
os.Exit(m.Run())
}
func TestNotesAPI(t *testing.T) {
tests := []struct {
name string
method string
path string
body string
storeErr error
wantStatus int
wantHeader map[string]string
wantBody string
}{
{
name: "create returns 201 and Location", method: "POST", path: "/notes", body: `{"title":" Review PR "}`,
wantStatus: 201,
wantHeader: map[string]string{"Location": "/notes/n1", "Content-Type": "application/json; charset=utf-8"},
wantBody: `{"title": "Review PR", "id": "n1", "createdAt": "2026-01-02T03:04:05Z"}`,
},
{
name: "missing note is a problem document", method: "GET", path: "/notes/n9",
wantStatus: 404,
wantHeader: map[string]string{"Content-Type": "application/problem+json"},
wantBody: `{"type": "https://example.com/problems/not-found", "title": "Note not found", "status": 404, "instance": "/notes/n9"}`,
},
{
name: "blank title is rejected with a reason", method: "POST", path: "/notes", body: `{"title":" "}`,
wantStatus: 422,
wantHeader: map[string]string{"Content-Type": "application/problem+json"},
wantBody: `{"type": "https://example.com/problems/validation", "title": "Invalid note", "status": 422, "detail": "title must not be blank", "instance": "/notes"}`,
},
{
name: "store failure hides the cause", method: "GET", path: "/notes/n1",
storeErr: errors.New("dial tcp 192.0.2.10:5432: connection refused"),
wantStatus: 500,
wantHeader: map[string]string{"Content-Type": "application/problem+json"},
wantBody: `{"type": "about:blank", "title": "Internal Server Error", "status": 500, "instance": "/notes/n1"}`,
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
r := newTestRouter(t, tc.storeErr)
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
if tc.body != "" {
req.Header.Set("Content-Type", "application/json")
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != tc.wantStatus {
t.Errorf("status = %d, want %d", w.Code, tc.wantStatus)
}
for k, want := range tc.wantHeader {
if got := w.Header().Get(k); got != want {
t.Errorf("header %s = %q, want %q", k, got, want)
}
}
assertJSONEqual(t, tc.wantBody, w.Body.Bytes())
})
}
}
func newTestRouter(t *testing.T, storeErr error) http.Handler {
t.Helper()
fake := newFakeStore()
fake.err = storeErr
seq := 0
ids := func() string { seq++; return fmt.Sprintf("n%d", seq) }
clock := func() time.Time { return time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) }
svc, err := notes.NewService(fake, clock, ids)
if err != nil {
t.Fatal(err)
}
r, err := httpapi.NewRouter(httpapi.NewHandler(svc, slog.New(slog.DiscardHandler)), httpapi.Options{})
if err != nil {
t.Fatal(err)
}
return r
}
func assertJSONEqual(t *testing.T, want string, got []byte) {
t.Helper()
var w, g any
if err := json.Unmarshal([]byte(want), &w); err != nil {
t.Fatalf("test table has invalid JSON: %v", err)
}
if err := json.Unmarshal(got, &g); err != nil {
t.Fatalf("response is not JSON: %v\n%s", err, got)
}
if !reflect.DeepEqual(w, g) {
t.Errorf("body mismatch\n got: %s\nwant: %s", got, want)
}
}This fragment belongs in internal/httpapi of the module from the layout lesson and runs there with go test -race ./internal/httpapi. Each table row names the request and the expected contract. t.Run gives every case its own name in the output, and t.Parallel is safe because the router and fake are per case; since Go 1.22 the loop variable tc is a fresh variable on each iteration, so the closure needs no copy. newTestRouter uses t.Helper and t.Fatal for wiring errors. assertJSONEqual decodes both sides into any and compares them with reflect.DeepEqual, reporting the full actual body on mismatch. fakeStore, with a mutex and an err field, lives in fake_test.go in the same package.
The same table, runnable, against a regression
The runnable model condenses the notes and httpapi packages into one file and runs the same four cases three times: against the current build, against a regressed build with status-only checks, and against the regressed build with full checks. The regression is a plausible "debugging aid": the problems middleware copies err.Error() into detail for unexpected errors.
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"net/http/httptest"
"reflect"
"slices"
"strings"
"time"
"github.com/gin-gonic/gin"
)
// ---- condensed code under test: notes + httpapi from earlier lessons ----
type Note struct {
ID string `json:"id"`
Title string `json:"title"`
CreatedAt time.Time `json:"createdAt"`
}
var (
ErrNotFound = errors.New("notes: not found")
ErrInvalid = errors.New("notes: title must not be blank")
)
type Store interface {
Insert(ctx context.Context, n Note) error
Get(ctx context.Context, id string) (Note, error)
}
type Handler struct {
store Store
now func() time.Time
nextID func() string
}
type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
}
func problems(exposeCause bool) gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
if len(c.Errors) == 0 || c.Writer.Written() {
return
}
err := c.Errors.Last().Err
p := Problem{Type: "about:blank", Title: "Internal Server Error", Status: 500}
switch {
case errors.Is(err, ErrNotFound):
p = Problem{Type: "https://example.com/problems/not-found", Title: "Note not found", Status: 404}
case errors.Is(err, ErrInvalid):
p = Problem{Type: "https://example.com/problems/validation", Title: "Invalid note", Status: 422,
Detail: "title must not be blank"}
case exposeCause:
p.Detail = err.Error() // the "helpful" regression
}
p.Instance = c.Request.URL.Path
c.Header("Content-Type", "application/problem+json")
c.JSON(p.Status, p)
}
}
func NewRouter(h *Handler, exposeCause bool) *gin.Engine {
r := gin.New()
r.Use(problems(exposeCause))
r.POST("/notes", func(c *gin.Context) {
var in struct {
Title string `json:"title"`
}
if err := c.ShouldBindJSON(&in); err != nil || strings.TrimSpace(in.Title) == "" {
_ = c.Error(ErrInvalid)
return
}
n := Note{ID: h.nextID(), Title: strings.TrimSpace(in.Title), CreatedAt: h.now()}
if err := h.store.Insert(c.Request.Context(), n); err != nil {
_ = c.Error(fmt.Errorf("insert %s: %w", n.ID, err))
return
}
c.Header("Location", "/notes/"+n.ID)
c.JSON(http.StatusCreated, n)
})
r.GET("/notes/:id", func(c *gin.Context) {
n, err := h.store.Get(c.Request.Context(), c.Param("id"))
if err != nil {
_ = c.Error(fmt.Errorf("get %s: %w", c.Param("id"), err))
return
}
c.JSON(http.StatusOK, n)
})
return r
}
// ---- test support: a fake store and a semantic JSON comparison ----
type fakeStore struct {
notes map[string]Note
err error
}
func (f *fakeStore) Insert(_ context.Context, n Note) error {
if f.err != nil {
return f.err
}
f.notes[n.ID] = n
return nil
}
func (f *fakeStore) Get(_ context.Context, id string) (Note, error) {
if f.err != nil {
return Note{}, f.err
}
n, ok := f.notes[id]
if !ok {
return Note{}, ErrNotFound
}
return n, nil
}
func jsonEqual(want string, got []byte) bool {
var w, g any
if json.Unmarshal([]byte(want), &w) != nil || json.Unmarshal(got, &g) != nil {
return false
}
return reflect.DeepEqual(w, g)
}
// ---- the table: the same one handler_test.go runs with t.Run ----
type apiCase struct {
name string
method string
path string
body string
storeErr error
wantStatus int
wantHeader map[string]string
wantBody string
}
var cases = []apiCase{
{
name: "create returns 201 and Location", method: "POST", path: "/notes", body: `{"title":" Review PR "}`,
wantStatus: 201,
wantHeader: map[string]string{"Location": "/notes/n1", "Content-Type": "application/json; charset=utf-8"},
wantBody: `{"title": "Review PR", "id": "n1", "createdAt": "2026-01-02T03:04:05Z"}`,
},
{
name: "missing note is a problem document", method: "GET", path: "/notes/n9",
wantStatus: 404,
wantHeader: map[string]string{"Content-Type": "application/problem+json"},
wantBody: `{"type": "https://example.com/problems/not-found", "title": "Note not found", "status": 404, "instance": "/notes/n9"}`,
},
{
name: "blank title is rejected with a reason", method: "POST", path: "/notes", body: `{"title":" "}`,
wantStatus: 422,
wantHeader: map[string]string{"Content-Type": "application/problem+json"},
wantBody: `{"type": "https://example.com/problems/validation", "title": "Invalid note", "status": 422, "detail": "title must not be blank", "instance": "/notes"}`,
},
{
name: "store failure hides the cause", method: "GET", path: "/notes/n1",
storeErr: errors.New("dial tcp 192.0.2.10:5432: connection refused"),
wantStatus: 500,
wantHeader: map[string]string{"Content-Type": "application/problem+json"},
wantBody: `{"type": "about:blank", "title": "Internal Server Error", "status": 500, "instance": "/notes/n1"}`,
},
}
func newRouterFor(tc apiCase, exposeCause bool) http.Handler {
seq := 0
h := &Handler{
store: &fakeStore{notes: map[string]Note{}, err: tc.storeErr},
now: func() time.Time { return time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC) },
nextID: func() string { seq++; return fmt.Sprintf("n%d", seq) },
}
return NewRouter(h, exposeCause)
}
func check(r http.Handler, tc apiCase, statusOnly bool) []string {
req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
if tc.body != "" {
req.Header.Set("Content-Type", "application/json")
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
var fails []string
if w.Code != tc.wantStatus {
fails = append(fails, fmt.Sprintf("status %d, want %d", w.Code, tc.wantStatus))
}
if statusOnly {
return fails
}
for _, k := range slices.Sorted(maps.Keys(tc.wantHeader)) {
if got := w.Header().Get(k); got != tc.wantHeader[k] {
fails = append(fails, fmt.Sprintf("%s %q, want %q", k, got, tc.wantHeader[k]))
}
}
if !jsonEqual(tc.wantBody, w.Body.Bytes()) {
fails = append(fails, "body "+w.Body.String())
}
return fails
}
func run(label string, exposeCause, statusOnly bool) {
fmt.Println(label)
for _, tc := range cases {
if fails := check(newRouterFor(tc, exposeCause), tc, statusOnly); len(fails) > 0 {
fmt.Printf(" FAIL %s: %s\n", tc.name, strings.Join(fails, "; "))
} else {
fmt.Printf(" PASS %s\n", tc.name)
}
}
}
func main() {
gin.SetMode(gin.TestMode)
run("current build, full checks:", false, false)
run("regressed build, status-only checks:", true, true)
run("regressed build, full checks:", true, false)
}check sends one request and collects failures instead of calling t.Errorf, so main can print a PASS or FAIL line per case. Header names are checked in sorted order to keep output stable. The current build passes everything; note that the expected create body lists keys in a different order and with spaces, and still matches. On the regressed build, status-only checks pass all four cases, because a leaking 500 is still a 500. Full checks fail the store-failure case and print the body that would have reached clients, with the database address in detail.
Compare JSON by meaning, and know the limits
Byte comparison breaks for reasons that are not part of the contract: key order in maps, field order after a struct refactor, whitespace, and HTML escaping, since encoding/json escapes <, > and & by default and Gin's c.PureJSON does not. Decoding both sides into any and comparing with reflect.DeepEqual compares values instead. It is still strict in the useful direction: an extra member, a missing member and a null where a string was expected all fail, which is exactly how the leaked detail was caught. Two caveats remain. Numbers decode to float64, so integers above 2^53 lose precision; decode with json.Decoder.UseNumber when IDs or amounts are large. And volatile fields should be made deterministic by injecting the clock and ID source rather than deleted before comparing, because deleted fields are untested fields.
What the table should cover
For each route, include the success path with its headers, every error kind the problems middleware maps and one failing store that must produce a bare 500. Add middleware-level rows: an unknown route, an oversized body, a missing Idempotency-Key, a missing or stale If-Match. Where a request has side effects, inspect the fake afterwards; a replayed idempotent POST must leave exactly one note. Run with -race and -count=1, and occasionally with -shuffle=on to surface hidden ordering between cases. When a bug escapes, its reproduction becomes a new row before the fix.
TAKE THIS WITH YOU
Drive tests through the production router with fakes for the store, clock and IDs, and assert status, contract headers and the whole JSON body compared semantically, so a leaked detail fails the build.
Check your understanding
Why does assertJSONEqual decode both the expected and the actual body into any before comparing them?
Go to the source
Progress stays in this browser. No account needed.