spec

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: MIT Imports: 14 Imported by: 22

README

oaswrap/spec

CI codecov Go Reference Go Report Card Go Version License

Code-first, framework-agnostic OpenAPI 3.x spec builder for Go. Generate docs from route registrations and Go structs — no annotations, no vendor lock-in.


Why oaswrap/spec?

  • Native OpenAPI builder — paths, operations, components, validation, and schema reflection are all implemented in this repository without third-party OpenAPI dependencies.
  • Framework-agnostic core — use spec.NewRouter for static generation, or drop in adapters for Chi, Echo, Gin, Fiber, net/http, and Mux.
  • Code-first route documentation — register routes and their documentation together using Go functions and typed options.
  • Version-aware output — defaults to OpenAPI 3.1.2, with full support for 3.0.x and 3.2.0 features when selected.
  • Direct model escape hatches — use typed openapi structs, Extensions for x-* fields, and Extra for official or future fields not yet wrapped by a helper option.
  • Deterministic output — generated documents are stable enough for golden-file snapshot tests and CI documentation checks.

Features

  • JSON and YAML generation.
  • Framework-agnostic route registration with NewRouter, groups, route builders, and HTTP method helpers.
  • Webhook registration helpers for OpenAPI 3.1.x and 3.2.0.
  • OpenAPI 3.2.0 QUERY method and additional operation support.
  • Request and response schema reflection from Go structs.
  • Parameter reflection from path, query, header, cookie, and OpenAPI 3.2.0 querystring tags.
  • JSON Schema/OpenAPI schema tags for examples, enums, constraints, nullability, read/write flags, content metadata, and XML metadata.
  • Security helpers for API key, HTTP bearer/basic-style schemes, OAuth2, OpenID Connect, and mutual TLS.
  • Duplicate response merging into oneOf.
  • Low-level typed OpenAPI model for direct field control.
  • spec.OneOf for explicit one-of schemas.
  • SchemaExposer and StaticSchemaExposer hooks for custom reflected schemas.
  • InterceptSchema hook for type-level schema customization and override.
  • InterceptProp hook for field-level property filtering and modification.
  • RequiredPropByValidateTag option to derive required from validate struct tags.
  • encoding.TextMarshaler/TextUnmarshaler types automatically reflected as type: string.
  • EmbedReferencer interface and refer:"true" tag for embedded struct allOf $ref instead of field inlining.

Installation

Requirements:

  • Go 1.22+
go get -u github.com/oaswrap/spec

Quick Start

package main

import (
	"log"

	"github.com/oaswrap/spec"
	"github.com/oaswrap/spec/openapi"
	"github.com/oaswrap/spec/option"
)

func main() {
	r := spec.NewRouter(
		option.WithOpenAPIVersion(openapi.Version320),
		option.WithTitle("Users API"),
		option.WithVersion("1.0.0"),
		option.WithServer("https://api.example.com"),
		option.WithSecurity("bearerAuth", option.SecurityHTTPBearer("bearer")),
	)

	v1 := r.Group("/api/v1", option.GroupTags("users"))
	v1.Post("/login",
		option.Summary("Login"),
		option.Request(new(LoginRequest)),
		option.Response(200, new(LoginResponse)),
	)
	v1.Get("/users/{id}",
		option.Summary("Get user"),
		option.Request(new(GetUserRequest)),
		option.Response(200, new(User)),
	)

	if err := r.WriteSchemaTo("openapi.yaml"); err != nil {
		log.Fatal(err)
	}
}

type LoginRequest struct {
	Username string `json:"username" required:"true"`
	Password string `json:"password" required:"true" writeOnly:"true"`
}

type LoginResponse struct {
	Token string `json:"token" required:"true"`
}

type GetUserRequest struct {
	ID string `path:"id" required:"true" description:"User identifier"`
}

type User struct {
	ID   string `json:"id" required:"true"`
	Name string `json:"name"`
}

Output

spec.NewRouter and spec.NewGenerator expose the following output methods:

Method Description
GenerateSchema() Defaults to YAML.
GenerateSchema("yaml") / GenerateSchema("yml") Returns YAML.
GenerateSchema("json") Returns pretty-printed JSON.
MarshalYAML() Validates and serializes YAML.
MarshalJSON() Validates and serializes pretty-printed JSON.
WriteSchemaTo("openapi.yaml") Infers format from file extension (.yaml, .yml, .json).
Document() Returns the built *openapi.Document.
Validate() Builds the document and checks OpenAPI invariants. Returns only SeverityError findings.
ValidateReport() Builds and validates, returning all findings including warnings and info as ValidationErrors.
Config() Returns the effective OpenAPI configuration.

Framework Adapters

Use the core spec package for static generation and CI workflows. Use an adapter when you want route registration, spec generation, and docs UI wiring in a single framework-specific router.

Framework Package
Chi chiopenapi
Echo v4 echoopenapi
Echo v5 echov5openapi
Fiber v2 fiberopenapi
Fiber v3 fiberv3openapi
Gin ginopenapi
Iris irisopenapi
net/http httpopenapi
Mux muxopenapi

Adapter module import paths:

  • github.com/oaswrap/spec/adapter/chiopenapi
  • github.com/oaswrap/spec/adapter/echoopenapi
  • github.com/oaswrap/spec/adapter/echov5openapi
  • github.com/oaswrap/spec/adapter/fiberopenapi
  • github.com/oaswrap/spec/adapter/fiberv3openapi
  • github.com/oaswrap/spec/adapter/ginopenapi
  • github.com/oaswrap/spec/adapter/irisopenapi
  • github.com/oaswrap/spec/adapter/httpopenapi
  • github.com/oaswrap/spec/adapter/muxopenapi

OpenAPI Options

Root options are passed to spec.NewRouter or spec.NewGenerator.

r := spec.NewRouter(
	option.WithOpenAPIVersion(openapi.Version312),
	option.WithTitle("Payments API"),
	option.WithInfoSummary("Payments API"),
	option.WithVersion("1.4.0"),
	option.WithDescription("Payment operations."),
	option.WithTermsOfService("https://example.com/terms"),
	option.WithContact(openapi.Contact{Name: "API Team", Email: "api@example.com"}),
	option.WithLicense(openapi.License{Name: "Apache 2.0", URL: "https://www.apache.org/licenses/LICENSE-2.0.html"}),
	option.WithExternalDocs("https://docs.example.com", "Full documentation"),
	option.WithServer("https://api.example.com", option.ServerDescription("Production")),
	option.WithTag("payments", option.TagDescription("Payment operations")),
	option.WithStripTrailingSlash(),
)
Option Purpose
WithOpenAPIConfig(opts...) Build an *openapi.Config with defaults and apply options.
WithOpenAPIVersion(version) Set openapi; default is openapi.Version312. Constants are available for 3.0.03.0.4, 3.1.03.1.2, and 3.2.0.
WithSelf(uri) Set OpenAPI 3.2.0 $self.
WithJSONSchemaDialect(uri) Set root jsonSchemaDialect.
WithTitle(title) Set info.title.
WithInfoSummary(summary) Set info.summary.
WithVersion(version) Set info.version.
WithDescription(description) Set info.description.
WithContact(contact) Set info.contact.
WithLicense(license) Set info.license.
WithTermsOfService(url) Set info.termsOfService.
WithTags(tags...) Add root tags from openapi.Tag values.
WithTag(name, tagOpts...) Add one root tag without constructing openapi.Tag manually.
WithServer(url, opts...) Add a root server.
WithExternalDocs(url, description...) Set root externalDocs.
WithSecurity(name, opts...) Add a reusable security scheme.
WithGlobalSecurity(name, scopes...) Add a root security requirement.
WithReflectorConfig(opts...) Configure schema reflection.
WithStripTrailingSlash(strip...) Trim trailing slashes from operation paths except /.
WithPathParser(parser) Convert framework-style paths, e.g. :id{id}.
WithDocument(fn) Mutate the final low-level document before validation and serialization.
WithComponentSchema(name, schema) Register a reusable schema component.
WithComponentResponse(name, response) Register a reusable response component.
WithComponentParameter(name, parameter) Register a reusable parameter component.
WithComponentExample(name, example) Register a reusable example component.
WithComponentRequestBody(name, requestBody) Register a reusable request body component.
WithComponentHeader(name, header) Register a reusable header component.
WithComponentSecurityScheme(name, scheme) Register a reusable security scheme component.
WithComponentLink(name, link) Register a reusable link component.
WithComponentCallback(name, callback) Register a reusable callback component.
WithComponentPathItem(name, pathItem) Register a reusable path item component.
WithComponentMediaType(name, mediaType) Register a reusable media type component (OpenAPI 3.2.0).
WithDisableDocs(disable...) Disable adapter docs endpoints.
WithDocsPath(path) Set adapter docs UI path.
WithSpecPath(path) Set adapter OpenAPI spec path.
WithCacheAge(cacheAge) Set docs/spec cache age.
WithUIOption(opt) Set a low-level spec-ui option.
WithSwaggerUI(cfg...) Use Swagger UI.
WithStoplightElements(cfg...) Use Stoplight Elements.
WithReDoc(cfg...) Use ReDoc.
WithScalar(cfg...) Use Scalar.
WithRapiDoc(cfg...) Use RapiDoc.

Adapter-only options: WithDisableDocs, WithDocsPath, WithSpecPath, WithCacheAge, WithUIOption, WithSwaggerUI, WithStoplightElements, WithReDoc, WithScalar, and WithRapiDoc affect adapter docs/spec endpoints, not core static generation output.

Tag options: TagSummary, TagDescription, TagExternalDocs, TagParent (3.2.0), TagKind (3.2.0).

Server options: ServerDescription, ServerVariables, ServerName (3.2.0).


Routes and Groups

api := r.Group("/api/v1", option.GroupTags("v1"))

api.Get("/users/{id}",
	option.OperationID("getUser"),
	option.Summary("Get user"),
	option.Description("Returns one user."),
	option.Tags("users"),
	option.Security("bearerAuth"),
	option.Request(new(GetUserRequest)),
	option.Response(200, new(User), option.ContentDescription("OK")),
	option.Response(404, nil, option.ContentDescription("Not Found")),
)

Router methods:

Get, Post, Put, Delete, Patch, Options, Head, Trace, Query (3.2.0), Add, Webhook (3.1.x+), AddWebhook (3.1.x+), NewRoute(...).Method(...).Path(...).With(...), Group, Route, With.

Group options:

Option Purpose
GroupTags(tags...) Apply tags to all routes in the group.
GroupSecurity(name, scopes...) Apply an operation security requirement to all routes in the group.
GroupDeprecated(deprecated...) Mark all routes in the group as deprecated.
GroupHidden(hide...) Exclude all routes in the group from the generated document.

Operation options:

Option Purpose
OperationID(id) Set operationId.
Summary(summary) Set summary; also sets description when description is empty.
Description(description) Set description.
ExternalDocs(url, description...) Set operation externalDocs.
Tags(tags...) Add operation tags.
Security(name, scopes...) Add an operation security requirement.
Deprecated(deprecated...) Mark the operation deprecated.
Hidden(hide...) Exclude the operation from the generated document.
Request(structure, contentOpts...) Add parameters and/or a request body from a Go value.
Response(status, structure, contentOpts...) Add a response. Duplicate status/content pairs are merged into oneOf.
CustomizeOperation(fn) Mutate the low-level openapi.Operation directly.

Content options:

Option Purpose
ContentType(contentType) Set media type; default is application/json.
ContentDescription(description) Set request/response description.
ContentSummary(summary) Set request/response summary (OpenAPI 3.2.0).
ContentDefault(isDefault...) Mark response as default.
ContentEncoding(prop, enc) Add media type encoding metadata for a property.
ContentExample(value) Set media type example.
ContentNamedExample(name, value, opts...) Add one named media type example.
ContentExamples(examples) Set media type examples.
ContentRequired(required...) Mark request body as required.
ContentFormat(format) Override the reflected content schema format.

Example options: ExampleSummary, ExampleDescription, ExampleExternalValue, ExampleDataValue (3.2.0), ExampleSerializedValue (3.2.0).


Security

r := spec.NewRouter(
	option.WithSecurity("apiKey", option.SecurityAPIKey("X-API-Key", openapi.SecuritySchemeAPIKeyInHeader)),
	option.WithSecurity("bearerAuth", option.SecurityHTTPBearer("bearer")),
	option.WithSecurity("mtls", option.SecurityMutualTLS()),
	option.WithSecurity("oauth2", option.SecurityOAuth2AuthorizationCode(
		"https://auth.example.com/oauth/authorize",
		"https://auth.example.com/oauth/token",
		map[string]string{
			"read":  "Read access",
			"write": "Write access",
		},
	)),
	option.WithSecurity("oidc", option.SecurityOpenIDConnect("https://auth.example.com/.well-known/openid-configuration")),
)

Security helpers:

  • SecurityAPIKey(name, in)
  • SecurityHTTPBearer(scheme, bearerFormat...)
  • SecurityOAuth2(flows)
  • SecurityOAuth2Implicit(authorizationURL, scopes, flowOpts...)
  • SecurityOAuth2Password(tokenURL, scopes, flowOpts...)
  • SecurityOAuth2ClientCredentials(tokenURL, scopes, flowOpts...)
  • SecurityOAuth2AuthorizationCode(authorizationURL, tokenURL, scopes, flowOpts...)
  • SecurityOAuth2DeviceAuthorization(deviceAuthorizationURL, tokenURL, scopes, flowOpts...) — OpenAPI 3.2.0
  • OAuthRefreshURL(url)
  • SecurityOpenIDConnect(url)
  • SecurityMutualTLS()
  • SecurityDescription(description)
  • SecurityOAuth2MetadataURL(url) — OpenAPI 3.2.0
  • SecurityDeprecated(deprecated...) — OpenAPI 3.2.0

Reflection Tags

Request structs are split into parameters and request body:

  • Fields with path, query, header, cookie, or querystring tags become OpenAPI parameters.
  • querystring is only valid for OpenAPI 3.2.0.
  • Body fields use json names by default; for application/x-www-form-urlencoded and multipart/form-data they use form names, falling back to json.
  • json:"-" skips a field.
  • Path parameters are always marked required.
  • Adapter packages can add framework-specific parameter tags with ParameterTagMapping (e.g. Gin uses uri, Fiber uses params, Echo uses param).
type SearchRequest struct {
	ID       string `path:"id" required:"true" description:"Resource ID"`
	Status   string `query:"status" enum:"active,inactive"`
	TraceID  string `header:"X-Trace-ID"`
	Session  string `cookie:"session"`
	Name     string `json:"name" minLength:"2" maxLength:"80"`
	File     []byte `form:"file" format:"binary" description:"Upload file"`
	Internal string `json:"-"`
}

Naming and location tags:

Tag Purpose
json:"name" Body/schema property name.
path:"name" Path parameter.
query:"name" Query parameter.
header:"name" Header parameter.
cookie:"name" Cookie parameter.
querystring:"name" OpenAPI 3.2.0 whole-query-string parameter.
mediaType:"..." Media type for querystring parameter content; defaults to application/x-www-form-urlencoded. OpenAPI 3.2.0 only.
form:"name" Form body property name for form content types.

Schema tags:

Tag Output
required:"true" Adds property to parent required; path parameters are required automatically.
type:"string,null" Overrides type; comma-separated unions emitted only for OpenAPI 3.1.x/3.2.0.
title:"..." title.
description:"..." description.
format:"email" format.
pattern:"..." pattern.
default:"..." default; JSON values are decoded when valid.
example:"..." example; JSON values are decoded when valid.
examples:"[...]" examples for OpenAPI 3.1.x/3.2.0; JSON array preferred, comma-separated fallback.
enum:"a,b,c" enum; JSON array or comma-separated values.
const:"..." const for OpenAPI 3.1.x/3.2.0.
multipleOf:"2" multipleOf.
maximum:"100" maximum.
minimum:"1" minimum.
exclusiveMaximum:"true" OpenAPI 3.0.x: boolean; OpenAPI 3.1.x/3.2.0: numeric value.
exclusiveMinimum:"true" OpenAPI 3.0.x: boolean; OpenAPI 3.1.x/3.2.0: numeric value.
maxLength:"80" maxLength.
minLength:"2" minLength.
maxItems:"10" maxItems.
minItems:"1" minItems.
maxProperties:"10" maxProperties.
minProperties:"1" minProperties.
uniqueItems:"true" uniqueItems.
nullable:"true" nullable for OpenAPI 3.0.x; type: [T, null] for OpenAPI 3.1.x/3.2.0 when possible.
deprecated:"true" deprecated.
readOnly:"true" readOnly.
writeOnly:"true" writeOnly.
contentEncoding:"base64" contentEncoding for OpenAPI 3.1.x/3.2.0.
contentMediaType:"image/png" contentMediaType for OpenAPI 3.1.x/3.2.0.
xmlName:"name" XML object name.
xmlNamespace:"uri" XML object namespace.
xmlPrefix:"p" XML object prefix.
xmlAttribute:"true" XML object attribute; skipped when OpenAPI 3.2.0 xmlNodeType is set.
xmlWrapped:"true" XML object wrapped; skipped when OpenAPI 3.2.0 xmlNodeType is set.
xmlNodeType:"element" OpenAPI 3.2.0 XML object nodeType.

Reflection intentionally omits keywords that are invalid for the selected OpenAPI version. For example, const, examples, contentEncoding, and contentMediaType are not emitted for OpenAPI 3.0.x.


Reflected Go Types

Go type Schema
bool type: boolean
Signed integers (except int64) type: integer, format: int32
int64 type: integer, format: int64
uint8, uint16 type: integer, format: int32, minimum: 0
uint, uint32, uint64, uintptr type: integer, format: int64, minimum: 0
float32 type: number, format: float
float64 type: number, format: double
string type: string
time.Time type: string, format: date-time
[]T, [N]T type: array, items: T
[]byte 3.0.x: type: string, format: byte; 3.1.x/3.2.0: type: string, contentEncoding: base64
map[string]T type: object, additionalProperties: T
Structs type: object, properties
Named structs (component mode) #/components/schemas/{TypeName} reference
encoding.TextMarshaler + TextUnmarshaler (no json.Marshaler) type: string
Pointers Nullable schema behavior

Custom types can expose their own schema when tags are not expressive enough:

type Slug string

func (*Slug) OpenAPISchema(version string) *openapi.Schema {
	if version == openapi.Version304 {
		return &openapi.Schema{Type: "string", Format: "slug"}
	}
	return &openapi.Schema{Type: []string{"string", "null"}, Format: "slug"}
}

For static schemas, implement OpenAPISchema() *openapi.Schema instead. Field tags are still applied on top of custom schemas.

Embedded struct references

By default, anonymous embedded struct fields are inlined into the parent schema. To emit an allOf $ref instead, use the refer:"true" tag or implement openapi.EmbedReferencer on the embedded type:

// Via struct tag
type Request struct {
    Base `refer:"true"`
    Name string `json:"name"`
}

// Via interface (useful when you own the embedded type)
type Base struct {
    ID int `json:"id"`
}

func (Base) ReferEmbedded() {}

Both produce:

Request:
  type: object
  properties:
    name:
      type: string
  allOf:
    - $ref: '#/components/schemas/Base'

Reflector Configuration

r := spec.NewRouter(
	option.WithReflectorConfig(
		option.InlineRefs(),
		option.StripDefNamePrefix("DTO"),
		option.TypeMapping(NullString{}, new(string)),
		option.ParameterTagMapping(openapi.ParameterInPath, "params"),
		option.InterceptDefName(func(t reflect.Type, defaultName string) string {
			return defaultName
		}),
		option.InterceptSchema(func(params openapi.InterceptSchemaParams) (stop bool, err error) {
			if params.Processed {
				params.Schema.Extensions = map[string]any{"x-go-type": params.Type.String()}
			}
			return false, nil
		}),
		option.InterceptProp(func(params openapi.InterceptPropParams) error {
			if params.Processed && params.Field.Tag.Get("internal") == "true" {
				return openapi.ErrSkipProperty
			}
			return nil
		}),
		option.RequiredPropByValidateTag(), // marks fields required when validate tag contains "required"
	),
)
Option Purpose
InlineRefs(inline...) Inline schemas instead of using component references for named structs.
StripDefNamePrefix(prefixes...) Strip prefixes from generated component names.
TypeMapping(src, dst) Reflect src as if it were dst.
ParameterTagMapping(in, sourceTag) Override the struct tag for a parameter location or body. Use openapi.ParameterInBody to replace json tag, openapi.ParameterInForm to replace form tag.
InterceptDefName(fn) Customize schema component names.
InterceptSchema(fn) Hook called before and after each type is reflected. Pre-call (Processed=false): return stop=true to override schema entirely. Post-call (Processed=true): modify the built schema.
InterceptProp(fn) Hook called before and after each struct field is reflected. Return openapi.ErrSkipProperty to exclude the field.
RequiredPropByValidateTag(tag, sep...) Mark properties as required when their validate tag (or custom tag) contains "required". Default tag: validate, default separator: ,.

OpenAPI 3.2

Selecting openapi.Version320 enables the following additional features:

  • Router.Query(path, opts...) — new QUERY HTTP method.
  • Custom HTTP methods via Add, emitted as additionalOperations.
  • querystring parameter tags.
  • Root $self field.
  • Server name field.
  • Response summary field.
  • Tag parent and kind fields.
  • Security scheme metadata and deprecation fields.
  • components.mediaTypes.
  • Media type and encoding fields: itemSchema, prefixEncoding, itemEncoding.
  • Discriminator defaultMapping.
  • Example dataValue and serializedValue fields.
  • XML nodeType.

Low-Level OpenAPI Control

The openapi package exposes typed low-level OpenAPI structs. Use them when a feature does not require reflection or doesn't yet have a convenience option.

r := spec.NewRouter(
	option.WithOpenAPIVersion(openapi.Version320),
	option.WithTitle("API"),
	option.WithVersion("1.0.0"),
	option.WithDocument(func(doc *openapi.Document) {
		doc.Webhooks = map[string]*openapi.PathItem{
			"user.created": {
				Post: &openapi.Operation{
					Responses: map[string]*openapi.Response{
						"202": {Description: "Accepted"},
					},
				},
			},
		}
		doc.Extensions = map[string]any{"x-company": "oaswrap"}
		doc.Extra = map[string]any{"futureOfficialField": true}
	}),
)
  • Use Extensions for x-* specification extensions.
  • Use Extra to emit official or future fields not yet typed.
  • Use CustomizeOperation to mutate an operation directly.
  • Use WithDocument to mutate the final document before output.

The library validates many OpenAPI invariants but does not attempt exhaustive semantic validation for every rule in the specification.


Examples

Complete working examples are in the examples/ directory:

  • Basic — standalone spec generation.
  • Petstore — full Petstore API with routes and models.
  • Adapter examples — framework-specific examples in adapter/*/example.

API Reference

Full documentation is available at pkg.go.dev/github.com/oaswrap/spec.

Package Purpose
spec Core router and spec builder.
openapi Owned OpenAPI model.
option Configuration options.
pkg/parser Path parsers such as NewColonParamParser.

Contributing

Issues and pull requests are welcome. Please check existing issues and discussions before starting work on new features.


License

MIT


Acknowledgements

Documentation

Index

Constants

View Source
const (
	// SeverityError indicates a strict validation failure.
	SeverityError = validate.SeverityError
	// SeverityWarning indicates a validation warning that doesn't necessarily invalidate the document.
	SeverityWarning = validate.SeverityWarning
	// SeverityInfo indicates informational validation feedback.
	SeverityInfo = validate.SeverityInfo
)

Variables

This section is empty.

Functions

func OneOf added in v0.5.0

func OneOf(values ...any) any

OneOf returns a value that represents multiple possible schemas.

Types

type Contact added in v0.5.0

type Contact = openapi.Contact

Contact is an alias of openapi.Contact.

type Document added in v0.5.0

type Document = openapi.Document

Document is an alias of openapi.Document.

type ExternalDocs added in v0.5.0

type ExternalDocs = openapi.ExternalDocs

ExternalDocs is an alias of openapi.ExternalDocs.

type Generator

type Generator interface {
	Router
	// Config returns the effective OpenAPI configuration.
	Config() *openapi.Config
	// Document returns the built in-memory OpenAPI document.
	Document() *openapi.Document
	// GenerateSchema serializes the document in YAML by default, or JSON/YAML
	// when explicitly requested.
	GenerateSchema(formats ...string) ([]byte, error)
	// MarshalYAML validates and serializes the document as YAML.
	MarshalYAML() ([]byte, error)
	// MarshalJSON validates and serializes the document as pretty JSON.
	MarshalJSON() ([]byte, error)
	// Validate builds the document and validates OpenAPI invariants.
	Validate() error
	// ValidateReport builds the document, validates it, and returns all findings including warnings and info.
	ValidateReport() error
	// WriteSchemaTo serializes and writes the document based on file extension.
	WriteSchemaTo(path string) error
}

Generator builds, validates, and serializes an OpenAPI document.

func NewGenerator

func NewGenerator(opts ...option.OpenAPIOption) Generator

NewGenerator creates a new OpenAPI generator with the provided options.

Example:

g := NewGenerator(
	option.WithTitle("My API"),
	option.WithVersion("1.0.0"),
	option.WithDescription("This is my API"),
	option.WithServer("https://api.example.com"),
)
g.Get("/users", option.Summary("Get all users"))
g.Post("/users", option.Summary("Create a new user"))
schema, err := g.GenerateSchema("yaml")
if err != nil {
	log.Fatal(err)
}
fmt.Println(string(schema))

func NewRouter added in v0.1.3

func NewRouter(opts ...option.OpenAPIOption) Generator

NewRouter creates a new OpenAPI generator. It is an alias of NewGenerator for naming compatibility.

Example:

g := NewRouter(
	option.WithTitle("My API"),
	option.WithVersion("1.0.0"),
	option.WithDescription("This is my API"),
	option.WithServer("https://api.example.com"),
)
g.Get("/users", option.Summary("Get all users"))
g.Post("/users", option.Summary("Create a new user"))
schema, err := g.GenerateSchema("yaml")
if err != nil {
	log.Fatal(err)
}
fmt.Println(string(schema))

type License added in v0.5.0

type License = openapi.License

License is an alias of openapi.License.

type OAuthFlow added in v0.5.0

type OAuthFlow = openapi.OAuthFlow

OAuthFlow is an alias of openapi.OAuthFlow.

type OAuthFlows

type OAuthFlows = openapi.OAuthFlows

OAuthFlows is an alias of openapi.OAuthFlows.

type Route added in v0.1.3

type Route interface {
	// Method sets the HTTP method.
	Method(method string) Route
	// Path sets the route path or webhook name.
	Path(path string) Route
	// With appends operation options.
	With(opts ...option.OperationOption) Route
}

Route lets callers set method/path/options incrementally.

type Router added in v0.1.3

type Router interface {
	// Get registers a GET operation for a path.
	Get(path string, opts ...option.OperationOption) Route
	// Post registers a POST operation for a path.
	Post(path string, opts ...option.OperationOption) Route
	// Put registers a PUT operation for a path.
	Put(path string, opts ...option.OperationOption) Route
	// Delete registers a DELETE operation for a path.
	Delete(path string, opts ...option.OperationOption) Route
	// Patch registers a PATCH operation for a path.
	Patch(path string, opts ...option.OperationOption) Route
	// Options registers an OPTIONS operation for a path.
	Options(path string, opts ...option.OperationOption) Route
	// Head registers a HEAD operation for a path.
	Head(path string, opts ...option.OperationOption) Route
	// Trace registers a TRACE operation for a path.
	Trace(path string, opts ...option.OperationOption) Route
	// Query registers an OpenAPI 3.2 QUERY operation for a path.
	Query(path string, opts ...option.OperationOption) Route
	// Add registers an operation for an arbitrary HTTP method.
	Add(method, path string, opts ...option.OperationOption) Route
	// Webhook registers a webhook entry using POST as the default method.
	// Webhooks require OpenAPI 3.1.x or 3.2.0.
	Webhook(name string, opts ...option.OperationOption) Route
	// AddWebhook registers a webhook entry with an explicit HTTP method.
	// Webhooks require OpenAPI 3.1.x or 3.2.0.
	AddWebhook(method, name string, opts ...option.OperationOption) Route
	// NewRoute creates a route that can be configured incrementally.
	NewRoute(opts ...option.OperationOption) Route
	// Route creates a grouped router and executes registrations in fn.
	Route(pattern string, fn func(router Router), opts ...option.GroupOption) Router
	// Group creates a grouped router with a path prefix and group options.
	Group(pattern string, opts ...option.GroupOption) Router
	// With appends group options to the current router scope.
	With(opts ...option.GroupOption) Router
}

Router registers operations and route groups that are converted to OpenAPI Paths and Webhooks during document generation.

type Schema added in v0.5.0

type Schema = openapi.Schema

Schema is an alias of openapi.Schema.

type SchemaExposer added in v0.5.0

type SchemaExposer interface {
	OpenAPISchema(version string) *openapi.Schema
}

SchemaExposer lets custom Go types provide their own OpenAPI Schema Object. The selected OpenAPI version is passed so implementations can return version-specific schema keywords.

type SecurityScheme

type SecurityScheme = openapi.SecurityScheme

SecurityScheme is an alias of openapi.SecurityScheme.

type Server

type Server = openapi.Server

Server is an alias of openapi.Server.

type ServerVariable

type ServerVariable = openapi.ServerVariable

ServerVariable is an alias of openapi.ServerVariable.

type Severity added in v0.5.0

type Severity = validate.Severity

Severity represents the severity level of a validation error.

type StaticSchemaExposer added in v0.5.0

type StaticSchemaExposer interface {
	OpenAPISchema() *openapi.Schema
}

StaticSchemaExposer lets custom Go types provide an OpenAPI Schema Object when they do not need version-specific output.

type Tag added in v0.5.0

type Tag = openapi.Tag

Tag is an alias of openapi.Tag.

type ValidationError added in v0.5.0

type ValidationError = validate.Error

ValidationError represents a single validation error with an associated severity.

type ValidationErrors added in v0.5.0

type ValidationErrors struct {
	Errors []ValidationError
}

ValidationErrors is a collection of ValidationError. It implements the error interface and aggregates multiple validation issues into a single error value.

func (ValidationErrors) Error added in v0.5.0

func (e ValidationErrors) Error() string

Error implements the error interface by joining each entry with "; ".

func (ValidationErrors) HasSeverity added in v0.5.0

func (e ValidationErrors) HasSeverity(s Severity) bool

HasSeverity reports whether the collection contains an entry at the given severity.

func (ValidationErrors) Unwrap added in v0.5.0

func (e ValidationErrors) Unwrap() []error

Unwrap returns each ValidationError as a standard error for errors.Is/errors.As walks.

Directories

Path Synopsis
adapter
chiopenapi module
echoopenapi module
echov5openapi module
fiberopenapi module
ginopenapi module
httpopenapi module
muxopenapi module
internal
pkg

Jump to

Keyboard shortcuts

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