openapi

package
v0.1.5 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Bind

func Bind(r *http.Request, v interface{}) error

func BuildSpec

func BuildSpec(routes []RouteMeta, cfg Config) *openapi3.T

BuildSpec builds an OpenAPI document from captured routes and config.

func JSON

func JSON(w http.ResponseWriter, code int, v interface{})

func MultipartSchema

func MultipartSchema(fileField string, fields ...MultipartField) *openapi3.SchemaRef

MultipartSchema returns a schema sample that produces a multipart/form-data request body.

This returns an *openapi3.SchemaRef directly so we can accurately represent: - file as type=string, format=binary - primitive fields as string/integer/number/boolean - required fields

It is designed for use with the oas builder:

s.POST("/upload").Req(openapi.MultipartSchema("file", openapi.MultipartField{Name: "note"})).Res(...)

func PathValue

func PathValue(r *http.Request, key string) string

func QueryValue

func QueryValue[T any](r *http.Request, name string) (T, bool, error)

QueryValue reads a query parameter from URL and parses it into the requested type.

func QueryValues

func QueryValues[T any](r *http.Request, name string) ([]T, bool, error)

QueryValues reads repeated query params (?id=1&id=2) and parses into []T.

func Register

func Register(r *Router, cfg Config)

Types

type Config

type Config struct {
	Title           string
	Version         string
	Description     string
	SecuritySchemes map[string]*openapi3.SecuritySchemeRef
	Tags            openapi3.Tags
	SpecPath        string
	SwaggerPath     string

	// Schemas registers component schemas by name without attaching them to a route.
	// Useful when you want config-only schema registration.
	Schemas SchemaRegistry

	// DefaultErrorResponses controls which standard error responses are automatically
	// added to every operation (if not already declared).
	//
	// If nil, a sensible default set is used.
	// If empty (len==0), automatic error responses are disabled.
	DefaultErrorResponses []int

	// DefaultErrorSchema is the schema used for DefaultErrorResponses.
	// If nil, openapi.ErrorResponse{} is used.
	DefaultErrorSchema any
}

type ErrorResponse

type ErrorResponse struct {
	Error string `json:"error"`
}

ErrorResponse is the default error schema used when you don't provide explicit response specs via WithResponses.

You can override/replace this by declaring your own responses with WithResponses(...) on a route.

type Group

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

Group allows applying shared options (e.g., WithTags) and a common path prefix to multiple routes.

Example:

api := r.Group("", WithTags("Users"))
api.GET("/users", ...)

Options provided to the group are applied to every route in that group, and can be overridden/extended by per-route options.

Path joining is kept oas and consistent with common router behavior. We avoid cleaning ":" or "{}" segments; NormalizePath handles OpenAPI normalization.

func NewGroup added in v0.1.5

func NewGroup(prefix string, opts []HandlerOption, route func(method, path string, h http.HandlerFunc, opts ...HandlerOption)) *Group

NewGroup constructs a Group with the provided prefix, options and a custom route function. Useful for adapters or wrappers that need the group's routing to call a specific handler registration function (for examples, oas.Router wants to ensure route registrations go through its Handle method so spec injection happens correctly).

func (*Group) DELETE

func (g *Group) DELETE(p string, h http.HandlerFunc, opts ...HandlerOption)

func (*Group) GET

func (g *Group) GET(p string, h http.HandlerFunc, opts ...HandlerOption)

func (*Group) Handle

func (g *Group) Handle(method, p string, h http.HandlerFunc, opts ...HandlerOption)

func (*Group) PATCH

func (g *Group) PATCH(p string, h http.HandlerFunc, opts ...HandlerOption)

func (*Group) POST

func (g *Group) POST(p string, h http.HandlerFunc, opts ...HandlerOption)

func (*Group) PUT

func (g *Group) PUT(p string, h http.HandlerFunc, opts ...HandlerOption)

type HandlerOption

type HandlerOption func(*RouteMeta)

HandlerOption configures RouteMeta.

func JSONRoute

func JSONRoute(reqSchema any, resSchema any, successStatus int) []HandlerOption

JSONRoute JSONRouteSpec is a convenience for common JSON APIs. It wires request/response schemas + a primary success status code.

You still can override everything by passing explicit options.

Typical usage from adapters:

r.POST("/users", h, openapi.JSONRoute(CreateUser{}, struct{}{}, http.StatusCreated)...)

func MergeOptionSlices

func MergeOptionSlices(slices ...[]HandlerOption) []HandlerOption

MergeOptionSlices merges multiple slices, returning a new slice.

func MergeOptions

func MergeOptions(base []HandlerOption, add ...HandlerOption) []HandlerOption

MergeOptions merges a base option slice with additional options, returning a new slice (doesn't mutate base).

func WithHeaderParams

func WithHeaderParams(params ...HeaderParam) HandlerOption

WithHeaderParams declares header parameters for a route for OpenAPI generation.

func WithPathParam

func WithPathParam(name string, typ ParamType, required bool, description string) HandlerOption

WithPathParam declares a typed path parameter (name + primitive type) for OpenAPI generation.

func WithQueryParams

func WithQueryParams(params ...QueryParam) HandlerOption

WithQueryParams declares query parameters for a route for OpenAPI generation.

func WithRequestSchema

func WithRequestSchema(schema interface{}) HandlerOption

func WithResponseSchema

func WithResponseSchema(schema interface{}) HandlerOption

func WithResponses

func WithResponses(responses ...ResponseSpec) HandlerOption

WithResponses adds/overrides response entries for a route.

func WithSecurity

func WithSecurity(security *openapi3.SecurityRequirement) HandlerOption

func WithTags

func WithTags(tags ...string) HandlerOption

type HeaderParam

type HeaderParam struct {
	Name        string
	Type        ParamType
	Required    bool
	Description string
}

HeaderParam describes a header parameter for OpenAPI generation.

type MultipartField

type MultipartField struct {
	Name        string
	Type        ParamType
	Required    bool
	Description string
}

MultipartField defines an extra multipart/form-data field (besides the file).

Type controls the primitive type for that field in the OpenAPI schema. If omitted/unknown, it defaults to string.

NOTE: multipart/form-data fields are represented as properties on an object schema.

type MultipartFile

type MultipartFile struct{}

MultipartFile is a marker type for OpenAPI generation.

Use it inside a request schema struct to document multipart/form-data uploads. Example:

type UploadReq struct {
	File MultipartFile `json:"file"`
	Note string       `json:"note"`
}

When used with WithRequestSchema(UploadReq{}), the builder will render the request body as multipart/form-data with a binary file part.

At runtime you still parse files using your framework (r.FormFile, c.FormFile, etc). This type is only for spec generation.

type ParamType

type ParamType string

ParamType represents a primitive type used for path/query parameters.

const (
	ParamString  ParamType = "string"
	ParamInteger ParamType = "integer"
	ParamNumber  ParamType = "number"
	ParamBoolean ParamType = "boolean"
)

type PathParamSpec

type PathParamSpec struct {
	Name        string
	Type        ParamType
	Required    bool
	Description string
}

type QueryParam

type QueryParam struct {
	Name        string
	Type        ParamType
	Required    bool
	Description string
}

QueryParam describes a query parameter for OpenAPI generation.

type Registry

type Registry struct{}

Registry is reserved for future: merge routes across multiple routers/adapters. Today, Router stores routes in-memory and BuildSpec consumes them.

type ResponseSpec

type ResponseSpec struct {
	Status      int
	Description string
	Schema      interface{}
}

ResponseSpec declares an OpenAPI response for a specific status code.

Schema can be nil to indicate an empty body. Description is optional; if empty we'll use http.StatusText(code) where possible.

Example:

WithResponses(
  ResponseSpec{Status: 200, Schema: User{}, Description: "OK"},
  ResponseSpec{Status: 401, Schema: ErrorResponse{}, Description: "Unauthorized"},
)

type RouteMeta

type RouteMeta struct {
	Method         string
	Path           string
	Handler        http.HandlerFunc
	Summary        string
	Description    string
	Tags           []string
	RequestSchema  interface{}
	ResponseSchema interface{}
	Responses      []ResponseSpec
	Security       *openapi3.SecurityRequirement
	QueryParams    []QueryParam
	HeaderParams   []HeaderParam
	PathParams     []PathParamSpec
}

type Router

type Router struct {
	Mux *httpMux
	// contains filtered or unexported fields
}

Router uses a small net/http-backed mux that understands oas path params of the form /users/{id}. This avoids depending on chi while preserving behavior needed by the OpenAPI builder (path param extraction via context).

func NewRouter

func NewRouter() *Router

func (*Router) DELETE

func (r *Router) DELETE(path string, h http.HandlerFunc, opts ...HandlerOption)

func (*Router) GET

func (r *Router) GET(path string, h http.HandlerFunc, opts ...HandlerOption)

func (*Router) Get

func (r *Router) Get(path string, h http.HandlerFunc)

Get registers a plain GET handler (used by Swagger UI mount helpers).

func (*Router) Group

func (r *Router) Group(prefix string, opts ...HandlerOption) *Group

func (*Router) HEAD

func (r *Router) HEAD(path string, h http.HandlerFunc, opts ...HandlerOption)

func (*Router) Handle

func (r *Router) Handle(method, path string, h http.HandlerFunc, opts ...HandlerOption)

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, h http.HandlerFunc, opts ...HandlerOption)

func (*Router) PATCH

func (r *Router) PATCH(path string, h http.HandlerFunc, opts ...HandlerOption)

func (*Router) POST

func (r *Router) POST(path string, h http.HandlerFunc, opts ...HandlerOption)

func (*Router) PUT

func (r *Router) PUT(path string, h http.HandlerFunc, opts ...HandlerOption)

func (*Router) Routes

func (r *Router) Routes() []RouteMeta

func (*Router) ServeHTTP

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

type SchemaRegistry

type SchemaRegistry map[string]any

SchemaRegistry allows registering types that should appear in OpenAPI components/schemas without having to attach them to a specific route.

This is the closest Go equivalent of “Spring Boot config-only” schema registration. It does NOT automatically infer which route uses which schema; it only ensures schemas exist in components for references and tooling.

If you want per-route request/response schemas, keep using JSONRoute(...) or WithRequestSchema/WithResponseSchema on that route.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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