Gin in the wider system · 5 MIN READ

Keep the OpenAPI document and the Gin router honest: diff routes, operations and status codes in a test

Write a test that converts engine.Routes() to OpenAPI path templates, reports routes and operations that exist on only one side, and checks recorded status codes against declared responses.

An OpenAPI document is a promise that clients, generated SDKs and gateway configurations build on, while the router is what actually answers. Nothing connects the two unless you write the check: a handler added on Friday never reaches the document, an operation deleted from code lingers in the SDK, and a handler that starts returning 422 contradicts a spec that says 400. A small test that reads both sides and prints sorted differences keeps them together.

gin · A MAP OF THE IDEA

  1. Parse spec operations
  2. Convert route templates
  3. Record observed codes
  4. Report sorted findings

Useful when

  • Undocumented routes and dead operations fail CI the day they appear.
  • Status checks reuse the API test table instead of new fixtures.

Watch out

  • Catch-all routes have no faithful OpenAPI template.
  • Only exercised status codes are compared; 4XX and default accept anything in range.

Implementation & operation cost: About a hundred lines of test helpers and one recording middleware; it checks paths, methods and codes, not body schemas, which need a separate validator.

01

How a document and a router drift apart

Drift comes in three shapes, and each hurts a different reader. A route missing from the document is invisible to client generators and API gateways that validate requests against the spec, so the new endpoint works in curl and fails behind the gateway. An operation in the document without a route ships as a method in every generated SDK that returns 404 at runtime. A status code the handler sends but the document does not declare breaks clients that switch on declared responses, and generated clients often treat an undeclared code as a decoding error. None of these fail a build by themselves. It does not matter whether the document is written by hand or generated from annotations: annotations drift from handler code in exactly the same ways, because they are comments that nothing executes. The cure is a test that reads both sides.

02

Diff the route table against the document

The program parses a small OpenAPI 3.1 document, builds a router that disagrees with it in three ways, sends the calls an API test table would send, and prints each finding in sorted order. The document is a string constant only so the example fits in one file; the last section embeds the real file.

go
package main

import (
	"encoding/json"
	"fmt"
	"maps"
	"net/http"
	"net/http/httptest"
	"slices"
	"strconv"
	"strings"
	"sync"

	"github.com/gin-gonic/gin"
)

// In the service this is //go:embed openapi.json; a constant keeps the example in one file.
const openAPI = `{
  "openapi": "3.1.0",
  "info": {"title": "notes", "version": "2.3.0"},
  "paths": {
    "/v2/notes": {
      "get": {"responses": {"200": {"description": "a page of notes"}}},
      "post": {"responses": {"201": {"description": "created"}, "400": {"description": "invalid note"}}}
    },
    "/v2/notes/{id}": {
      "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}],
      "get": {"responses": {"200": {"description": "the note"}, "4XX": {"description": "client error"}}},
      "delete": {"responses": {"204": {"description": "deleted"}}}
    },
    "/v2/files/{path}": {
      "get": {"responses": {"200": {"description": "file bytes"}}}
    }
  }
}`

var httpMethods = []string{"get", "put", "post", "delete", "options", "head", "patch", "trace"}

// operations maps "METHOD /template" to the declared response codes.
func operations(doc []byte) (map[string][]string, error) {
	var spec struct {
		Paths map[string]map[string]json.RawMessage `json:"paths"`
	}
	if err := json.Unmarshal(doc, &spec); err != nil {
		return nil, err
	}
	ops := map[string][]string{}
	for path, item := range spec.Paths {
		for _, m := range httpMethods {
			raw, ok := item[m]
			if !ok {
				continue
			}
			var op struct {
				Responses map[string]json.RawMessage `json:"responses"`
			}
			if err := json.Unmarshal(raw, &op); err != nil {
				return nil, fmt.Errorf("%s %s: %w", m, path, err)
			}
			ops[strings.ToUpper(m)+" "+path] = slices.Sorted(maps.Keys(op.Responses))
		}
	}
	return ops, nil
}

// template converts Gin's /notes/:id and /files/*path to /notes/{id} and /files/{path}.
func template(ginPath string) (string, bool) {
	parts := strings.Split(ginPath, "/")
	catchAll := false
	for i, p := range parts {
		switch {
		case strings.HasPrefix(p, ":"):
			parts[i] = "{" + p[1:] + "}"
		case strings.HasPrefix(p, "*"):
			parts[i] = "{" + p[1:] + "}"
			catchAll = true
		}
	}
	return strings.Join(parts, "/"), catchAll
}

func declared(codes []string, status int) bool {
	s := strconv.Itoa(status)
	return slices.Contains(codes, s) || slices.Contains(codes, s[:1]+"XX") || slices.Contains(codes, "default")
}

// observed records which status each route template actually answered with.
type observed struct {
	mu   sync.Mutex
	seen map[string]map[int]bool
}

func (o *observed) middleware(c *gin.Context) {
	c.Next()
	if c.FullPath() == "" {
		return // unmatched requests are not operations
	}
	t, _ := template(c.FullPath())
	key := c.Request.Method + " " + t
	o.mu.Lock()
	defer o.mu.Unlock()
	if o.seen[key] == nil {
		o.seen[key] = map[int]bool{}
	}
	o.seen[key][c.Writer.Status()] = true
}

func drift(routes gin.RoutesInfo, ops map[string][]string, seen map[string]map[int]bool, internal map[string]bool) []string {
	var out []string
	routed := map[string]bool{}
	for _, r := range routes {
		t, catchAll := template(r.Path)
		key := r.Method + " " + t
		routed[key] = true
		if internal[r.Method+" "+r.Path] {
			continue
		}
		if _, ok := ops[key]; !ok {
			out = append(out, "route missing from spec: "+key)
		}
		if catchAll {
			out = append(out, "warning: "+key+" is a Gin catch-all; OpenAPI {param} matches one segment")
		}
	}
	for key, codes := range ops {
		if !routed[key] {
			out = append(out, "spec operation without route: "+key)
		}
		for status := range seen[key] {
			if !declared(codes, status) {
				out = append(out, fmt.Sprintf("undeclared status: %s answered %d, spec declares %s", key, status, strings.Join(codes, " ")))
			}
		}
	}
	slices.Sort(out)
	return out
}

func newRouter(obs *observed) *gin.Engine {
	r := gin.New()
	r.Use(obs.middleware)
	r.GET("/healthz", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
	v2 := r.Group("/v2")
	v2.GET("/notes", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"items": []string{}}) })
	v2.POST("/notes", func(c *gin.Context) {
		var in struct {
			Title string `json:"title" binding:"required"`
		}
		if err := c.ShouldBindJSON(&in); err != nil {
			c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "title is required"})
			return
		}
		c.JSON(http.StatusCreated, gin.H{"id": "8", "title": in.Title})
	})
	v2.GET("/notes/:id", func(c *gin.Context) {
		if c.Param("id") != "7" {
			c.JSON(http.StatusNotFound, gin.H{"error": "note not found"})
			return
		}
		c.JSON(http.StatusOK, gin.H{"id": "7"})
	})
	v2.PATCH("/notes/:id", func(c *gin.Context) { c.Status(http.StatusNoContent) })
	v2.GET("/files/*path", func(c *gin.Context) { c.String(http.StatusOK, "file %s", c.Param("path")) })
	return r
}

func main() {
	gin.SetMode(gin.TestMode)
	ops, err := operations([]byte(openAPI))
	if err != nil {
		panic(err)
	}
	obs := &observed{seen: map[string]map[int]bool{}}
	r := newRouter(obs)
	calls := []struct{ method, path, body string }{
		{"GET", "/v2/notes", ""},
		{"POST", "/v2/notes", `{"title":"retro"}`},
		{"POST", "/v2/notes", `{}`},
		{"GET", "/v2/notes/7", ""},
		{"GET", "/v2/notes/99", ""},
		{"GET", "/v2/files/a/b.txt", ""},
		{"GET", "/v2/typo", ""},
	}
	for _, tc := range calls {
		req := httptest.NewRequest(tc.method, tc.path, strings.NewReader(tc.body))
		req.Header.Set("Content-Type", "application/json")
		w := httptest.NewRecorder()
		r.ServeHTTP(w, req)
		fmt.Println(tc.method, tc.path, w.Code)
	}
	problems := drift(r.Routes(), ops, obs.seen, map[string]bool{"GET /healthz": true})
	for _, p := range problems {
		fmt.Println(p)
	}
	fmt.Printf("%d operations in spec, %d findings\n", len(ops), len(problems))
}
Read the code

operations decodes paths into raw path items and reads only the eight HTTP method keys, because a path item can also hold keys such as parameters and summary. template rewrites each Gin segment: :id becomes {id}, *path becomes {path}, and the catch-all is reported. The observed middleware runs after c.Next, keys each response by method and converted c.FullPath(), and skips requests whose FullPath is empty because they matched no route. drift walks the routes against the operations, then each operation's observed statuses against its declared codes, accepting an exact code, a range such as 4XX or default. Map iteration order never reaches stdout, because only the sorted findings are printed.

03

Translate Gin paths into OpenAPI templates

A Gin :param matches one path segment, which is exactly what an OpenAPI {param} means, so the conversion is mechanical, but the names must match: a document that says /notes/{noteId} for the route /notes/:id produces two findings, and that is correct, because generated clients use the parameter name. A catch-all is different. Gin's *path matches several segments and c.Param returns them with a leading slash, while an OpenAPI path parameter value cannot contain an unescaped slash, so no template describes the route faithfully. Either redesign it, for example as a query parameter, or keep it as a reviewed warning, as the program does. Watch the edges as well: OpenAPI method keys are lowercase, a servers URL such as /api is a prefix the router may or may not include, and the redirects and 405 answers Gin generates are not operations. Gin registers no implicit HEAD or OPTIONS routes, so engine.Routes() holds exactly what your code registered and nothing more.

04

Declared codes against observed codes

Matching routes compares structure; status codes need behavior. The recording middleware observes what the handlers really send, and the natural source of calls is the table the API-tests lesson already runs through the real router, so each success and error case contributes its status for free. The check can only judge codes the table exercises: a 409 that no case triggers is never compared, which is one more reason to give every error kind a row. Use ranges such as 4XX and the default response deliberately, because each one accepts codes nobody reviewed. Requests that match no route have an empty FullPath and Gin's NoRoute answers them, so they are skipped rather than reported against an operation. Checking response bodies against the declared schemas is the next step and needs a JSON Schema validator; the problem-details lesson fixes the error body shape, which keeps that check small.

05

Run it as a test against the embedded document

In the service, embed the document so the binary and the test read the same bytes, and serve those bytes at /openapi.json if clients fetch the spec at runtime. Keep the allow-list of undocumented internal routes in the test file, where every exemption is visible in review. Because the findings are sorted, a CI failure is a stable list that diffs cleanly between runs instead of a different order every time.

go
// spec.go
package httpapi

import _ "embed"

//go:embed openapi.json
var openAPIDoc []byte

// contract_test.go
func TestContractDrift(t *testing.T) {
	gin.SetMode(gin.TestMode)
	ops, err := operations(openAPIDoc)
	if err != nil {
		t.Fatal(err)
	}
	obs := &observed{seen: map[string]map[int]bool{}}
	r := newRouter(obs)
	for _, tc := range apiCases { // the table the API tests already use
		r.ServeHTTP(httptest.NewRecorder(), tc.request())
	}
	internal := map[string]bool{"GET /healthz": true, "GET /openapi.json": true}
	for _, finding := range drift(r.Routes(), ops, obs.seen, internal) {
		t.Error(finding)
	}
}
Read the code

This fragment spans two files of the package. spec.go embeds openapi.json into the binary; go:embed patterns are relative to the package directory and cannot contain .., so the document lives beside the package or in a small package of its own that exports the bytes. The test replays the shared case table through a router built with the recording middleware, then reports one error per finding. internal is the reviewed allow-list, including the route that serves the document itself.

TAKE THIS WITH YOU

Treat the OpenAPI document as test input: convert engine.Routes() to templates, fail on routes or operations present on one side only, compare observed status codes with declared responses, and print findings sorted.

Check your understanding

A drift test records the status of each test call and compares it with the OpenAPI responses. Why key the records by c.FullPath() instead of c.Request.URL.Path?

Go to the source

Progress stays in this browser. No account needed.