Generate the OpenAPI document from a route table
Security / Vulnerability check (push) Successful in 38s
Test / Lint and test (push) Successful in 1m53s

The server registers its routes from one table in server/routes.go, and
tools/genopenapi (run by go generate) writes docs/swagger.json, an
OpenAPI 3.1 document, from the same table and the Go types it names.
Schemas are reflected with invopop/jsonschema: descriptions from the
first paragraph of the doc comments, enums and limits from jsonschema
tags. Request schemas are strict, as the decoder is; response schemas
allow fields added later. The daemon serves the embedded document at
GET /openapi.json without a token, internal/app passes it to the server
in its config, and release archives and the Docker build include it.

Tests keep it honest: a golden test and a CI step fail when the
document is stale, every registered route must be in the table, and the
tags are held to validation, to the Go constants and to the values the
handlers send. receipt.Element and printqueue.Status gain field doc
comments for the descriptions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 09:30:42 -06:00
1 parent 9f7c5db923
commit bdd337e2dc
31 files changed
+3153 -128

No files matched your search

+2
View File
@@ -14,6 +14,7 @@ import (
"go.jetify.com/typeid"
"golang.org/x/sync/errgroup"
"uberbringer/docs"
"uberbringer/internal/app/uberbringer/server"
"uberbringer/internal/pkg/config"
"uberbringer/internal/pkg/escpos"
@@ -97,6 +98,7 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
WriteTimeout: cfg.WebServer.WriteTimeout,
IdleTimeout: cfg.WebServer.IdleTimeout,
RequestID: newRequestID,
OpenAPI: docs.OpenAPI(),
}, server.Deps{Jobs: queue, Printer: printerClient, Previewer: renderer}, logger)
addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port))
+6 -2
View File
@@ -79,8 +79,12 @@ func (e *apiError) Error() string { return e.message }
// errorResponse is the JSON body of every error.
type errorResponse struct {
Error string `json:"error"`
Code string `json:"code"`
// Error says what went wrong, for people. It may change.
Error string `json:"error"`
// Code is stable and meant for clients to match on.
Code string `json:"code"`
// Details lists every problem when an invalid_job fails validation, each
// naming the element by its path, e.g. elements[0].children[3] (qr).
Details []string `json:"details,omitempty"`
}
+64 -19
View File
@@ -19,21 +19,47 @@ import (
// healthTimeout bounds the printer status check behind /healthz.
const healthTimeout = 3 * time.Second
// indexResponse describes the running build.
type indexResponse struct {
// Project is the project's name.
Project string `json:"Project"`
// Description says what the daemon does.
Description string `json:"Description"`
// Authors is where the project lives.
Authors string `json:"Authors"`
// Version is the release, e.g. 0.2.0, or dev for a local build.
Version string `json:"Version"`
// Build is the commit the binary was built from.
Build string `json:"Build"`
}
func (s *Server) handleIndex(c fiber.Ctx) error {
info := s.config.Info
return c.JSON(fiber.Map{
"Project": info.Project,
"Description": info.Description,
"Authors": info.Authors,
"Version": info.Version,
"Build": info.Build,
})
return c.JSON(indexResponse(s.config.Info))
}
func handleRobots(c fiber.Ctx) error {
return c.SendString("User-agent: *\nDisallow:\n")
}
// openAPIDocument is the body of GET /openapi.json: this API's OpenAPI 3.1
// document, generated from the route table.
type openAPIDocument struct {
// OpenAPI is the OpenAPI version the document follows.
OpenAPI string `json:"openapi"`
// Info names the API and its version.
Info map[string]any `json:"info"`
// Paths are the routes.
Paths map[string]any `json:"paths"`
// Components holds the schemas of the request and response bodies.
Components map[string]any `json:"components"`
}
// handleOpenAPI answers with the configured OpenAPI document.
func (s *Server) handleOpenAPI(c fiber.Ctx) error {
c.Set(fiber.HeaderContentType, mediaJSON)
return c.Send(s.config.OpenAPI)
}
// handlePrint validates and queues a job.
func (s *Server) handlePrint(c fiber.Ctx) error {
job, err := decodeValidJob(c.Body())
@@ -121,21 +147,40 @@ func (s *Server) handleJob(c fiber.Ctx) error {
// printerHealth is the printer part of the /healthz response.
type printerHealth struct {
// Reachable is omitted when it is unknown, e.g. after a timeout.
Reachable *bool `json:"reachable,omitempty"`
Status string `json:"status"`
Online *bool `json:"online,omitempty"`
CoverOpen *bool `json:"cover_open,omitempty"`
Paper string `json:"paper,omitempty"`
Error string `json:"error,omitempty"`
// Reachable is whether the printer accepted a connection; it is omitted
// when that is unknown, e.g. after a timeout.
Reachable *bool `json:"reachable,omitempty"`
// Status is ready, not_ready, unknown for a printer that does not
// answer status requests, unreachable, or timeout when the status read
// ran out of time.
Status string `json:"status" jsonschema:"enum=ready,enum=not_ready,enum=unknown,enum=unreachable,enum=timeout"`
// Online is whether the printer reports itself online.
Online *bool `json:"online,omitempty"`
// CoverOpen is reported only while the printer is offline: Epson
// printers go offline when the cover opens.
CoverOpen *bool `json:"cover_open,omitempty"`
// Paper is ok, near_end or out.
Paper string `json:"paper,omitempty" jsonschema:"enum=ok,enum=near_end,enum=out"`
// Error is set when the printer reports an error, such as a cutter
// error.
Error string `json:"error,omitempty"`
}
// healthResponse is the body of GET /healthz.
type healthResponse struct {
Status string `json:"status"`
// Status is ok, degraded when the printer is not ready, or unavailable
// when it is unreachable or did not answer in time.
Status string `json:"status" jsonschema:"enum=ok,enum=degraded,enum=unavailable"`
// Printer is the printer's state.
Printer printerHealth `json:"printer"`
Queue struct {
Pending int `json:"pending"`
} `json:"queue"`
// Queue is the print queue's state.
Queue queueHealth `json:"queue"`
}
// queueHealth is the queue part of the /healthz response.
type queueHealth struct {
// Pending is how many jobs wait to be printed.
Pending int `json:"pending"`
}
// handleHealth reports whether the printer is reachable and ready. It
@@ -41,31 +41,54 @@ func (s *Server) handlePreview(c fiber.Ctx) error {
// previewResponse is the JSON form of a preview.
type previewResponse struct {
Columns int `json:"columns"`
CodePage string `json:"codepage"`
LineCount int `json:"line_count"`
Lines []previewLine `json:"lines"`
Warnings []string `json:"warnings"`
// Columns is the number of Font A characters per line.
Columns int `json:"columns"`
// CodePage is the code page text is printed in.
CodePage string `json:"codepage"`
// LineCount is the lines the receipt prints, all copies counted: text
// lines, fed lines, and one for each QR code, barcode and image.
LineCount int `json:"line_count"`
// Lines are the lines as they print, in order.
Lines []previewLine `json:"lines"`
// Warnings name the elements with characters the code page lacks, and
// images wider than the paper.
Warnings []string `json:"warnings"`
}
// previewLine is one line of a preview.
type previewLine struct {
Kind string `json:"kind"`
Text string `json:"text"`
// Kind is what printed the line.
Kind string `json:"kind" jsonschema:"enum=text,enum=qr,enum=barcode,enum=image,enum=raw,enum=cut"`
// Text is the line as it prints, or a placeholder such as
// [qr: https://example.com].
Text string `json:"text"`
// Runs are the styled parts of text. Plain Font A text at size 1 has
// none.
Runs []previewRun `json:"runs,omitempty"`
Data string `json:"data,omitempty"`
// Data is the QR code or barcode data, the image URL (or base64), the
// number of raw bytes, or the cut mode.
Data string `json:"data,omitempty"`
}
// previewRun is a styled range of a line's text, in characters [from, to).
// Width and height are omitted at scale 1, font when it is a.
type previewRun struct {
From int `json:"from"`
To int `json:"to"`
Bold bool `json:"bold,omitempty"`
Underline int `json:"underline,omitempty"`
Invert bool `json:"invert,omitempty"`
Font string `json:"font,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
// From is the first character of the run.
From int `json:"from"`
// To is the character after the run.
To int `json:"to"`
// Bold is set for bold text.
Bold bool `json:"bold,omitempty"`
// Underline is 1 for a thin and 2 for a thick underline.
Underline int `json:"underline,omitempty" jsonschema:"enum=1,enum=2"`
// Invert is set for white on black.
Invert bool `json:"invert,omitempty"`
// Font is b for the smaller font.
Font string `json:"font,omitempty" jsonschema:"enum=b"`
// Width is the character width multiplier, when it is not 1.
Width int `json:"width,omitempty"`
// Height is the character height multiplier, when it is not 1.
Height int `json:"height,omitempty"`
}
func newPreviewResponse(p receipt.Preview) previewResponse {
+259
View File
@@ -0,0 +1,259 @@
package server
import (
"net/http"
"regexp"
"strings"
"github.com/gofiber/fiber/v3"
"uberbringer/internal/pkg/printqueue"
"uberbringer/internal/pkg/receipt"
)
// BasePath prefixes the routes that need a bearer token.
const BasePath = "/api/v1"
// Media types the routes answer with.
const (
mediaJSON = fiber.MIMEApplicationJSON
mediaText = fiber.MIMETextPlainCharsetUTF8
)
// Route is one route of the HTTP API. The server registers it from this
// table and tools/genopenapi documents it in docs/swagger.json, so the two
// cannot differ.
type Route struct {
Method string
// Path is in OpenAPI form, e.g. /api/v1/jobs/{id}.
Path string
OperationID string
Summary string
Description string
Tag string
// Auth routes are under BasePath: they need a bearer token, are rate
// limited per client and answer with Cache-Control: no-store.
Auth bool
// NoStore adds Cache-Control: no-store to a route without Auth.
NoStore bool
// Request is the zero value of the JSON request body's type, or nil.
Request any
// Params are the route's path, query and header parameters.
Params []Param
Responses []Response
// errors are the codes the handler answers with itself;
// DocumentedErrors adds those of the middleware.
errors []errorCode
handle func(*Server, fiber.Ctx) error
}
// Response is one documented answer of a route that is not an error.
type Response struct {
Status int
Description string
// Content lists the bodies by media type; none for an empty answer.
Content []Content
// Headers are the headers it carries besides Content-Type.
Headers []Header
}
// Content is a response body in one media type.
type Content struct {
MediaType string
// Body is the zero value of the body's type; a string is a text body.
Body any
}
// Header is a response header a route documents.
type Header struct {
Name string
Description string
// Integer headers carry a whole number, the rest a string.
Integer bool
}
// Param is a path, query or header parameter of a route.
type Param struct {
Name string
// In is "path", "query" or "header".
In string
Description string
Required bool
}
// ErrorDoc is an error code a route can answer with.
type ErrorDoc struct {
Status int
Code string
Message string
}
// ErrorBody returns the zero value of the body every error answers with.
func ErrorBody() any { return errorResponse{} }
// DocumentedErrors returns the codes the route can answer with: its own and
// those of the middleware it runs behind.
func (r Route) DocumentedErrors() []ErrorDoc {
codes := append([]errorCode(nil), r.errors...)
if r.Request != nil {
codes = append(codes, codeBodyTooLarge)
}
if r.Auth {
codes = append(codes, codeUnauthorized, codeRateLimited)
}
codes = append(codes, codeInternal)
return errorDocs(codes)
}
// ServerErrors returns the codes the HTTP server itself can answer any
// request with: for a malformed or slow request, for an unknown route or
// method, and for an unsupported transfer coding.
func ServerErrors() []ErrorDoc {
return errorDocs([]errorCode{codeBadRequest, codeNotFound, codeMethodNotAllowed, codeRequestTimeout,
codeHeadersTooLarge, codeNotImplemented})
}
func errorDocs(codes []errorCode) []ErrorDoc {
docs := make([]ErrorDoc, len(codes))
for i, c := range codes {
docs[i] = ErrorDoc{Status: c.status, Code: c.code, Message: c.message}
}
return docs
}
// Routes returns the route table.
func Routes() []Route {
return []Route{
{
Method: http.MethodGet,
Path: "/",
OperationID: "getInfo",
Summary: "Version information",
Description: "The project's name, description and authors, and the version and build of the running daemon.",
Tag: "meta",
Responses: []Response{{Status: http.StatusOK, Description: "The running build",
Content: []Content{{MediaType: mediaJSON, Body: indexResponse{}}}}},
handle: (*Server).handleIndex,
},
{
Method: http.MethodGet,
Path: "/robots.txt",
OperationID: "getRobots",
Summary: "Robots exclusion file",
Tag: "meta",
Responses: []Response{{Status: http.StatusOK, Description: "A robots.txt that allows everything",
Content: []Content{{MediaType: mediaText, Body: ""}}}},
handle: func(_ *Server, c fiber.Ctx) error { return handleRobots(c) },
},
{
Method: http.MethodGet,
Path: "/openapi.json",
OperationID: "getOpenAPI",
Summary: "This API's OpenAPI document",
Description: "The OpenAPI 3.1 document of this API, generated from its route table, as the running " +
"build serves it.",
Tag: "meta",
Responses: []Response{{Status: http.StatusOK, Description: "The document",
Content: []Content{{MediaType: mediaJSON, Body: openAPIDocument{}}}}},
handle: (*Server).handleOpenAPI,
},
{
Method: http.MethodGet,
Path: "/healthz",
OperationID: "getHealth",
Summary: "Printer and queue health",
Description: "Reads the printer's real-time status. A printer that looks not ready is read again " +
"750 ms later, and only a problem that is still there gives 503. A printer that does not " +
"answer status requests is reported as status unknown with 200.",
Tag: "health",
NoStore: true,
Responses: []Response{
{Status: http.StatusOK, Description: "The printer is reachable and ready, or does not report status",
Content: []Content{{MediaType: mediaJSON, Body: healthResponse{}}}},
{Status: http.StatusServiceUnavailable, Description: "The printer is unreachable, not ready, " +
"or did not answer in time", Content: []Content{{MediaType: mediaJSON, Body: healthResponse{}}}},
},
handle: (*Server).handleHealth,
},
{
Method: http.MethodPost,
Path: BasePath + "/print",
OperationID: "printJob",
Summary: "Queue a print job",
Description: "Validates the whole job and queues it. The worker renders it in full before anything " +
"is sent to the printer, and fetches its images then, so a broken image URL shows up as a " +
"failed job.",
Tag: "print",
Auth: true,
Request: receipt.Job{},
Responses: []Response{{Status: http.StatusAccepted, Description: "The job is queued",
Content: []Content{{MediaType: mediaJSON, Body: printqueue.Status{}}},
Headers: []Header{{Name: fiber.HeaderLocation, Description: "The job's URL, which answers with " +
"its status."}}}},
errors: []errorCode{codeInvalidJob, codeQueueFull, codeShuttingDown},
handle: (*Server).handlePrint,
},
{
Method: http.MethodPost,
Path: BasePath + "/preview",
OperationID: "previewJob",
Summary: "Show the lines a job prints, without printing it",
Description: "Validates the job as /api/v1/print does, renders it and reads the lines back from " +
"the rendered bytes. It prints nothing and fetches no images. The answer is JSON with the " +
"lines' styles when the Accept header prefers application/json to text/plain (for example " +
"application/json or application/*), and plain text otherwise.",
Tag: "print",
Auth: true,
Request: receipt.Job{},
Responses: []Response{{Status: http.StatusOK, Description: "The lines the printer would print",
Content: []Content{
{MediaType: mediaText, Body: ""},
{MediaType: mediaJSON, Body: previewResponse{}},
}}},
errors: []errorCode{codeInvalidJob, codeTooManyLines},
handle: (*Server).handlePreview,
},
{
Method: http.MethodGet,
Path: BasePath + "/jobs/{id}",
OperationID: "getJob",
Summary: "Job status",
Description: "The status of a queued, printing or finished job. The last queue.history finished " +
"jobs are kept.",
Tag: "print",
Auth: true,
Params: []Param{{Name: "id", In: "path", Required: true, Description: "The job's ID, a job_ TypeID."}},
Responses: []Response{{Status: http.StatusOK, Description: "The job's status",
Content: []Content{{MediaType: mediaJSON, Body: printqueue.Status{}}}}},
errors: []errorCode{codeJobNotFound},
handle: (*Server).handleJob,
},
}
}
// pathParam finds the {name} parameters in a route path.
var pathParam = regexp.MustCompile(`\{([^/{}]+)\}`)
// fiberPath turns an OpenAPI path into Fiber's form: {id} becomes :id.
func fiberPath(path string) string {
return pathParam.ReplaceAllString(path, ":$1")
}
// registerRoutes adds every route of the table to the app. api is the group
// at BasePath that holds the bearer token, rate limit and no-store
// middleware.
func (s *Server) registerRoutes(api fiber.Router) {
for _, r := range Routes() {
handler := func(c fiber.Ctx) error { return r.handle(s, c) }
path := fiberPath(r.Path)
switch {
case r.Auth:
api.Add([]string{r.Method}, strings.TrimPrefix(path, BasePath), handler)
case r.NoStore:
s.app.Add([]string{r.Method}, path, noStore, handler)
default:
s.app.Add([]string{r.Method}, path, handler)
}
}
}
@@ -0,0 +1,102 @@
package server
import (
"bytes"
"net/http"
"net/http/httptest"
"strings"
"testing"
"uberbringer/docs"
)
// The route table is consistent: every route has a handler, a response and
// a unique operation ID, the routes that need a token are exactly those
// under BasePath, and every path parameter is declared.
func TestRouteTable(t *testing.T) {
ops := map[string]bool{}
routes := map[string]bool{}
for _, r := range Routes() {
key := r.Method + " " + r.Path
if routes[key] {
t.Errorf("%s is in the table twice", key)
}
routes[key] = true
if ops[r.OperationID] || r.OperationID == "" {
t.Errorf("%s: operation ID %q is empty or taken", key, r.OperationID)
}
ops[r.OperationID] = true
if r.handle == nil || len(r.Responses) == 0 || r.Summary == "" || r.Tag == "" {
t.Errorf("%s: needs a handler, a response, a summary and a tag", key)
}
if r.Auth != strings.HasPrefix(r.Path, BasePath+"/") {
t.Errorf("%s: Auth is %v, but the token is needed exactly under %s", key, r.Auth, BasePath)
}
if p := fiberPath(r.Path); strings.ContainsAny(p, "{}") {
t.Errorf("%s: Fiber path %s still has braces", key, p)
}
for _, m := range pathParam.FindAllStringSubmatch(r.Path, -1) {
declared := false
for _, p := range r.Params {
declared = declared || p.In == "path" && p.Name == m[1]
}
if !declared {
t.Errorf("%s: path parameter %s is not in Params", key, m[1])
}
}
}
}
// The server registers exactly the routes of the table, so none can be
// added without being documented.
func TestRegisteredRoutesAreTheTable(t *testing.T) {
want := map[string]bool{}
for _, r := range Routes() {
want[r.Method+" "+fiberPath(r.Path)] = true
}
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
got := map[string]bool{}
for _, route := range s.app.GetRoutes(true) {
if route.Method != http.MethodHead {
got[route.Method+" "+route.Path] = true
}
}
for key := range got {
if !want[key] {
t.Errorf("%s is registered but not in Routes(): add it to the table in routes.go", key)
}
}
for key := range want {
if !got[key] {
t.Errorf("%s is in Routes() but not registered", key)
}
}
}
// GET /openapi.json answers, without a token, with the document embedded in
// the build.
func TestOpenAPIServesEmbeddedDocument(t *testing.T) {
s := newTestServer(t, &fakeJobs{}, &fakePrinter{}, func(c *Config) { c.OpenAPI = docs.OpenAPI() })
resp, body := send(t, s, httptest.NewRequest(http.MethodGet, "/openapi.json", nil))
if resp.StatusCode != http.StatusOK {
t.Fatalf("status %d: %s", resp.StatusCode, body)
}
if ct := resp.Header.Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
t.Errorf("Content-Type = %q", ct)
}
if !bytes.Equal(body, docs.OpenAPI()) {
t.Error("the body is not the embedded document")
}
}
func TestFiberPath(t *testing.T) {
for in, want := range map[string]string{
BasePath + "/jobs/{id}": BasePath + "/jobs/:id",
BasePath + "/jobs/{job_id}/x/{n}": BasePath + "/jobs/:job_id/x/:n",
"/healthz": "/healthz",
} {
if got := fiberPath(in); got != want {
t.Errorf("fiberPath(%q) = %q, want %q", in, got, want)
}
}
}
@@ -0,0 +1,113 @@
package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"go/ast"
"go/parser"
gotoken "go/token"
"maps"
"net/http"
"net/http/httptest"
"reflect"
"slices"
"strconv"
"strings"
"testing"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/printer"
)
// enumOf returns the enum values in the jsonschema tag of typ's field,
// sorted.
func enumOf(t *testing.T, typ reflect.Type, field string) []string {
t.Helper()
f, ok := typ.FieldByName(field)
if !ok {
t.Fatalf("%s has no field %s", typ.Name(), field)
}
var values []string
for part := range strings.SplitSeq(f.Tag.Get("jsonschema"), ",") {
if v, ok := strings.CutPrefix(part, "enum="); ok {
values = append(values, v)
}
}
slices.Sort(values)
return values
}
// The kind enum of a preview line lists every line kind the interpreter
// produces.
func TestPreviewKindEnumListsEveryLineKind(t *testing.T) {
file, err := parser.ParseFile(gotoken.NewFileSet(), "../../../pkg/escpos/interpret.go", nil, 0)
if err != nil {
t.Fatal(err)
}
var kinds []string
ast.Inspect(file, func(n ast.Node) bool {
spec, ok := n.(*ast.ValueSpec)
if !ok {
return true
}
for i, name := range spec.Names {
if !strings.HasPrefix(name.Name, "Line") || i >= len(spec.Values) {
continue
}
if lit, ok := spec.Values[i].(*ast.BasicLit); ok && lit.Kind == gotoken.STRING {
v, _ := strconv.Unquote(lit.Value)
kinds = append(kinds, v)
}
}
return true
})
slices.Sort(kinds)
if enum := enumOf(t, reflect.TypeFor[previewLine](), "Kind"); len(kinds) == 0 || !slices.Equal(kinds, enum) {
t.Errorf("previewLine.Kind enum %v, escpos Line constants %v", enum, kinds)
}
}
// The enums of the /healthz body are exactly the values the handler sends
// over every printer state.
func TestHealthEnumsMatchHandler(t *testing.T) {
printers := []*fakePrinter{
{statuses: []escpos.Status{{Online: true}}},
{statuses: []escpos.Status{{Online: true, PaperNearEnd: true}}},
{statuses: []escpos.Status{{PaperOut: true}}},
{statuses: []escpos.Status{{CoverOpen: true}}},
{statuses: []escpos.Status{{CutterError: true}}},
{err: printer.ErrStatusUnsupported},
{err: errors.New("connection refused")},
{err: fmt.Errorf("reading printer status: %w", context.DeadlineExceeded)},
}
status, printerStatus, paper := map[string]bool{}, map[string]bool{}, map[string]bool{}
for _, p := range printers {
s := newTestServer(t, &fakeJobs{}, p)
_, body := send(t, s, httptest.NewRequest(http.MethodGet, "/healthz", nil))
var resp healthResponse
if err := json.Unmarshal(body, &resp); err != nil {
t.Fatalf("decoding %s: %v", body, err)
}
status[resp.Status] = true
printerStatus[resp.Printer.Status] = true
if resp.Printer.Paper != "" {
paper[resp.Printer.Paper] = true
}
}
for _, tt := range []struct {
typ reflect.Type
field string
seen map[string]bool
}{
{reflect.TypeFor[healthResponse](), "Status", status},
{reflect.TypeFor[printerHealth](), "Status", printerStatus},
{reflect.TypeFor[printerHealth](), "Paper", paper},
} {
seen := slices.Sorted(maps.Keys(tt.seen))
if enum := enumOf(t, tt.typ, tt.field); !slices.Equal(seen, enum) {
t.Errorf("%s.%s enum %v, the handler sends %v", tt.typ.Name(), tt.field, enum, seen)
}
}
}
+6 -8
View File
@@ -80,6 +80,10 @@ type Config struct {
// RequestID generates request IDs.
RequestID func() string
// OpenAPI is the API's OpenAPI document, which GET /openapi.json
// answers with.
OpenAPI []byte
// HealthRecheckDelay is how long /healthz waits before re-reading a
// printer that looked not ready. Zero means defaultHealthRecheckDelay.
HealthRecheckDelay time.Duration
@@ -140,11 +144,7 @@ func New(config Config, deps Deps, logger *slog.Logger) *Server {
s.app.Use(requestid.New(requestid.Config{Generator: config.RequestID}))
s.app.Use(compress.New(compress.Config{Level: compress.LevelBestSpeed}))
s.app.Get("/", s.handleIndex)
s.app.Get("/robots.txt", handleRobots)
s.app.Get("/healthz", noStore, s.handleHealth)
api := s.app.Group("/api/v1",
api := s.app.Group(BasePath,
noStore,
limiter.New(limiter.Config{
Max: config.RateLimit,
@@ -154,9 +154,7 @@ func New(config Config, deps Deps, logger *slog.Logger) *Server {
}),
requireBearerToken(config.Secret),
)
api.Post("/print", s.handlePrint)
api.Post("/preview", s.handlePreview)
api.Get("/jobs/:id", s.handleJob)
s.registerRoutes(api)
return s
}
@@ -702,9 +702,10 @@ func TestRateLimitPerClientBehindProxy(t *testing.T) {
func TestRoutesConform(t *testing.T) {
id := newJobID(t)
public := map[string]bool{
"GET /": true,
"GET /robots.txt": true,
"GET /healthz": true,
"GET /": true,
"GET /robots.txt": true,
"GET /healthz": true,
"GET /openapi.json": true,
}
// Each authenticated route maps to a path that reaches it.
authenticated := map[string]string{
@@ -732,7 +733,7 @@ func TestRoutesConform(t *testing.T) {
}
})
default:
t.Errorf("%s has no conformance case: add one here and a row to the API table in docs/api.md", key)
t.Errorf("%s has no conformance case: add it to the table in routes.go, a case here and a row to the API table in docs/api.md", key)
}
}
for key := range authenticated {