Documentation

Go router syntax (net/http ServeMux, chi, gin)

ADR 0076; task T023 (step GR1 captures the syntax; units GR2-GR6 recognise, compose and check it). Aggregate extractor version: extractors-49 (49 from T024, ADR 0077, outside the Go payload; 48 from T026, ADR 0079, outside the Go payload; 47 from T022, ADR 0075, outside the Go payload; 46 from T023 GR1: cached Go facts gained the router payload; Go payload version 9, facts.GoModelsVersion: version 4, from T023 GR3, keeps the two router filter forms GR2 found; version 5, from T023 GR4, gates and keeps the net/http serving syntax; version 6, from T023 GR5, adds the wrappers and request helpers and keeps x.Handler = v assignments; version 7, from T023 GR6, adds the generated-server record and gates and keeps the calls of a generated server's entry functions; version 8, from T023 GR7, adds the forwarding proof of a function literal (GoExpr.Forward); version 9, from T023 GR8, adds the escape records (Escapes, GoRouteCall.Context, GoExpr.Request, the Uses of captured literals) and the deciding statements of wrappers and forwarding closures (Methods, Guards) with the request reads of request helpers (URL, Method); none bumps the aggregate version, since extractors-46 is this unmerged branch's own). Contract version unchanged; the payload adds no graph record.

The Go extractor captures the syntax that Go route extraction reads: in files that can register routes (the route gate), the functions and function literals that mention router syntax, with their signatures, lexical blocks, the bindings of the names their calls use, the router-named calls and the calls that may pass a router on, and their returns; and, in every non-test file, each function's single named result type. The payload is syntax, never a claim (rule 31): which object is a router, which call registers a route, which path it serves and which handler it names are decided at link time through the module's own packages, under the claim contract of docs/contract/claims/go-http-routers.md.

Why a cached payload

On a cache hit the indexer replays stored facts and never parses the file, so the link pass has no tree. The Go facts cached before this payload keep one node per declaration, the calls with their callee name and the GORM payload of files that import GORM: no call arguments, no receiver chains, no function literals, no lexical blocks and no bindings outside GORM files.

Gate and filters (rule 31)

Most Go files import net/http, and every gin handler file imports gin for *gin.Context, so the payload is filtered at capture by the cheapest syntactic tests that keep every site the claim contract reads:

  1. File gate (task decision 10, rows RG-*): the file imports github.com/go-chi/chi/v5 (or an older chi path, which GR-K1 refuses at link time, counted) or github.com/gin-gonic/gin, or it imports net/http and mentions ServeMux, NewServeMux, DefaultServeMux, Handle or HandleFunc, or (since step GR4, the serving syntax of contract rows GR-C3 and GR-C6) StripPrefix, ListenAndServe, ListenAndServeTLS, Serve, ServeTLS or Server, as a selector or qualified type of its net/http name, or (since step GR6, row RG-generated) it calls a generated server's entry function (Handler, HandlerFromMux, HandlerFromMuxWithBaseURL, HandlerWithOptions, RegisterHandlers, RegisterHandlersWithOptions) with an argument, as F(...) or pkg.F(...) with pkg neither a standard-library nor a router import. Test files are gated like any other file (test-scope routes). A dot import binds no name; the link pass counts it from the file's imports.
  2. Router functions (rows RF-*): in a gated file, a function declaration or function literal is captured when its signature has a parameter or result of a router type (X.ServeMux, X.Router, X.Mux, X.Engine, X.RouterGroup, X.IRouter, X.IRoutes, a pointer to one, X a router import) or a result X.Handler, or its body holds a router call that is not excluded (row RC-excluded), a router import member NewServeMux, DefaultServeMux, Handle, HandleFunc, NewRouter, NewMux, New or Default, a router type, a net/http StripPrefix, ListenAndServe, ListenAndServeTLS, Serve, ServeTLS or Server, a generated server's entry call as in the gate, or a function literal that is captured itself. A literal's record follows its parent's.
  3. Router calls (row RC-router): a call whose callee is a selector named Handle, HandleFunc, Get, Post, Put, Patch, Delete, Head, Options, Connect, Trace, Method, MethodFunc, Route, Group, With, Mount, GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS, Any, Match, Static, StaticFS, StaticFile or StaticFileFS, whatever its receiver is (the receiver is proven at link time: miniflux's HTTP client calls c.request.Get(...) are captured and refused there), except row RC-excluded. A call in the receiver chain of a router call (r.With(m) of r.With(m).Get(...), Group(...).Use(...)) is part of that call's tree and not listed on its own; a router call in another captured call's arguments is listed on its own too.
  4. Exclusion (row RC-excluded): a router-named call whose receiver no contract row can prove a router: the receiver is the package name of a non-router import (slog.Any(...): a package function); the receiver chain starts at a parameter declared with a qualified type that is no router type (*gin.Context, *http.Request, *testing.T), never rebound in the function; the receiver is a parameter of another type (s *Server), directly or through method calls, never rebound (a field of it is kept: a router in a struct field is receiver_unproven, counted); the receiver is a local whose every binding holds a value that cannot be a router (the router filter below: query := location.Query(), a composite literal). GR-O4 binds only parameters of the router types, and GR-K3 refuses fields, elements, type assertions and receives, so none of these is a proven router object.
  5. Plain calls (row RC-call): a call of a name (not a predeclared function) or of x.F (x a name that is not a standard-library or router import) outside a captured call's arguments, with an argument that may hold a router by the router filter: the calls the Go linker's rules can resolve to a module function or method that may receive a router (GR-O4). Serving calls (row RC-serve): a call of a standard-library function (x.F, x a standard-library import, net/http included) outside a captured call's arguments, another serving call, a binding's value and a return (those are kept whole), that is net/http's ListenAndServe, ListenAndServeTLS, Serve or ServeTLS or whose arguments hold a net/http StripPrefix or serving call (outside function literals): http.ListenAndServe(addr, http.StripPrefix(p, mux)), log.Fatal(http.ListenAndServe(addr, cors(mux))). It is kept whatever its arguments are, and its arguments are walked as outside a captured call (a plain or router call inside is still listed on its own). Generated-server calls (row RC-generated): a call of a generated server's entry function (as in the gate) outside a captured call's arguments, a serving call, a binding's value and a return is kept whatever its arguments are (api.HandlerWithOptions(s, api.ChiServerOptions{BaseURL: "/v1"})); a binding whose value holds one is kept too (rule 7).
  6. Router filter (rows RC-call, RC-excluded, RE-closure): per record, a value may hold a router when it is a name that may, a call of f(...) (not predeclared), of pkg.F(...) (not a standard-library package; a router package only for NewServeMux, NewRouter, NewMux, New, Default), of x.M(...) with x a parameter (not of a qualified non-router type), a free name, a local declared var x T or a local that may hold a router, a call of Route, Group, With or Use on a call that may (r.With(a).With(b)), new(X.ServeMux) (GR-K4), a conversion or & of such a value, or X.DefaultServeMux. A name may when it is a parameter of a router type, a name one of whose bindings may, or a name the record neither declares nor binds (a package-level or enclosing name). Every other value (literal, composite literal, field, index, slice, type assertion, receive, range or type-switch variable, function literal, a call through a field such as w.Body.String()) is no proven router object.
  7. Bindings (rows RL-*): every declaration or = assignment in the record's body (outside nested literals) of a name that the record's kept calls and returns, its nested records or the kept values of other bindings use; every binding of such a name is kept, so shadowing and reassignment stay visible. A binding whose value holds a net/http StripPrefix or serving call or an http.Server composite literal (outside function literals) is kept too (step GR4: a serving position may read it), with the names its value uses. An assignment x.Handler = v (one target, x an identifier, one value) is kept always, as kind handler with x and the names v uses (row RL-handler: an http.Server's handler set by an assignment is a serving position when x is a server); a function with a parameter of type http.Server or *http.Server is a router function.
  8. Package-level vars (rows RV-*): var specs of the gated file whose value or type mentions router syntax, or whose names a captured record uses.

Signatures (rows RS-*) and //go:debug lines (row RD-debug) are not gated: a handler's receiver type may come from a constructor in any file (GR-H2), and the httpmuxgo121 setting of a main package may sit in any file (GR-V2).

Wrappers and request helpers

Contract row GR-O7 passes a router through a call of a module wrapper only where the wrapper provably leaves the request path unchanged. The capture records the local part of that proof for every file that imports net/http (test files included), outside the route gate (rows RW-* and RQ-*); the link pass resolves the calls and decides the rest. The proof follows Go 1.27.1: ServeMux.ServeHTTP and findHandler dispatch on the request's RequestURI, Proto, Method, Host and URL (its EscapedPath, Host and RawQuery); r.WithContext(c) returns a shallow copy that shares the URL (request.go).

At link time (contract row GR-O7) a call f(x), pkg.F(x) or v.M(x) of a recorded wrapper (resolved as GR-O5 resolves factories; v typed as GR-H2 types a receiver; exactly one declaration of the name) passes the router objects of its http.Handler argument through when every pass resolves: f to the functions of the declaring package, pkg.F to a module package's functions, recv.M to the methods of the receiver's type, each target (every build variant of the name) a request helper whose request parameter is the argument passed and whose own passes resolve the same way (the greatest such set of helpers: a cycle of helpers that only read keeps the path). A wrapper with Context passes no chi router (chi reads its routing state from the context). Since unit GR8 a wrapper whose Guards resolve to a request helper that reads the URL or the method (URL, Method, directly or through its passes), or to no helper, passes nothing (the helper may decide by the path); its Methods travel with the routers it passes (on the composition edge or the serving position) and refuse the paths of the inner routes of those methods and of ANY routes (a CORS preflight answered by the wrapper never reaches an inner OPTIONS route).

Forwarding closures

Contract row GR-O8 reads a function literal registered as a ServeMux's / handler as the router it serves, where the literal provably serves the request it receives unchanged. The capture records the local proof on every function literal it reduces (rows RE-forward and RE-forward-D): Forward (Name, Passes, Shadows) when the literal

Otherwise the literal has no Forward (row RE-forward-D). The link pass decides whether X holds a router, whether the passes keep the path, whether a guard reads the URL or the method (then no proof), which composed paths the shadows refuse and which methods are answered by the closure (rows GR-O8 and GR-C7).

Escapes

Contract row GR-C4 makes a router object a root only when every use of every value that holds it is a use a row reads. The kept syntax (bindings, calls, returns) shows the uses the payload keeps; the capture adds the rest for every captured record (rows RU-escape and RU-context), scanning the body, and the bodies of the function literals it does not capture, outside the kept syntax:

The link pass (gohttp_escape.go) walks the kept bindings (by target), the returns (a return GR-O5 or GR-O9 reads is a use; any other return escapes), the kept calls with a Context, and the escape records. A walked value goes into a call's arguments by the callee: a registration, composition or child call on proven routers, a serving function and a generated server's entry call read theirs; StripPrefix, TimeoutHandler, MaxBytesHandler, http.Handler and http.HandlerFunc and a proven wrapper carry their handler to the call's destination; an argument bound to a router-typed parameter (GR-O4) is read in the callee; an http.Handler argument of a module function whose one result is an http.Handler goes with the call's value when that is bound locally or read by a row; a router value passed to an http.Handler parameter whose every use in the callee (and its literals) serves it at its own paths (an http.Server literal's Handler, a serving call's handler, srv.Handler = h, h.ServeHTTP), never reassigned and named by no escape record, is served (miniflux's newHTTPServer; the capture treats http.Handler parameters as values that may hold a router, so their uses are kept or recorded); the handler of httptest.NewServer, NewTLSServer and NewUnstartedServer named directly is served; every other argument escapes. An escaping value's objects (directly, or inside the calls and closures its bindings hold) are escaped_router, named in route_mount_unresolved; a parameter's escape is that of every object bound to it. A ServeMux that escapes makes a GR-C7 gate opaque.

Generated servers

Contract row GR-G1 (developer decision GO2) reads the HTTP servers oapi-codegen generates (oapi-codegen -generate chi-server, gin-server or std-http-server). The capture (internal/lang/golang/oapi.go, row RO-server) accepts a gated file only when:

The templates are oapi-codegen v2.8.0's pkg/codegen/templates (chi/chi-handler.tmpl, chi/chi-middleware.tmpl, gin/gin-register.tmpl, gin/gin-wrappers.tmpl, stdhttp/std-http-handler.tmpl, stdhttp/std-http-middleware.tmpl) and the path helpers of pkg/codegen/utils.go, read from the Go module proxy (github.com/oapi-codegen/oapi-codegen/v2, Apache License 2.0; nothing is built or run, nothing added to Graphvein's go.mod). v2.8.1 and v2.8.2 have the same files byte for byte; v2.7.2 and earlier differ (the chi middleware template and the path helpers), so their files are row RO-D. The record says only that the shape matched; the link pass decides the routers, BaseURL and handlers from the entry calls (GR-G1).

Payload

facts.GoFacts (JSON Go), version 7, fields added by T023 GR1, GR5 and GR6 (the GORM and structure fields are documented in docs/lang/go-models.md and docs/lang/go-structure.md). Spans are contract v1 spans (1-based lines, 0-based byte columns, end exclusive) of the scanner's text.

Validity: GoFacts.ModelsValid() also checks the router payload (record order, parent and block indexes, block trees, kinds, spans, router calls with a hash and plain calls without, expression kinds and the funclit fields); the indexer checks it on every cache read, so a payload of another version or a damaged one is re-extracted. A capture failure (a recovered panic) behaves as the GORM payload's: diagnostic model_syntax_capture_failed, no payload, the next run tries again.

Payload table

Every capture branch in internal/lang/golang/routes.go reports one row id below; TestGoRoutePayloadContract checks that the Go table and this table match 1:1, that a snippet per row fills exactly the row's fields, and that the snippets together emit exactly the rows of the table.

id form payload
RG-chi a file importing github.com/go-chi/chi/v5, github.com/go-chi/chi or another github.com/go-chi/chi/vN routes: Routes
RG-gin a file importing github.com/gin-gonic/gin (and no chi path) routes: Routes
RG-http a file importing net/http (and neither chi nor gin) that mentions ServeMux, NewServeMux, DefaultServeMux, Handle or HandleFunc as a selector or qualified type of its net/http name routes: Routes
RG-generated a file passing none of the gates above that calls a generated server's entry function (Handler, HandlerFromMux, HandlerFromMuxWithBaseURL, HandlerWithOptions, RegisterHandlers or RegisterHandlersWithOptions) with at least one argument, as F(...) or pkg.F(...) with pkg an import that is neither a standard-library nor a router package (contract row GR-G1) routes: Routes
RG-D every other file nothing
RF-decl a function or method declaration with a body in a gated file that is a router function (see Gate and filters, 2) func: Name, Receiver, Params, Results, Span, Blocks, Bindings, Calls, Returns
RF-literal a function literal that is a router function, inside a captured record or a kept package var func: Parent, Block, Params, Results, Span, Blocks, Bindings, Calls, Returns
RF-D any other function declaration or literal of a gated file (a literal inside router syntax is row RE-closure) nothing
RB-body the body of a captured record block: Kind
RB-block a bare { } block block: Parent, Kind
RB-if an if statement (initializer and condition) block: Parent, Kind
RB-then an if statement's consequence block: Parent, Kind
RB-else an if statement's alternative block: Parent, Kind
RB-for a for statement, any clause block: Parent, Kind
RB-switch an expression or type switch (initializer and tag) block: Parent, Kind
RB-case a case or default clause of a switch, type switch or select block: Parent, Kind
RB-go a go statement block: Parent, Kind
RB-defer a defer statement block: Parent, Kind
RL-var a var spec in a body, kept (see Gate and filters, 7) binding: Kind, Names, Type, Values, Block, Span
RL-define a := declaration or a select receive x := <-c, kept binding: Kind, Names, Values, Block, Span
RL-assign an = assignment or receive x = <-c with at least one identifier target, kept binding: Kind, Names, Values, Block, Span
RL-const a const spec in a body, kept binding: Kind, Names, Values, Block, Span
RL-range a for k, v := range e clause, kept binding: Kind, Names, Values, Block, Span
RL-range_assign a for k, v = range e clause, kept binding: Kind, Names, Values, Block, Span
RL-typeswitch a type switch guard switch x := e.(type), kept binding: Kind, Names, Values, Block, Span
RL-handler an = assignment x.Handler = v with one target, x an identifier, and one value (step GR5: a serving position when x is an http.Server, row GR-C6); kept always, with the bindings of the names it uses; Names holds x (no name is declared or assigned) binding: Kind, Names, Values, Block, Span
RL-D a binding no kept syntax uses; compound assignments (+=), increments, assignments without an identifier target (other than RL-handler) nothing
RC-router a router call (see Gate and filters, 3) call: Kind, Call, Block, Span, Hash, Context
RC-call a plain call that may pass a router on (see Gate and filters, 5) call: Kind, Call, Block, Span, Context
RC-serve a serving call (see Gate and filters, 5): a standard-library call outside a binding's value and a return that is a net/http serving function or holds a net/http StripPrefix or serving call call: Kind, Call, Block, Span, Context
RC-generated a call of a generated server's entry function as in RG-generated, outside a captured call's arguments, a serving call, a binding's value and a return (those keep it in their tree), kept whatever its arguments are call: Kind, Call, Block, Span, Context
RC-excluded a router-named call on a receiver no rule proves a router (see Gate and filters, 4) nothing
RC-D every other call (kept only inside a captured tree) nothing
RR-return a return statement of a captured record (outside nested literals) return: Values, Block, Span
RJ-jump a goto statement, or a break or continue naming a label, in a captured record's body (outside nested literals); a plain break or continue is not one jump: Jumps
RU-escape a position outside the record's kept syntax (kept bindings, calls and returns) where a value that may hold a router goes somewhere no contract row reads (see Escapes): a store to a field, element, dereference or a name the scope does not declare; a composite literal element; an argument of a call the payload does not keep (with the call's value bound locally, the arguments go with it); a channel send; the receiver of a method other than a router's own or a router method value; a return of a function literal with no record; a handler-shaped literal (Request) in one of those positions escape: Form, Value, Detail, Type, Block, Span
RU-context a kept call that lies in syntax the payload does not keep: an expression, go or defer statement or a condition operand (statement), or the value of a binding to a local the scope declares (local) call: Context
RE-funclit a function literal inside a kept tree that has a captured record expression: Kind, Func
RE-closure a function literal inside a kept tree that has no record expression: Kind, Uses
RE-forward a function literal inside a kept tree whose syntax passes the forwarding proof (see Forwarding closures), in addition to RE-funclit or RE-closure expression: Forward
RE-forward-D any other function literal inside a kept tree nothing
RE-request a function literal inside a kept tree with a *http.Request parameter of the file's net/http name, in addition to RE-funclit or RE-closure (a captured literal's Uses are filled too) expression: Request
RE-text an argument of a router-named call, other than a function literal expression: Text
RV-var a package-level var spec of a gated file that mentions router syntax or whose names a captured record uses var: Names, Type, Values, Line
RV-D every other package-level var spec of a gated file nothing
RK-const a package-level constant of a gated _test.go file whose value is string literals, names (not iota), selectors and + of those const: Name, Type, Value, Line
RK-D any other package-level constant of a gated _test.go file nothing
RS-signature a function without receiver of a non-test file that declares exactly one result of type T, *T, pkg.T or *pkg.T, T not predeclared signature: Name, Result, Line
RS-D any other function declaration of a non-test file nothing
RO-server a gated file whose header, before the package clause, holds the line // Code generated by github.com/oapi-codegen/oapi-codegen/v2 version vX.Y.Z DO NOT EDIT. with version v2.8.0, v2.8.1 or v2.8.2, that imports net/http and either github.com/go-chi/chi/v5 or github.com/gin-gonic/gin or neither (all unaliased, no other aliased import), and whose server declarations equal the templates token for token (see "Generated servers") generated: Generator, Version, Framework
RO-D a file with an oapi-codegen header of another version, other imports or declarations that differ from the templates nothing
RN-names every Go file: per name a call may target (an identifier F, a selector .M of a value, imp:<path>.F of an import), the count of its calls and of its other uses (not declaration names, assignment or definition targets, keyed-element keys, labels or type names) names: Names
RN-results every Go file: for each call of a module function or method outside the captured router syntax, each use of its result (directly, or through the names a binding gives it in the enclosing body) that no row reads by construction: an argument of a module call (argument: Callee, Arg), a return (return: Callee the enclosing function), anything else (other); a discarded call, a serving call's handler (net/http, httptest), an http.Server's Handler, a router's own method or ServeHTTP record nothing names: Results
RD-debug a header line //go:debug ... that mentions httpmuxgo121 debug: Debug
RW-wrapper a function or method declaration of a file importing net/http with exactly one http.Handler parameter and one http.Handler result whose syntax passes the wrapper proof (see Wrappers and request helpers) wrapper: Name, Receiver, Param, Context, Passes, Methods, Guards, Line
RW-D a declaration with that signature whose syntax fails the proof nothing
RQ-request any other function or method declaration of such a file with exactly one named *http.Request parameter whose every use is a read or a pass (see Wrappers and request helpers) request: Name, Receiver, Param, Passes, URL, Method, Line
RQ-D every other function or method declaration with a body of such a file nothing

Census (the T023 investigation corpora)

TestGoRoutesCensus (set GRAPHVEIN_GO_ROUTES_CENSUS_CORPUS to the corpus directory holding realworld-gin, gotify, dozzle, miniflux and owncast, cloned by scripts/cloud-corpus.sh) parses the five corpora at their pins and checks every route and compose row of docs/contract/claims/data/go-http-routers-census.jsonl (sites only): the row's file passes the gate and the payload holds a router call at the row's position whose receiver chain names the row's method. Captured router calls the census does not list (HTTP client and test-helper calls named Get, Handle or Group on receivers the filters cannot rule out) are the link pass's to refuse; the test logs their count per corpus.

corpus census sites Go files gated router calls not in the census
realworld-gin 62 21 12 1 (Get)
gotify 71 142 51 4 (Get 2, Group, Handle)
dozzle 106 402 18 30 (Get)
miniflux 181 441 8 0
owncast 519 472 6 2 (Get)

Refreshed (Go payload version 5): the gate also passes files that only serve a router (StripPrefix, ListenAndServe, Serve, Server: gotify 50 to 51, miniflux 5 to 8 gated files). The unlisted router calls fell from 40 to 30 (dozzle) and 5 to 4 (gotify) against step GR1's table, after the filter forms of payload versions 4 and 5.

Known gaps

Report a problem with this pageSource: docs/lang/go-routes.md