Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Swagger 3.0 implementation for go

License

NotificationsYou must be signed in to change notification settings

parvez3019/go-swagger3

Repository files navigation

Click here forYoutube Demo Link

go-swagger3

GenerateOpenAPI Specification v3 file with comments in Go.

Table of content

1. Install

go install github.com/parvez3019/go-swagger3@latest

2. Documentation Generation

Using binary

Go to the folder where is main.go in

// go.mod and main file arein the same directorygo-swagger3 --module-path. --output oas.json --schema-without-pkg --generate-yamltrue// go.mod and main file arein the different directorygo-swagger3 --module-path. --main-file-path ./cmd/xxx/main.go --output oas.json --schema-without-pkg --generate-yamltrue//incase you get'command not found: go-swagger3' error, pleaseexport add GOPATH/bin to PATHexport PATH="$HOME/go/bin:$PATH"Notes - - Pass schema-without-pkg flag astrueif you want to generate schemas without package names- Pass generate-yaml as trusif you want to generate yaml spec file instead of json

Using docker

// go.mod and main file arein the same directorydocker run -t --rm -v$(pwd):/app -w /app parvez3019/go-swagger3:latest --module-path. --output oas.json --schema-without-pkg --generate-yamltrue// go.mod and main file arein the different directorydocker run -t --rm -v$(pwd):/app -w /app parvez3019/go-swagger3:latest --module-path. --main-file-path ./cmd/xxx/main.go --output oas.json --schema-without-pkg --generate-yamltrueNotes - - Pass schema-without-pkg flag astrueif you want to generate schemas without package names- Pass generate-yaml as trusif you want to generate yaml spec file instead of json

3. 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 Parvez// @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

Handler Functions

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

typeUserstruct {IDuint64`json:"id" example:"100" description:"User identity"`Namestring`json:"name" example:"Parvez"` }typeUsersResponsestruct {Data []Users`json:"users" example:"[{\"id\":100, \"name\":\"Parvez\"}]"`}typeErrorstruct {Codestring`json:"code"`Msgstring`json:"msg" skip:"true"`// use skip:"true" if you want to skip the field in the documentation spec}typeErrorResponsestruct {ErrorInfoError`json:"error"`}// RequestHeaders represents the model for header params// @HeaderParameters RequestHeaderstypeRequestHeadersstruct {Authorizationstring`json:"Authorization"`}// @Title Get user list of a group.// @Description Get users related to a specific group.// @Header model.RequestHeaders// @Param  groupID  path  int  true  "Id of a specific group." "120"// @Success  200  object  UsersResponse  "UsersResponse JSON"// @Failure  400  object  ErrorResponse  "ErrorResponse JSON"// @Resource users// @Route /api/group/{groupID}/users [get]funcGetGroupUsers() {// ...}// @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]funcPostUser() {// ...}

Title And 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}             {example}@Param  groupID   path  int       true        "Id of a specific group." "120"
  • {name}: The parameter name.
  • {in}: The parameter is inpath,query,form,header,cookie,body orfile.
  • {goType}: The type in go code. This will be ignored when {in} isfile.
  • {required}:true,false,required oroptional.
  • {description}: The description of the parameter. Must be quoted.
  • {example}:Optional example of this parameter. Must be quoted.

One can also override example for an object withoverride-example key in structeg -

typeRequeststruct {version  model.Version`"json:"Version" override-example:"11.0.0"`}

Header

@Header          {goType}@HeaderParameters   model.RequestHeaders
  • Header query param for endpoints, parses the query param from the model

Header Parameters

@Param              {goType}@HeaderParameters   RequestHeaders
  • {goType}: The type in go code. This will be ignored when {in} isfile.
  • Parses parameters from the type and keep it up component section for reference

Response

@Success  {status}  {jsonType}  {goType}       {description}@Success  200       object      UsersResponse  "UsersResponse JSON"@Failure  {status}  {jsonType}  {goType}       {description}@Failure  400       object      ErrorResponse  "ErrorResponse JSON"
  • {status}: The HTTP status code.
  • {jsonType}: The value can beobject orarray.
  • {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.

Enums

  • To generate enums create type structs for enum field with comma-separated values as follows:
  • Create struct type fields with @Enum Tag
  • Example as follows-
// @Enum CountriesEnumtypeCountriesEnumstruct {// Create the field name with same as struct nameCountriesEnumstring`enum:"india,china,mexico,japan" example:"india"`}
How to add reference of Enum on types
typeRequeststruct {Namestring`json:"name" example:"Parvez"`Countrystring`json:"country" $ref:"CountriesEnum"`}

Response body

You need to provide swagger fields as reflect tags in your structure. In example:

typeFilterstruct {Ratingint`json:"rating"`Typestring`json:"type"`Distanceint64`json:"distance", minimum:"1", maximum:"100"`DistrictCodestring`json:"district_code", pattern:"[a-z]{2}\\d[a-z]\\s\\d[a-z]{2}"`}

Available fields:

  • type
  • format
  • required
  • properties
  • description
  • items
  • example
  • deprecated (bool)
  • ref
  • enum
  • title
  • maximum (float64)
  • exclusiveMaximum (bool)
  • minimum (float64)
  • exclusiveMinimum (bool)
  • maxLength (uint)
  • minLength (uint)
  • pattern
  • maxItems (uint)
  • minItems (uint)
  • uniqueItems (bool)
  • maxProperties (uint)
  • minProperties (uint)
  • additionalProperties (bool)
  • nullable (bool)
  • readOnly (bool)
  • writeOnly (bool)

4. Security

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

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

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

TypeDescriptionParametersExample
HTTPA HTTP Authentication scheme using theAuthorization headerscheme: anyHTTP Authentication scheme@SecurityScheme MyApiAuth basic
APIKeyAuthorization by passing an API Key along with the requestin: Location of the API Key, options areheader,query andcookie. name: The name of the field where the API Key must be set@SecurityScheme MyApiAuth apiKey header X-MyCustomHeader
OpenIdConnectDelegating security to a known OpenId serverurl: The URL of the OpenId server@SecurityScheme MyApiAuth openIdConnect https://example.com/.well-known/openid-configuration
OAuth2AuthCodeUsing the "Authentication Code" flow of OAuth2authorizationUrl, tokenUrl@SecurityScheme MyApiAuth oauth2AuthCode /oauth/authorize /oauth/token
OAuth2ImplicitUsing the "Implicit" flow of OAuth2authorizationUrl`@SecurityScheme MyApiAuth oauth2Implicit /oauth/authorize
OAuth2ResourceOwnerCredentialsUsing the "Resource Owner Credentials" flow of OAuth2authorizationUrl`@SecurityScheme MyApiAuth oauth2ResourceOwnerCredentials /oauth/token
OAuth2ClientCredentialsUsing the "Client Credentials" flow of OAuth2authorizationUrl`@SecurityScheme MyApiAuth oauth2ClientCredentials /oauth/token

Any text that is present after the last parameter wil be used as the description. Forinstance@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 thetype of the scheme, scopes (see below) may be supported.At the moment, it is only possible toconfigure security for the entire service.

// @Security MyApiAuth read_user write_user

Scopes

For OAuth2 security schemes, it is possible to define scopes usingthe@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

5. Limitations

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

6. References


[8]ページ先頭

©2009-2025 Movatter.jp