Skip to content

Repository files navigation

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:docstypeTestObjectstruct {
// A is an example field.Astring`json:"a"`// B is another example field.////openapi:required//openapi:format=ipv4Bstring
}

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 {
returnmap[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 {
returnmap[string]string{
"B": "required",
}
}
// Formats returns a set of property formats per property.func (TestObject) Formats() map[string]string {
returnmap[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.
  • openapi:enum=1,2,3: Sets the allowed enum values for this field. For array fields, this is applied to the item values (items.enum).

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")

About

openapi provides a framework for generating OpenAPI v3 specifications, using a chi mux, from code.

Topics

Resources

Stars

4 stars

Watchers

3 watching

Forks

Releases

Used by

Contributors

Languages