goas

package module
v1.16.1 Latest Latest
Warning

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

Go to latest
Published: Dec 12, 2022 License: BSD-3-Clause, MIT Imports: 19 Imported by: 0

README

goas

The project is based on

Generate OpenAPI Specification json file with comments in Go.

Limit

  • Only support go module.
  • Anonymous struct field is not supported.

Install

go get -u github.com/mikunalpha/goas

Usage

You can document your service by placing annotations inside your godoc at various places in your code.

Service Description

The service description comments can be located in any of your .go files. They provide general information about the service you are documenting.

// @Version 1.0.0
// @Title Backend API
// @Description API usually works as expected. But sometimes its not true.
// @ContactName Abcd
// @ContactEmail abce@email.com
// @ContactURL http://someurl.oxox
// @TermsOfServiceUrl http://someurl.oxox
// @LicenseName MIT
// @LicenseURL https://en.wikipedia.org/wiki/MIT_License
// @Server http://www.fake.com Server-1
// @Server http://www.fake2.com Server-2
// @Security AuthorizationHeader read write
// @SecurityScheme AuthorizationHeader http bearer Input your token
Security

If authorization is required, you must define security schemes and then apply those to the API. A scheme is defined using @SecurityScheme [name] [type] [parameters] and applied by adding @Security [scheme-name] [scope1] [scope2] [...].

All examples in this section use MyApiAuth as the name. This name can be anything you chose; multiple named schemes are supported. Each scheme must have its own name, except for OAuth2 schemes - OAuth2 supports multiple schemes by the same name.

A number of different types is supported, they all have different parameters:

Type Description Parameters Example
HTTP A HTTP Authentication scheme using the Authorization header scheme: any HTTP Authentication scheme @SecurityScheme MyApiAuth basic
APIKey Authorization by passing an API Key along with the request in: Location of the API Key, options are header, query and cookie. name: The name of the field where the API Key must be set @SecurityScheme MyApiAuth apiKey header X-MyCustomHeader
OpenIdConnect Delegating security to a known OpenId server url: The URL of the OpenId server @SecurityScheme MyApiAuth openIdConnect https://example.com/.well-known/openid-configuration
OAuth2AuthCode Using the "Authentication Code" flow of OAuth2 authorizationUrl, tokenUrl @SecurityScheme MyApiAuth oauth2AuthCode /oauth/authorize /oauth/token
OAuth2Implicit Using the "Implicit" flow of OAuth2 authorizationUrl `@SecurityScheme MyApiAuth oauth2Implicit /oauth/authorize
OAuth2ResourceOwnerCredentials Using the "Resource Owner Credentials" flow of OAuth2 authorizationUrl `@SecurityScheme MyApiAuth oauth2ResourceOwnerCredentials /oauth/token
OAuth2ClientCredentials Using the "Client Credentials" flow of OAuth2 authorizationUrl `@SecurityScheme MyApiAuth oauth2ClientCredentials /oauth/token

Any text that is present after the last parameter wil be used as the description. For instance @SecurityScheme MyApiAuth basic Login with your admin credentials.

Once all security schemes have been defined, they must be configured. This is done with the @Security comment. Depending on the type of the scheme, scopes (see below) may be supported. At the moment, it is only possible to configure security for the entire service.

// @Security MyApiAuth read_user write_user
Scopes

For OAuth2 security schemes, it is possible to define scopes using the @SecurityScope [schema-name] [scope-code] [scope-description] comment.

// @SecurityScope MyApiAuth read_user Read a user from the system
// @SecurityScope MyApiAuth write_user Write a user to the system
Handler funcs

By adding comments to your handler func godoc, you can document individual actions as well as their input and output.

type User struct {
  ID   uint64 `json:"id" example:"100" description:"User identity"`
  Name string `json:"name" example:"Mikun"` 
}

type UsersResponse struct {
  Data []Users `json:"users" example:"[{\"id\":100, \"name\":\"Mikun\"}]"`
}

type Error struct {
  Code string `json:"code"`
  Msg  string `json:"msg"`
}

type ErrorResponse struct {
  ErrorInfo Error `json:"error"`
}

// @Title Get user list of a group.
// @Description Get users related to a specific group.
// @Param  groupID  path  int  true  "Id of a specific group."
// @Success  200  object  UsersResponse  "UsersResponse JSON"
// @Failure  400  object  ErrorResponse  "ErrorResponse JSON"
// @Resource users
// @Route /api/group/{groupID}/users [get]
func GetGroupUsers() {
  // ...
}

// @Title Get user list of a group.
// @Description Create a new user.
// @Param  user  body  User  true  "Info of a user."
// @Success  200  object  User           "UsersResponse JSON"
// @Failure  400  object  ErrorResponse  "ErrorResponse JSON"
// @Resource users
// @Route /api/user [post]
func PostUser() {
  // ...
}
Title & Description
@Title {title}
@Title Get user list of a group.

@Description {description}.
@Description Get users related to a specific group.
  • {title}: The title of the route.
  • {description}: The description of the route.
Parameter
@Param  {name}  {in}  {goType}  {required}  {description}
@Param  user    body  User      true        "Info of a user."
  • {name}: The parameter name.
  • {in}: The parameter is in path, query, form, header, cookie, body or file.
  • {goType}: The type in go code. This will be ignored when {in} is file.
  • {required}: true, false, required or optional.
  • {description}: The description of the parameter. Must be quoted.
Response
@Success  {stauts}  {jsonType}  {goType}       {description}
@Success  200       object      UsersResponse  "UsersResponse JSON"

@Failure  {stauts}  {jsonType}  {goType}       {description}
@Failure  400       object      ErrorResponse  "ErrorResponse JSON"
  • {status}: The HTTP status code.
  • {jsonType}: The value can be object or array.
  • {goType}: The type in go code.
  • {description}: The description of the response. Must be quoted.
Resource & Tag
@Resource {resource}
@Resource users

@Tag {tag}
@tag xxx
  • {resource}, {tag}: Tag of the route.
Route
@Route {path}    {method}
@Route /api/user [post]
  • {path}: The URL path.
  • {method}: The HTTP Method. Must be put in brackets.
Documentation Generation

Go to the folder where is main.go in

// go.mod and main file are in the same directory
goas --module-path . --output oas.json

// go.mod and main file are in the different directory
goas --module-path . --main-file-path ./cmd/xxx/main.go --output oas.json

Documentation

Index

Constants

View Source
const (
	OpenAPIVersion = "3.0.0"

	ContentTypeText        = "text/plain"
	ContentTypeJson        = "application/json"
	ContentTypeOctetStream = "application/octet-stream"
	ContentTypeForm        = "multipart/form-data"
)

Variables

This section is empty.

Functions

func NewParser added in v1.8.0

func NewParser(modulePath, mainFilePath, handlerPath string, debug bool) (*parser, error)

Types

type ComponentsOjbect

type ComponentsOjbect struct {
	Schemas         map[string]*SchemaObject         `json:"schemas,omitempty"`
	SecuritySchemes map[string]*SecuritySchemeObject `json:"securitySchemes,omitempty"`
}

type ContactObject

type ContactObject struct {
	Name  string `json:"name,omitempty"`
	URL   string `json:"url,omitempty"`
	Email string `json:"email,omitempty"`
}

type HeaderObject

type HeaderObject struct {
	Schema      *SchemaObject `json:"schema,omitempty"`
	Description string        `json:"description,omitempty"`
}

type InfoObject

type InfoObject struct {
	Title          string         `json:"title"`
	Description    string         `json:"description,omitempty"`
	TermsOfService string         `json:"termsOfService,omitempty"`
	Contact        *ContactObject `json:"contact,omitempty"`
	License        *LicenseObject `json:"license,omitempty"`
	Version        string         `json:"version"`
}

type LicenseObject

type LicenseObject struct {
	Name string `json:"name,omitempty"`
	URL  string `json:"url,omitempty"`
}

type MediaTypeObject

type MediaTypeObject struct {
	Schema SchemaObject `json:"schema,omitempty"`
}

type OpenAPIObject

type OpenAPIObject struct {
	OpenAPI string         `json:"openapi"` // Required
	Info    InfoObject     `json:"info"`    // Required
	Servers []ServerObject `json:"servers,omitempty"`
	Paths   PathsObject    `json:"paths"` // Required

	Components ComponentsOjbect      `json:"components,omitempty"` // Required for Authorization header
	Security   []map[string][]string `json:"security,omitempty"`
}

type OperationObject

type OperationObject struct {
	Responses ResponsesObject `json:"responses"` // Required

	Tags        []string           `json:"tags,omitempty"`
	OperationID string             `json:"operationId,omitempty"`
	Summary     string             `json:"summary,omitempty"`
	Description string             `json:"description,omitempty"`
	Parameters  []ParameterObject  `json:"parameters,omitempty"`
	RequestBody *RequestBodyObject `json:"requestBody,omitempty"`
}

type ParameterObject

type ParameterObject struct {
	Name string `json:"name"` // Required
	In   string `json:"in"`   // Required. Possible values are "query", "header", "path" or "cookie"

	Description string        `json:"description,omitempty"`
	Required    bool          `json:"required,omitempty"`
	Example     interface{}   `json:"example,omitempty"`
	Schema      *SchemaObject `json:"schema,omitempty"`

	// Ref is used when ParameterOjbect is as a ReferenceObject
	Ref string `json:"$ref,omitempty"`
}

type PathItemObject

type PathItemObject struct {
	Ref         string           `json:"$ref,omitempty"`
	Summary     string           `json:"summary,omitempty"`
	Description string           `json:"description,omitempty"`
	Get         *OperationObject `json:"get,omitempty"`
	Post        *OperationObject `json:"post,omitempty"`
	Patch       *OperationObject `json:"patch,omitempty"`
	Put         *OperationObject `json:"put,omitempty"`
	Delete      *OperationObject `json:"delete,omitempty"`
	Options     *OperationObject `json:"options,omitempty"`
	Head        *OperationObject `json:"head,omitempty"`
	Trace       *OperationObject `json:"trace,omitempty"`
}

type PathsObject

type PathsObject map[string]*PathItemObject

type ReferenceObject

type ReferenceObject struct {
	Ref string `json:"$ref,omitempty"`
}

type RequestBodyObject

type RequestBodyObject struct {
	Content map[string]*MediaTypeObject `json:"content"` // Required

	Description string `json:"description,omitempty"`
	Required    bool   `json:"required,omitempty"`

	// Ref is used when RequestBodyObject is as a ReferenceObject
	Ref string `json:"$ref,omitempty"`
}

type ResponseObject

type ResponseObject struct {
	Description string `json:"description"` // Required

	Headers *orderedmap.OrderedMap      `json:"headers,omitempty"`
	Content map[string]*MediaTypeObject `json:"content,omitempty"`

	// Ref is for ReferenceObject
	Ref string `json:"$ref,omitempty"`
}

type ResponsesObject

type ResponsesObject map[string]*ResponseObject // [status]ResponseObject

type SchemaObject

type SchemaObject struct {
	ID                 string              `json:"-"` // For goas
	PkgName            string              `json:"-"` // For goas
	FieldName          string              `json:"-"` // For goas
	DisabledFieldNames map[string]struct{} `json:"-"` // For goas

	Type        string                 `json:"type,omitempty"`
	Format      string                 `json:"format,omitempty"`
	Required    []string               `json:"required,omitempty"`
	Properties  *orderedmap.OrderedMap `json:"properties,omitempty"`
	Description string                 `json:"description,omitempty"`
	Items       *SchemaObject          `json:"items,omitempty"` // use ptr to prevent recursive error
	Example     interface{}            `json:"example,omitempty"`
	Deprecated  bool                   `json:"deprecated,omitempty"`
	Nullable    bool                   `json:"nullable,omitempty"`
	Minimum     *int64                 `json:"minimum,omitempty"`
	Maximum     *int64                 `json:"maximum,omitempty"`
	MinLength   *int64                 `json:"minLength,omitempty"`
	MaxLength   *int64                 `json:"maxLength,omitempty"`
	MinItems    *int64                 `json:"minItems,omitempty"`
	MaxItems    *int64                 `json:"maxItems,omitempty"`
	Enum        []interface{}          `json:"enum,omitempty"`

	// Ref is used when SchemaObject is as a ReferenceObject
	Ref string `json:"$ref,omitempty"`
}

type SecuritySchemeOauthFlowObject

type SecuritySchemeOauthFlowObject struct {
	AuthorizationUrl string            `json:"authorizationUrl,omitempty"`
	TokenUrl         string            `json:"tokenUrl,omitempty"`
	Scopes           map[string]string `json:"scopes"`
}

type SecuritySchemeOauthObject

type SecuritySchemeOauthObject struct {
	Implicit              *SecuritySchemeOauthFlowObject `json:"implicit,omitempty"`
	AuthorizationCode     *SecuritySchemeOauthFlowObject `json:"authorizationCode,omitempty"`
	ResourceOwnerPassword *SecuritySchemeOauthFlowObject `json:"password,omitempty"`
	ClientCredentials     *SecuritySchemeOauthFlowObject `json:"clientCredentials,omitempty"`
}

func (*SecuritySchemeOauthObject) ApplyScopes

func (s *SecuritySchemeOauthObject) ApplyScopes(scopes map[string]string)

type SecuritySchemeObject

type SecuritySchemeObject struct {
	// Generic fields
	Type        string `json:"type"` // Required
	Description string `json:"description,omitempty"`

	// http
	Scheme string `json:"scheme,omitempty"`

	// apiKey
	In   string `json:"in,omitempty"`
	Name string `json:"name,omitempty"`

	// OpenID
	OpenIdConnectUrl string `json:"openIdConnectUrl,omitempty"`

	// OAuth2
	OAuthFlows *SecuritySchemeOauthObject `json:"flows,omitempty"`
}

type ServerObject

type ServerObject struct {
	URL         string `json:"url"`
	Description string `json:"description,omitempty"`
}

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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