openapi

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2025 License: MIT Imports: 11 Imported by: 0

README

OpenAPI Specification Generator

openapi provides a framework for generating OpenAPI v3 specifications, using a chi mux, from code. It attaches as one or more middleware to describe each route, removing itself at runtime to have no performance impact.

Usage

Struct Generator

oapi-gen is a struct function generator used to create documentation and attriubutes from struct field comments.

Any struct with the directive openapi:gen will have a documentation function generated.

Install
$ go install github.com/gamefabric/openapi/cmd/oapi-gen@<version>

A simple way to keep the generation up-to-date is to use Go's generation framework on each package that needs documentation functions.

//go:generate oapi-gen

Then run:

go generate ./...
Example

Running oapi-gen on the following package:

package somepackage

// TestObject is a test object.
//
//openapi:docs
type TestObject struct {
	// A is an example field.
	A string `json:"a"`

	// B is another example field.
	//
	//openapi:required
	//openapi:format=ipv4
	B string
}

Will produce a documentation file zz_generated.docs.go with the content:

package somepackage

// Code generated by oapi-docgen. DO NOT EDIT.

// Docs returns a set of property descriptions per property.
func (TestObject) Docs() map[string]string {
	return map[string]string{
		"B": "B is another example field.",
		"a": "A is an example field.",
	}
}

// Attributes returns a set of property attributes per property.
func (TestObject) Attributes() map[string]string {
	return map[string]string{
		"B": "required",
	}
}

// Formats returns a set of property formats per property.
func (TestObject) Formats() map[string]string {
	return map[string]string{
		"B": "ipv4",
	}
}

The following directives can be used on struct fields:

  • openapi:required: Marks the field as required.
  • openapi:readonly: Marks the field as read only.
  • openapi:format=<FORMAT>: Sets the format of the field, e.g. "date" or "ipv4". See list of valid formats.
More Options

oapi-gen command supports the following additional arguments.

Options:
  -all
    	Parse all structs.
  -path string
    	The path to parse for documentation. Defaults to the current working directory.
  -q	Suppress generation output.
  -tag string
    	The tag to override the documentation key. (default "json")

Documentation

Overview

Package openapi provides a framework for generating OpenAPI v3 specifications using a chi mux.

Example
mux := chi.NewMux()

// `openapi` will build the route additively.
mux.Use(openapi.Op().
	Consumes("application/json").
	Produces("application/json").
	Build())

mux.Route("/api", func(r chi.Router) {
	op := openapi.Op().
		ID("test-id").
		Doc("test").
		Tag("test-tag").
		Param(openapi.PathParameter("name", "the item name")).
		Param(openapi.QueryParameter("filter", "the filter number", 123)).
		Param(openapi.QueryParameterWithType("custom", "the customer param", "integer")).
		Consumes("text/html", "text/plain").
		Reads(&TestObject{}).
		Produces("application/json", "application/xml").
		Returns(http.StatusOK, "OK", &TestObject{})

	r.With(op.Build()).Post("/test/{name}", func(rw http.ResponseWriter, req *http.Request) {})
})

mux.Get("/internal/handler", testHandler())

doc, err := openapi.BuildSpec(mux, openapi.SpecConfig{
	StripPrefixes:  []string{"/internal"},
	ObjPkgSegments: 1,
})
if err != nil {
	log.Printf("Error: %v\n", err)
	return
}

doc.OpenAPI = "3.0.0"
doc.Info = &kin.Info{
	Title:   "Test Server",
	Version: "1",
}
_, err = json.MarshalIndent(doc, "", "  ")
if err != nil {
	log.Printf("Error: %v\n", err)
	return
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	SecurityNone   = Security{}
	SecurityBearer = Security{
		Type: secTypeBearer,

		BearerFormat: "",
	}
	SecurityBasic = Security{
		Type: secTypeBasic,
	}
)

SecurityNone means no security is required for this endpoint.

Functions

func BuildSpec

func BuildSpec(r chi.Routes, cfg SpecConfig) (kin.T, error)

BuildSpec builds openapi v3 spec from the given chi router.

Types

type OpBuilder

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

OpBuilder builds an operation. An operation describes a request route.

func Op

func Op() *OpBuilder

Op returns an op builder.

func (*OpBuilder) Build

func (o *OpBuilder) Build() func(http.Handler) http.Handler

Build builds a middleware that will return an Operation when queried. In all other situations, the given handler is returned, effectively removing the middleware from the stack.

func (*OpBuilder) BuildHandler

func (o *OpBuilder) BuildHandler() func(http.HandlerFunc) http.HandlerFunc

BuildHandler builds a wrapper handler that contains an Operation.

The operation is registered globally with the operation registrar as there is no other way to retrieve the operation from a handler func.

func (*OpBuilder) Consumes

func (o *OpBuilder) Consumes(mediaTypes ...string) *OpBuilder

Consumes appends the given consumable media types to the operation.

func (*OpBuilder) Doc

func (o *OpBuilder) Doc(doc string) *OpBuilder

Doc sets the operation summary.

func (*OpBuilder) ID

func (o *OpBuilder) ID(id string) *OpBuilder

ID set the operation id.

func (*OpBuilder) Param

func (o *OpBuilder) Param(param Parameter) *OpBuilder

Param appends the given parameter to the operation.

func (*OpBuilder) Params

func (o *OpBuilder) Params(params ...Parameter) *OpBuilder

Params appends the given parameters to the operation.

func (*OpBuilder) Produces

func (o *OpBuilder) Produces(mediaTypes ...string) *OpBuilder

Produces appends the given producible media types to the operation.

func (*OpBuilder) Reads

func (o *OpBuilder) Reads(obj any) *OpBuilder

Reads sets the request body type on the operation.

func (*OpBuilder) RequiresAuth

func (o *OpBuilder) RequiresAuth(name string, sec Security) *OpBuilder

RequiresAuth requires authentication for this endpoint.

The supported authentication types are "bearer", "basic" and "apiKey". The same name requires the same Security object, as all security schemes are registered under its name. The behavior for not following this directive is undetermined.

func (*OpBuilder) Returns

func (o *OpBuilder) Returns(code int, description string, obj any, opts ...ResponseOptFunc) *OpBuilder

Returns appends the given response to the operation.

func (*OpBuilder) Tag

func (o *OpBuilder) Tag(tag string) *OpBuilder

Tag appends the given tag to the operation.

type Operation

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

Operation documents a request.

func (Operation) Merge

func (o Operation) Merge(newOp Operation) Operation

Merge merges the operation with the given operation.

type Parameter

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

Parameter documents a query or path parameter.

func HeaderParameter

func HeaderParameter(name, description string) Parameter

HeaderParameter returns a header parameter with the given type.

func ParseParams

func ParseParams(obj any, tag string) []Parameter

ParseParams parses parameters from a struct using the given tag to derive its name.

func PathParameter

func PathParameter(name, description string) Parameter

PathParameter returns a path parameter with the given name and description.

func QueryParameter

func QueryParameter(name, description string, typ any) Parameter

QueryParameter returns a query parameter where the type will be resolved.

func QueryParameterWithType

func QueryParameterWithType(name, description, typ string) Parameter

QueryParameterWithType returns a query parameter with the given type.

type Response

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

Response documents a request response.

type ResponseOptFunc

type ResponseOptFunc func(*Response)

ResponseOptFunc is an option function for configuration the response.

func WithMediaTypes

func WithMediaTypes(mediaTypes ...string) ResponseOptFunc

WithMediaTypes sets the specific media types for this response.

func WithResponseHeader

func WithResponseHeader(name string) ResponseOptFunc

WithResponseHeader adds a header to the response.

type Security

type Security struct {
	// Type is the security type, valid values are "bearer", "auth" and "apiKey".
	Type string

	// BearerFormat is a hint to the client to identify how the bearer token is formatted.
	// Bearer tokens are usually generated by an authorization server,
	// so this information is primarily for documentation purposes.
	BearerFormat string

	// APIKeyName contains the name of the header, query or cookie parameter to be used.
	APIKeyName string

	// APIKeyIn is required for type "apiKey", valid values are "query", "header" or "cookie".
	APIKeyIn string
}

Security represents a security configuration.

type SpecConfig

type SpecConfig struct {
	// StripPrefixes strips the given prefixes from the routes.
	StripPrefixes []string

	// ObjPkgSegments determines the maximum number of
	// package segments to use to identify an object.
	ObjPkgSegments int
}

SpecConfig configures how the spec is built.

Directories

Path Synopsis
cmd
oapi-gen
Package main is struct documentation generator
Package main is struct documentation generator

Jump to

Keyboard shortcuts

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