router

package module
v0.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 3, 2026 License: MIT Imports: 14 Imported by: 0

README

go-router

go-router

Documentation · Part of go-webthings.

go-router is a lightweight router for Go websites and APIs. It builds on the standard library net/http ServeMux and adds the pieces most small and medium applications usually end up needing: route groups, middleware, named routes, host and subdomain routing, mounted routers, OpenAPI helpers, route walking, static files, and practical middleware.

It is designed for applications that want to stay close to net/http without giving up website/API ergonomics.

Features

  • Standard-library based routing with Go's method-aware ServeMux patterns.
  • Route groups and middleware-only groups.
  • Exact host, subdomain, and wildcard subdomain routing.
  • Named routes with reverse path and URL generation.
  • Mounted routers with named route, route walk, and OpenAPI metadata propagation.
  • Route walking and route table diagnostics.
  • Static file and single-file serving.
  • Custom status handlers.
  • Optional trailing slash redirects.
  • OpenAPI metadata and schema helpers.
  • JSON request/response helpers.
  • Path parameter helper functions.
  • Bundled middleware for request IDs, logging, recovery, timeouts, security headers, CORS, real IP, content length, and timing.
  • Registration freezes after the first request to avoid runtime mutation races.

Install

go get github.com/donseba/go-router

go-router targets modern Go and uses the standard library routing improvements introduced in Go 1.22.

Quick Start

package main

import (
    "fmt"
    "log"
    "net/http"
    "time"

    "github.com/donseba/go-router"
    "github.com/donseba/go-router/middleware"
)

func main() {
    r := router.New(http.NewServeMux(), "Example API", "1.0.0")

    r.Use(middleware.RequestID)
    r.Use(middleware.Logger())
    r.Use(middleware.Recover)
    r.Use(middleware.Timeout(10 * time.Second))

    r.Get("/", func(w http.ResponseWriter, req *http.Request) {
        _, _ = fmt.Fprintln(w, "hello")
    }).As("home")

    r.Get("/users/{id}", func(w http.ResponseWriter, req *http.Request) {
        id, err := router.IntParam(req, "id")
        if err != nil {
            _ = router.BadRequest(w, err)
            return
        }

        _ = router.JSON(w, http.StatusOK, map[string]any{
            "id": id,
        })
    }).As("users.show")

    log.Fatal(http.ListenAndServe(":8080", r))
}

Routing

Routes are registered by HTTP method:

r.Get("/users", listUsers)
r.Post("/users", createUser)
r.Get("/users/{id}", showUser)
r.Put("/users/{id}", updateUser)
r.Patch("/users/{id}", patchUser)
r.Delete("/users/{id}", deleteUser)
r.Head("/health", healthHead)
r.Options("/health", healthOptions)

Route patterns use the standard http.ServeMux syntax:

r.Get("/users/{id}", handler)
r.Get("/exact/{$}", handler)
r.Get("/assets/", handler)

Inside handlers, use standard req.PathValue or the small helper functions:

id := req.PathValue("id")

intID, err := router.IntParam(req, "id")

Available helpers:

  • Param
  • IntParam
  • Int64Param
  • BoolParam
  • Float64Param

Error-Returning Registration

The normal registration API panics on duplicate routes or invalid late registration. That is useful during startup because mistakes fail loudly.

For apps that prefer explicit errors, use the Try variants:

route, err := r.TryGet("/users/{id}", showUser)
if err != nil {
    return err
}

if err := route.TryAs("users.show"); err != nil {
    return err
}

Available Try methods:

  • TryGet, TryHead, TryPost, TryPut, TryPatch, TryDelete, TryOptions
  • TryHandle, TryHandleFunc
  • TryMount
  • TryAs

Groups

Use Group to share a path prefix:

r.Group("/api", func(api *router.Router) {
    api.Get("/users", listUsers)
    api.Post("/users", createUser)
})

Middleware added inside a group only applies to routes registered through that group:

r.Group("/admin", func(admin *router.Router) {
    admin.Use(adminOnly)
    admin.Get("/dashboard", dashboard)
})

Use With for middleware-only groups:

r.With(func(private *router.Router) {
    private.Use(requireLogin)
    private.Get("/account", account)
})

Group-level OpenAPI metadata is inherited by child routes:

r.Group("/api", func(api *router.Router) {
    api.UseDocs(router.Docs{
        Tags: []string{"api"},
    })

    api.Get("/users", listUsers, router.Docs{
        Summary: "List users",
    })
})

Host and Subdomain Routing

Scope routes to an exact host:

r.Host("admin.example.com", func(admin *router.Router) {
    admin.Get("/", adminHome)
})

Use Subdomain for named subdomains:

r.Subdomain("app", "example.com", func(app *router.Router) {
    app.Get("/", appHome)
})

Use Subdomain("*", ...) for wildcard subdomains:

r.Subdomain("*", "example.com", func(tenant *router.Router) {
    tenant.Get("/dashboard", tenantDashboard).As("tenant.dashboard")
})

Exact hosts take precedence over wildcard hosts. The apex domain does not match a wildcard subdomain. Unknown hosts fall back to the default router.

Named Routes and URLs

Name a route with As:

r.Get("/users/{id}", showUser).As("users.show")

Generate paths:

path := r.RoutePathWithParams("users.show", map[string]any{
    "id": 123,
})
// "/users/123"

Parameter values are URL-escaped:

r.RoutePathWithParams("files.show", map[string]any{
    "name": "hello world/a",
})
// "/files/hello%20world%2Fa"

Host routes can generate full URLs:

r.Host("admin.example.com", func(admin *router.Router) {
    admin.Get("/users/{id}", showUser).As("admin.users.show")
})

r.RouteURL("admin.users.show", map[string]any{"id": 123}, "https")
// "https://admin.example.com/users/123"

Wildcard subdomain URLs use a subdomain or tenant parameter:

r.RouteURL("tenant.dashboard", map[string]any{
    "subdomain": "acme",
}, "https")
// "https://acme.example.com/dashboard"

Template helpers are available through FuncMap:

tmpl := template.New("page").Funcs(r.FuncMap())

Included template functions:

  • routePath
  • routePathWithParams
  • routeHost
  • routeURL
  • isActiveRoute
  • isActiveRouteExact
  • isActiveRouteContains

Mounting

Mount any http.Handler under a path:

r.Mount("/debug", http.DefaultServeMux)

Mounted *router.Router instances also contribute named routes, walk metadata, and OpenAPI paths/components:

api := router.New(http.NewServeMux(), "API", "1.0.0")
api.Get("/users/{id}", showUser).As("api.users.show")

r.Mount("/api", api)

r.RoutePathWithParams("api.users.show", map[string]any{"id": 123})
// "/api/users/123"

Middleware

Middleware uses the standard shape:

type Middleware func(http.Handler) http.Handler

Register middleware globally:

r.Use(middleware.RequestID)
r.Use(middleware.Logger())
r.Use(middleware.Recover)

The bundled middleware package includes:

  • RequestID
  • Logger
  • Recover
  • Timeout
  • RealIP
  • RealIPWithOptions
  • SecurityHeaders
  • CORS
  • ContentLengthMiddleware
  • Timer

For production proxy deployments, prefer RealIPWithOptions:

r.Use(middleware.RealIPWithOptions(middleware.RealIPOptions{
    TrustedProxies: []string{"127.0.0.1/32", "::1/128"},
}))

RealIP trusts forwarding headers from any client and is mainly a convenience helper.

CORS enforces configured preflight methods and headers:

r.Use(middleware.CORS(middleware.CORSOptions{
    AllowedOrigins: []string{"https://example.com"},
    AllowedMethods: []string{"GET", "POST", "OPTIONS"},
    AllowedHeaders: []string{"Content-Type", "Authorization"},
}))

ContentLengthMiddleware buffers ordinary responses to compute their length. Calling http.NewResponseController(w).Flush() or http.Flusher.Flush() switches to streaming and skips automatic Content-Length. Place handlers that hijack the connection, such as websockets, outside this middleware.

JSON Helpers

For small JSON APIs:

type CreateUser struct {
    Name string `json:"name"`
}

func createUser(w http.ResponseWriter, req *http.Request) {
    var input CreateUser
    if err := router.DecodeJSON(req, &input); err != nil {
        _ = router.BadRequest(w, err)
        return
    }

    _ = router.JSON(w, http.StatusCreated, input)
}

Helpers:

  • DecodeJSON
  • JSON
  • Error
  • BadRequest
  • InternalServerError
  • MessageError

Static Files

Serve a directory:

r.ServeFiles("/static/", http.Dir("./static"))

Serve one file:

r.ServeFile("/favicon.ico", "./static/favicon.ico")

Static files work inside groups and host routers:

r.Host("cdn.example.com", func(cdn *router.Router) {
    cdn.ServeFiles("/assets", http.Dir("./assets"))
})

Custom Status Handlers

Register custom handlers for status codes emitted by the underlying router:

r.HandleStatus(http.StatusNotFound, notFound)
r.HandleStatus(http.StatusMethodNotAllowed, methodNotAllowed)

Custom status handling uses an intercepting response writer. The no-custom-status path is optimized and allocation-free in the router benchmark.

Trailing Slashes

Trailing slash redirects are off by default:

r.RedirectTrailingSlash(true)

Groups and hosts can set their own trailing slash policy:

r.Group("/admin", func(admin *router.Router) {
    admin.RedirectTrailingSlash(true)
})

Route Walking and Diagnostics

Use Walk to inspect registered routes:

err := r.Walk(func(route router.RouteInfo) error {
    log.Printf("%s %s %s %s", route.Host, route.Method, route.Path, route.Name)
    log.Printf("handler: %T middleware: %d", route.Handler, len(route.Middlewares))
    return nil
})

Or print a route table:

fmt.Print(r.RouteTable())

Duplicate route names and duplicate method/path/host registrations fail during registration.

OpenAPI

Enable OpenAPI docs:

r.UseOpenapiDocs(true)

Attach docs to routes:

r.Get("/users/{id}", showUser, router.Docs{
    Tags:    []string{"users"},
    Summary: "Show user",
    Out: map[string]router.DocOut{
        "200": {
            ApplicationType: "application/json",
            Description:     "OK",
            Object:          User{},
        },
    },
})

Access the document:

doc := r.OpenAPI()

Supported methods:

  • GET
  • HEAD
  • POST
  • PUT
  • PATCH
  • DELETE
  • OPTIONS

Schema generation supports:

  • JSON field names and ignored fields
  • nested structs
  • embedded structs
  • slices and arrays
  • maps via additionalProperties
  • pointers as nullable
  • time.Time as date-time
  • format tags
  • enum tags such as enum:"admin|user"
  • required fields from validate:"required", binding:"required", or required:"true"

OpenAPI support is useful, but still intentionally lightweight. For highly detailed API specs, you may still want explicit docs or schema overrides in your application.

Production Notes

The router is intended to be configured during startup. After the first request is served, registration freezes and later mutation panics or returns an error through the Try APIs.

Recommended production defaults:

r.Use(middleware.RequestID)
r.Use(middleware.RealIPWithOptions(middleware.RealIPOptions{
    TrustedProxies: []string{"127.0.0.1/32", "::1/128"},
}))
r.Use(middleware.Logger())
r.Use(middleware.Recover)
r.Use(middleware.Timeout(10 * time.Second))
r.Use(middleware.SecurityHeaders())

Before shipping an app:

  • Register routes only during startup.
  • Prefer Try* registration if you want explicit bootstrap errors.
  • Use RealIPWithOptions behind proxies.
  • Explicitly flush streaming responses and use middleware that supports flushing.
  • Run go test ./..., go test -race ./..., and go vet ./....
  • Add app-level tests for mounted routers, subdomains, and custom middleware.

See PRODUCTION.md for the current hardening checklist.

Benchmarks

The router has a direct benchmark against raw http.ServeMux using the same route set and a minimal response writer.

Recent local result:

BenchmarkRouterVsServeMuxRouter  280271 ns/op   0 B/op   0 allocs/op
BenchmarkRouterVsServeMuxStdlib  260223 ns/op   0 B/op   0 allocs/op

In that benchmark each operation serves 2000 requests, so the hot path is roughly:

go-router: ~140 ns/request
ServeMux:  ~130 ns/request

Benchmark numbers vary by machine. Run them locally with:

go test -run ^$ -bench . -benchmem

Examples

  • example/simple
  • example/openapi
  • example/production

Status

This project is suitable for controlled production use in your own applications, especially websites, internal tools, SaaS-style apps, and APIs where you own the route patterns and rollout.

It is not yet as battle-tested as mature routers like chi. If you use it broadly, keep tests close to your app, run race tests, and harden based on real production behavior.

License

MIT. See LICENSE.

Documentation

Index

Constants

View Source
const HeaderFlagDoNotIntercept = "do_not_intercept"

Variables

View Source
var (
	DefaultRedirectTrailingSlash = false
	DefaultRedirectStatusCode    = http.StatusTemporaryRedirect // or http.StatusMovedPermanently
	DefaultUseOpenapiDocs        = false
	OpenApiVersion               = "3.0.1"
)

Functions

func BadRequest added in v0.9.0

func BadRequest(w http.ResponseWriter, err error) error

func BoolParam added in v0.9.0

func BoolParam(r *http.Request, name string) (bool, error)

func DecodeJSON added in v0.9.0

func DecodeJSON(r *http.Request, v any) error

func Error added in v0.9.0

func Error(w http.ResponseWriter, statusCode int, err error) error

func Float64Param added in v0.9.0

func Float64Param(r *http.Request, name string) (float64, error)

func Int64Param added in v0.9.0

func Int64Param(r *http.Request, name string) (int64, error)

func IntParam added in v0.9.0

func IntParam(r *http.Request, name string) (int, error)

func InternalServerError added in v0.9.0

func InternalServerError(w http.ResponseWriter, err error) error

func JSON added in v0.9.0

func JSON(w http.ResponseWriter, statusCode int, v any) error

func MessageError added in v0.9.0

func MessageError(message string) error

func Param added in v0.9.0

func Param(r *http.Request, name string) string

Types

type Components

type Components struct {
	Schemas         map[string]Schema         `json:"schemas,omitempty"`         // Reusable schemas
	SecuritySchemes map[string]SecurityScheme `json:"securitySchemes,omitempty"` // Security schemes
}

Components holds reusable components such as schemas and security schemes.

type DocIn

type DocIn struct {
	Object   any
	Required bool
}

type DocOut

type DocOut struct {
	ApplicationType string
	Description     string
	Object          any
}

type Docs

type Docs struct {
	Tags        []string              // Tags for the operation
	Summary     string                // Short summary of the operation
	Description string                // Operation description
	Parameters  []Parameter           // Parameters for the operation
	RequestBody *RequestBody          // Request body for the operation
	Responses   map[string]Response   // Expected responses
	Security    []map[string][]string // Security requirements

	In  map[string]DocIn
	Out map[string]DocOut
}

type Info

type Info struct {
	Title       string `json:"title" validate:"required"`   // API title
	Description string `json:"description,omitempty"`       // API description
	Version     string `json:"version" validate:"required"` // API version
}

Info represents the API metadata.

type MediaType

type MediaType struct {
	Schema *Schema `json:"schema,omitempty"` // Schema describing the type
}

MediaType represents the media type of a request or response body.

type Middleware

type Middleware func(http.Handler) http.Handler

type OpenAPI

type OpenAPI struct {
	Openapi    string                `json:"openapi" validate:"required"` // OpenAPI version (e.g., "3.0.1")
	Info       Info                  `json:"info" validate:"required"`    // API information
	Servers    []Server              `json:"servers,omitempty"`           // Server details
	Paths      map[string]PathItem   `json:"paths" validate:"required"`   // Paths and operations
	Components Components            `json:"components,omitempty"`        // Components such as schemas and security schemes
	Security   []map[string][]string `json:"security,omitempty"`          // Global security settings
	Tags       []Tag                 `json:"tags,omitempty"`              // Tags for API organization
}

OpenAPI represents the root OpenAPI document.

type Operation

type Operation struct {
	Tags        []string              `json:"tags,omitempty"`                // Tags for the operation
	Summary     string                `json:"summary,omitempty"`             // Short summary of the operation
	Description string                `json:"description,omitempty"`         // Operation description
	OperationID string                `json:"operationId,omitempty"`         // Unique operation ID
	Parameters  []Parameter           `json:"parameters,omitempty"`          // Parameters for the operation
	RequestBody *RequestBody          `json:"requestBody,omitempty"`         // Request body for the operation
	Responses   map[string]Response   `json:"responses" validate:"required"` // Expected responses
	Security    []map[string][]string `json:"security,omitempty"`            // Security requirements
}

Operation describes a single API operation on a path.

type Parameter

type Parameter struct {
	Name        string  `json:"name" validate:"required"` // Parameter name
	In          string  `json:"in" validate:"required"`   // Location (e.g., "query", "header", "path")
	Description string  `json:"description,omitempty"`    // Parameter description
	Required    bool    `json:"required,omitempty"`       // Is parameter required?
	Schema      *Schema `json:"schema,omitempty"`         // Schema defining the type
}

Parameter represents a single parameter for an operation.

type PathItem

type PathItem struct {
	Get     *Operation `json:"get,omitempty"`     // GET operation
	Head    *Operation `json:"head,omitempty"`    // HEAD operation
	Post    *Operation `json:"post,omitempty"`    // POST operation
	Put     *Operation `json:"put,omitempty"`     // PUT operation
	Delete  *Operation `json:"delete,omitempty"`  // DELETE operation
	Patch   *Operation `json:"patch,omitempty"`   // PATCH operation
	Options *Operation `json:"options,omitempty"` // OPTIONS operation
}

PathItem describes the operations available on a single path.

func (PathItem) Methods

func (p PathItem) Methods() []string

func (PathItem) SetMethod

func (p PathItem) SetMethod(method string, operation *Operation) PathItem

type RequestBody

type RequestBody struct {
	Description string               `json:"description,omitempty"` // Request body description
	Content     map[string]MediaType `json:"content"`               // Media types supported by the request
	Required    bool                 `json:"required,omitempty"`    // Is request body required?
}

RequestBody represents a request body for an operation.

type Response

type Response struct {
	Description string               `json:"description" validate:"required"` // Response description
	Content     map[string]MediaType `json:"content,omitempty"`               // Media types produced by the response
}

Response describes a single response from an API operation.

type RouteError added in v0.9.0

type RouteError struct {
	Err any
}

func (RouteError) Error added in v0.9.0

func (e RouteError) Error() string

type RouteInfo added in v0.9.0

type RouteInfo struct {
	Method      string
	Path        string
	Host        string
	Name        string
	Handler     http.Handler
	Middlewares []Middleware
}

type RouteRegistration added in v0.9.0

type RouteRegistration struct {
	// contains filtered or unexported fields
}

func (*RouteRegistration) As added in v0.9.0

func (rr *RouteRegistration) As(name string)

func (*RouteRegistration) TryAs added in v0.9.0

func (rr *RouteRegistration) TryAs(name string) (err error)

type Router

type Router struct {
	// contains filtered or unexported fields
}

func New

func New(ht *http.ServeMux, title string, version string) *Router

func (*Router) AddServerEndpoint

func (r *Router) AddServerEndpoint(url string, description string)

func (*Router) Delete

func (r *Router) Delete(pattern string, handler http.HandlerFunc, doc ...Docs) *RouteRegistration

func (*Router) FuncMap added in v0.9.0

func (r *Router) FuncMap() map[string]any

func (*Router) Get

func (r *Router) Get(pattern string, handler http.HandlerFunc, doc ...Docs) *RouteRegistration

func (*Router) Group

func (r *Router) Group(basePath string, fn func(*Router))

func (*Router) Handle added in v0.9.0

func (r *Router) Handle(pattern string, handler http.Handler)

func (*Router) HandleFunc added in v0.9.0

func (r *Router) HandleFunc(pattern string, handler http.HandlerFunc)

func (*Router) HandleStatus added in v0.2.0

func (r *Router) HandleStatus(httpStatus int, handler http.HandlerFunc)

func (*Router) Head

func (r *Router) Head(pattern string, handler http.HandlerFunc, doc ...Docs) *RouteRegistration

func (*Router) Host added in v0.9.0

func (r *Router) Host(hostPattern string, fn func(*Router))

func (*Router) Mount added in v0.9.0

func (r *Router) Mount(pattern string, handler http.Handler)

func (*Router) OpenAPI

func (r *Router) OpenAPI() *OpenAPI

OpenAPI returns the root documentation tree

func (*Router) OperationID

func (r *Router) OperationID(s string) string

func (*Router) Options added in v0.9.0

func (r *Router) Options(pattern string, handler http.HandlerFunc, doc ...Docs) *RouteRegistration

func (*Router) Patch

func (r *Router) Patch(pattern string, handler http.HandlerFunc, doc ...Docs) *RouteRegistration

func (*Router) Post

func (r *Router) Post(pattern string, handler http.HandlerFunc, doc ...Docs) *RouteRegistration

func (*Router) Put

func (r *Router) Put(pattern string, handler http.HandlerFunc, doc ...Docs) *RouteRegistration

func (*Router) RedirectTrailingSlash

func (r *Router) RedirectTrailingSlash(redirect bool)

func (*Router) RouteHost added in v0.9.0

func (r *Router) RouteHost(name string) string

func (*Router) RoutePath added in v0.9.0

func (r *Router) RoutePath(name string) string

func (*Router) RoutePathWithParams added in v0.9.0

func (r *Router) RoutePathWithParams(name string, params map[string]any) string

func (*Router) RouteTable added in v0.9.0

func (r *Router) RouteTable() string

func (*Router) RouteURL added in v0.9.0

func (r *Router) RouteURL(name string, params map[string]any, scheme string) string

func (*Router) Routes added in v0.9.0

func (r *Router) Routes() map[string]RouteInfo

func (*Router) ServeFile

func (r *Router) ServeFile(pattern string, filepath string)

func (*Router) ServeFiles

func (r *Router) ServeFiles(pattern string, fs http.FileSystem)

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*Router) Subdomain added in v0.9.0

func (r *Router) Subdomain(subdomain string, domain string, fn func(*Router))

func (*Router) TryDelete added in v0.9.0

func (r *Router) TryDelete(pattern string, handler http.HandlerFunc, doc ...Docs) (*RouteRegistration, error)

func (*Router) TryGet added in v0.9.0

func (r *Router) TryGet(pattern string, handler http.HandlerFunc, doc ...Docs) (*RouteRegistration, error)

func (*Router) TryHandle added in v0.9.0

func (r *Router) TryHandle(pattern string, handler http.Handler) (err error)

func (*Router) TryHandleFunc added in v0.9.0

func (r *Router) TryHandleFunc(pattern string, handler http.HandlerFunc) error

func (*Router) TryHead added in v0.9.0

func (r *Router) TryHead(pattern string, handler http.HandlerFunc, doc ...Docs) (*RouteRegistration, error)

func (*Router) TryMount added in v0.9.0

func (r *Router) TryMount(pattern string, handler http.Handler) (err error)

func (*Router) TryOptions added in v0.9.0

func (r *Router) TryOptions(pattern string, handler http.HandlerFunc, doc ...Docs) (*RouteRegistration, error)

func (*Router) TryPatch added in v0.9.0

func (r *Router) TryPatch(pattern string, handler http.HandlerFunc, doc ...Docs) (*RouteRegistration, error)

func (*Router) TryPost added in v0.9.0

func (r *Router) TryPost(pattern string, handler http.HandlerFunc, doc ...Docs) (*RouteRegistration, error)

func (*Router) TryPut added in v0.9.0

func (r *Router) TryPut(pattern string, handler http.HandlerFunc, doc ...Docs) (*RouteRegistration, error)

func (*Router) Use

func (r *Router) Use(middleware Middleware)

func (*Router) UseDocs added in v0.9.0

func (r *Router) UseDocs(doc Docs)

func (*Router) UseOpenapiDocs

func (r *Router) UseOpenapiDocs(use bool)

func (*Router) Walk added in v0.9.0

func (r *Router) Walk(fn WalkFunc) error

func (*Router) WildcardSubdomain added in v0.9.0

func (r *Router) WildcardSubdomain(domain string, fn func(*Router))

func (*Router) With added in v0.9.0

func (r *Router) With(fn func(*Router))

func (*Router) WriteRouteTable added in v0.9.0

func (r *Router) WriteRouteTable(w io.Writer) error

type Schema

type Schema struct {
	Ref                  string            `json:"$ref,omitempty"`                 // Reference to a schema
	Type                 string            `json:"type,omitempty"`                 // Data type (e.g., "string", "object")
	Format               string            `json:"format,omitempty"`               // Data format (e.g., "uuid", "email")
	Properties           map[string]Schema `json:"properties,omitempty"`           // Properties of the object
	Items                *Schema           `json:"items,omitempty"`                // Schema for array items
	AdditionalProperties *Schema           `json:"additionalProperties,omitempty"` // Schema for map values
	Required             []string          `json:"required,omitempty"`             // Required properties
	Enum                 []any             `json:"enum,omitempty"`                 // Allowed values
	Nullable             bool              `json:"nullable,omitempty"`             // Whether the value can be null
}

Schema represents the structure of a request or response body.

type SecurityScheme

type SecurityScheme struct {
	Type         string `json:"type" validate:"required"` // Security scheme type (e.g., "http", "apiKey")
	Scheme       string `json:"scheme,omitempty"`         // HTTP Authorization scheme (e.g., "bearer")
	BearerFormat string `json:"bearerFormat,omitempty"`   // Bearer token format
}

SecurityScheme defines a security scheme for the API.

type Server

type Server struct {
	URL         string            `json:"url" validate:"required"` // Server URL
	Description string            `json:"description,omitempty"`   // Server description
	Variables   map[string]string `json:"variables,omitempty"`     // Variables for URL template
}

Server represents an API server.

type Tag

type Tag struct {
	Name        string `json:"name" validate:"required"` // Tag name
	Description string `json:"description,omitempty"`    // Tag description
}

Tag represents a tag for an API operation.

type WalkFunc added in v0.9.0

type WalkFunc func(RouteInfo) error

Directories

Path Synopsis
example
openapi command
production command
simple command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL