Skip to content

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

License

Notifications You must be signed in to change notification settings

GameFabric/openapi

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

About

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

Topics

Resources

License

Stars

Watchers

Forks