Documentation ¶
Overview ¶
Package openapi provide OpenAPI 3.0 support for Go In this package, there are many util functions that looks chained, but some are not. If a method starts with "Add", it will return the instance that has just been added. Otherwise, methods start with "With" returns the instance itself.
Package openapi provide OpenAPI 3.0 support for Go
Index ¶
- Constants
- Variables
- func DefaultOperationID(method, path string) string
- type APIExample
- type Components
- type Contact
- type Example
- type Info
- type License
- type Link
- type MediaType
- type OpenAPI
- func (o *OpenAPI) AddHeader(key string, param *Param) string
- func (o *OpenAPI) AddParam(key string, param *Param) string
- func (o *OpenAPI) AddPath(path, summary, description string) *Path
- func (o *OpenAPI) AddSchema(key string, schema *Schema) *Schema
- func (o *OpenAPI) GetHeader(key string) *Param
- func (o *OpenAPI) GetParam(key string) *Param
- func (o *OpenAPI) GetSchema(key string) *Schema
- func (o OpenAPI) JSON() ([]byte, error)
- func (o *OpenAPI) MustGetSchema(key string, v interface{}) *Schema
- func (o *OpenAPI) YAML() ([]byte, error)
- type Operation
- func (o *Operation) AddParam(in ParamType, name, description string) *Param
- func (o *Operation) Metadata(operationID, summary, description string) *Operation
- func (o *Operation) Read(description string, required bool, mimeType string, example interface{}) *Operation
- func (o *Operation) ReadJSON(description string, required bool, key string, v interface{}) *Operation
- func (o *Operation) ReturnDefault(description string, key string, v interface{}) *Operation
- func (o *Operation) Returns(code int, description string, key string, v interface{}) *Operation
- func (o *Operation) ReturnsNonJSON(code int, description string, mimeType string, headers map[string]*Param, ...) *Operation
- func (o *Operation) Root() *OpenAPI
- func (o *Operation) WithParam(param *Param) *Operation
- func (o *Operation) WithPathParam(name, description string) *Operation
- func (o *Operation) WithQueryParam(name, description string, example interface{}) *Operation
- func (o *Operation) WithTags(tags ...string) *Operation
- type Param
- type ParamType
- type Path
- type RequestBody
- type Response
- type Responses
- type Router
- type Schema
- func (s Schema) MarshalJSON() ([]byte, error)
- func (s *Schema) SetRoot(root *OpenAPI)
- func (s *Schema) WithAnyOf(args ...interface{}) *Schema
- func (s *Schema) WithBasicProperty(name, propType, description string, required bool) *Schema
- func (s *Schema) WithDescription(description string) *Schema
- func (s *Schema) WithItems(schema *Schema) *Schema
- func (s *Schema) WithOneOf(keyAndValues ...interface{}) *Schema
- func (s *Schema) WithProperty(name string, required bool, prop *Schema) *Schema
- func (s *Schema) WithRequired(required bool) *Schema
- type SchemaDoc
- type SchemaRequired
- type Server
- type ServerVariable
Examples ¶
Constants ¶
const ( MimeJSON = "application/json" MimeYAML = "application/yaml" )
Supported mime types when using shortcuts
Variables ¶
var ( ErrNoRoot = errors.New("root not initialized with NewRoot") ErrNoOneOf = errors.New("oneOf has no alternatives") ErrInvalidSchemaDoc = errors.New("invalid SchemaDoc method given") )
Errors that may be returned or raised
var OperationGenerator = DefaultOperationID
OperationGenerator provide operationId when no operation id given
Functions ¶
func DefaultOperationID ¶
DefaultOperationID provide default operation id generator
Types ¶
type Components ¶
type Components struct { Schemas schemaMap `json:"schemas,omitempty"` Responses respMap `json:"responses,omitempty"` Parameters paramMap `json:"parameters,omitempty"` Examples exampleMap `json:"examples,omitempty"` RequestBodies reqBodyMap `json:"requestBodies,omitempty"` Headers paramMap `json:"-"` Links map[string]*Link `json:"links,omitempty"` }
Components object
type Contact ¶
type Contact struct { Name string `json:"name,omitempty"` URL string `json:"url,omitempty"` Email string `json:"email,omitempty"` }
Contact info
type Example ¶
type Example struct { Summary string `json:"summary,omitempty"` Description string `json:"description,omitempty"` Value interface{} `json:"value"` }
Example ExampleObj
type Info ¶
type Info struct { Title string `json:"title" validate:"required"` Version string `json:"version" validate:"required"` TermsOfService string `json:"termsOfService,omitempty"` Contact *Contact `json:"contact,omitempty"` License *License `json:"license,omitempty"` }
Info of global document
type License ¶
type License struct { Name string `json:"name" validate:"required"` URL string `json:"url,omitempty"` }
License info
type Link ¶
type Link struct { OperationRef string `json:"operationRef,omitempty"` OperationID string `json:"operationId,omitempty"` Parameters map[string]*Param `json:"parameters,omitempty"` RequestBody interface{} `json:"requestBody,omitempty"` Description string `json:"description,omitempty"` }
Link to a resuable object
type MediaType ¶
type MediaType struct { Schema *Schema `json:"schema,omitempty"` Example interface{} `json:"example,omitempty"` Examples map[string]*Example `json:"examples,omitempty"` }
MediaType media type object
type OpenAPI ¶
type OpenAPI struct { OpenAPI string `json:"openapi"` Info Info `json:"info"` Servers []Server `json:"servers,omitempty"` Paths pathMap `json:"paths"` Components *Components `json:"components,omitempty"` }
OpenAPI document structure
func New ¶
New create OpenAPI document object and set it as global document root
Example ¶
o, err := New("3.0.0", sampleInfo) if err != nil { log.Fatal(err) } r := NewRouter(o) r.Route("/books", func(r Router) { r.GET("/", "List books", "List books"). Returns(200, "Book content", "bookArray", []*Book{}). Returns(404, "Book not found", "replyError", &ReplyError{ Code: "book_not_found", Message: "The request book is not found", }).ReturnDefault("internal errors", "replyError", &ReplyError{ Code: "internal_error", Message: "an unknown error occurred in our end", }) r.POST("/", "Add new book", "Add a new book"). ReadJSON("JSON of book info", true, "book", &Book{}). Returns(200, "Book content", "book", &Book{}). Returns(404, "Book not found", "replyError", &ReplyError{ Code: "book_not_found", Message: "The request book is not found", }) r.Route("/{id}", func(r Router) { r.WithPathParam("id", "ID of the book") r.GET("", "Get single book", "Info of a book"). Returns(200, "Book content", "book", &Book{}). Returns(404, "Book not found", "replyError", &ReplyError{ Code: "book_not_found", Message: "The request book is not found", }) }) }) raw, err := o.JSON() if err != nil { log.Fatal(err) } fmt.Print(string(raw))
Output: {"openapi":"3.0.0","info":{"title":"testing","version":"v1.0","termsOfService":"abcd","contact":{"name":"Ethan Tang","url":"example.com","email":"someone@example.com"},"license":{"name":"MIT License","url":"http://example.com/mit"}},"paths":{"/books":{"description":"","get":{"summary":"List books","description":"List books","responses":{"200":{"description":"Book content","content":{"application/json":{"schema":{"$ref":"#/components/schemas/bookArray"},"example":[]}}},"404":{"description":"Book not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/replyError"},"example":{"code":"book_not_found","message":"The request book is not found"}}}},"default":{"description":"internal errors","content":{"application/json":{"schema":{"$ref":"#/components/schemas/replyError"},"example":{"code":"internal_error","message":"an unknown error occurred in our end"}}}}}},"post":{"summary":"Add new book","description":"Add a new book","requestBody":{"description":"JSON of book info","content":{"application/json":{"schema":{"$ref":"#/components/schemas/book"},"example":{"name":"","author":"","date":""}}},"required":true},"responses":{"200":{"description":"Book content","content":{"application/json":{"schema":{"$ref":"#/components/schemas/book"},"example":{"name":"","author":"","date":""}}}},"404":{"description":"Book not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/replyError"},"example":{"code":"book_not_found","message":"The request book is not found"}}}}}},"summary":""},"/books/{id}":{"description":"","get":{"summary":"Get single book","description":"Info of a book","responses":{"200":{"description":"Book content","content":{"application/json":{"schema":{"$ref":"#/components/schemas/book"},"example":{"name":"","author":"","date":""}}}},"404":{"description":"Book not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/replyError"},"example":{"code":"book_not_found","message":"The request book is not found"}}}}}},"parameters":[{"name":"id","in":"path","description":"ID of the book","required":true,"schema":{"type":"string"}}],"summary":""}},"components":{"schemas":{"book":{"type":"object","properties":{"author":{"type":"string","maxLength":128,"minLength":1},"date":{"type":"string","format":"date"},"name":{"type":"string","maxLength":128,"minLength":1}},"required":["name","author"]},"bookArray":{"type":"array","items":{"type":"object","properties":{"author":{"type":"string","maxLength":128,"minLength":1},"date":{"type":"string","format":"date"},"name":{"type":"string","maxLength":128,"minLength":1}},"required":["name","author"]}},"replyError":{"type":"object","properties":{"code":{"type":"integer","description":"Error code of current string, read by program"},"message":{"type":"string","description":"Human friendly message that may help with the problem"}}}}}}
func (*OpenAPI) MustGetSchema ¶
MustGetSchema create schema for struct when necessary and always return a ref format
type Operation ¶
type Operation struct { Tags []string `json:"tags,omitempty"` Summary string `json:"summary,omitempty"` Description string `json:"description,omitempty"` OperationID string `json:"operationId,omitempty"` Parameters []*Param `json:"parameters,omitempty"` RequestBody *RequestBody `json:"requestBody,omitempty"` Responses Responses `json:"responses" validate:"required"` Deprecated bool `json:"deprecated,omitempty"` // contains filtered or unexported fields }
Operation OperationObject
func (*Operation) Read ¶
func (o *Operation) Read(description string, required bool, mimeType string, example interface{}) *Operation
Read read raw body of any kind
func (*Operation) ReadJSON ¶
func (o *Operation) ReadJSON(description string, required bool, key string, v interface{}) *Operation
ReadJSON read object json from request body
func (*Operation) ReturnDefault ¶
ReturnDefault add default response. A default response is the response to be used when none of defined codes match the situation.
func (*Operation) ReturnsNonJSON ¶
func (o *Operation) ReturnsNonJSON(code int, description string, mimeType string, headers map[string]*Param, schema *Schema, example interface{}) *Operation
ReturnsNonJSON return something not json
func (*Operation) WithPathParam ¶
WithPathParam add path param
func (*Operation) WithQueryParam ¶
WithQueryParam add query param. Complex types of query param is not supported here(e.g., a struct or slice)
type Param ¶
type Param struct { // Fixed fields Name string `json:"name" validate:"required"` In ParamType `json:"in" validate:"required,oneof=query header path cookie"` Description string `json:"description,omitempty"` Required bool `json:"required"` Deprecated bool `json:"deprecated,omitempty"` AllowEmptyValue bool `json:"allowEmptyValue,omitempty"` // Below are optional fields Schema *Schema `json:"schema,omitempty"` Example interface{} `json:"example,omitempty"` Examples map[string]*Example `json:"examples,omitempty"` // contains filtered or unexported fields }
Param ParameterObject
func NewPathParam ¶
NewPathParam create new path param
func NewQueryParam ¶
NewQueryParam create new query param
func (*Param) SetDeprecated ¶
SetDeprecated make param as deprecated
func (*Param) WithStruct ¶
WithStruct add struct schema for param
type ParamType ¶
type ParamType string
ParamType param "in" request
type Path ¶
type Path struct { Summary string `json:"summary"` Description string `json:"description"` Parameters []*Param `json:"parameters,omitempty"` // contains filtered or unexported fields }
Path definition
func (*Path) AddOperation ¶
AddOperation add operation to path
type RequestBody ¶
type RequestBody struct { Description string `json:"description,omitempty"` // MIME-Type -> MediaTypeObject Content mediaTypeMap `json:"content" validate:"required"` Required bool `json:"required,omitempty"` }
RequestBody request body object
type Response ¶
type Response struct { Description string `json:"description"` Headers paramMap `json:"headers,omitempty"` Content mediaTypeMap `json:"content,omitempty"` }
Response response object
type Router ¶
type Router interface { Root() *OpenAPI WithParam(param *Param) Router WithPathParam(name, description string) Router WithTags(tags ...string) Router Route(path string, fn func(r Router)) Router // HTTP methods GET(path, summary, description string) *Operation PUT(path, summary, description string) *Operation POST(path, summary, description string) *Operation DELETE(path, summary, description string) *Operation HEAD(path, summary, description string) *Operation PATCH(path, summary, description string) *Operation }
Router is a extract of api path. router grouped in multiple levels can share parameters(path/query/header/etc)
type Schema ¶
type Schema struct { Ref string `json:"-"` Type string `json:"type,omitempty"` Format string `json:"format,omitempty" validate:"oneof=int32 int64 float double byte binary date date-time password"` AllOf []*Schema `json:"allOf,omitempty"` OneOf []*Schema `json:"oneOf,omitempty"` AnyOf []*Schema `json:"anyOf,omitempty"` Not *Schema `json:"not,omitempty"` Items *Schema `json:"items,omitempty"` Properties map[string]*Schema `json:"properties,omitempty"` AdditionalProperties *Schema `json:"additionalProperties,omitempty"` Description string `json:"description,omitempty"` Default interface{} `json:"default,omitempty"` Maximum interface{} `json:"maximum,omitempty"` Minimum interface{} `json:"minimum,omitempty"` MaxLength *int64 `json:"maxLength,omitempty"` MinLength *int64 `json:"minLength,omitempty"` Pattern string `json:"pattern,omitempty"` Required *SchemaRequired `json:"required,omitempty"` Enum []string `json:"enum,omitempty"` // contains filtered or unexported fields }
Schema SchemaObject
func (*Schema) WithBasicProperty ¶
WithBasicProperty add a basic propertity
func (*Schema) WithDescription ¶
WithDescription add description
func (*Schema) WithProperty ¶
WithProperty add to a schema
func (*Schema) WithRequired ¶
WithRequired make a schema to required: true or false
type SchemaDoc ¶
type SchemaDoc interface {
SchemaDoc() *Schema
}
SchemaDoc provide schema for a struct
type SchemaRequired ¶
SchemaRequired is a special representation for schema field "required", which can be either boolean or an array of propertity names
func (SchemaRequired) MarshalJSON ¶
func (s SchemaRequired) MarshalJSON() ([]byte, error)
MarshalJSON for special required field
type Server ¶
type Server struct { URL string `json:"url" validate:"required"` Description string `json:"description,omitempty"` Variables map[string]ServerVariable `json:"variables,omitempty"` }
Server server object
type ServerVariable ¶
type ServerVariable struct { Enum []string `json:"enum,omitempty"` Description string `json:"description,omitempty"` Default string `json:"default" validate:"required"` }
ServerVariable is used to replace some things in url schema