• swaggo
  • swagger

Install the swag command

go get -u github.com/swaggo/swag/cmd/swag
Copy the code

Write a comment

  • Basic Service Information
// @title Swagger Usage example
/ / @ version 1.0
// @description Swagger
func main(a){
	r := gin.Default()
    r.GET("/check", connectCheck)
    ...
}
Copy the code
  • API information
type Response struct{
	Code uint32 `json:"code"`
	Message uint32 `json:"message"`
	Data interface{} `json:"data"`
}

type ResponseError struct{
	Code uint32 `json:"code"`
	Message uint32 `json:"message"`
}

// @summary service connection verification --> Interface introduction
// @description service initial connection test --> interface Description
// @accept json --> Receive type
// @produce json --> return type
// Success 200 {object} Response --> Return data structure on Success
// Failure 400 {object} ResponseError --> Return data structure after Failure
// Failure 404 {object} ResponseError
// Failure 500 {object} ResponseError
// @router /check [get] --> Router address and request method
func connectCheck(c *gin.Context){
	res := Response{ Code: 1001, Message: "OK", Data: "connect success !!!"}
	c.JSON(http.StatusOK, res)
}

Copy the code

Generating documentation

// The root directory executes swag initCopy the code

Configuring Document Routing

import ( ... GinSwagger "github.com/swaggo/gin-swagger" swaggerFiles "github.com/swaggo/files") func main(){ ... r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) r.Run(":8080") }Copy the code

Start the service and access

Go run main. Go / / the current document path: localhost: swagger/index. The HTMLCopy the code

API annotation definition

  • The summary introduction

    / / @ the Summary introduction
    Copy the code
  • Accept Specifies the MIME type to use

    // @Accept json
    Copy the code
  • Produce Specifies the MIME type that can be generated in response to the return type

    // @Produce json
    // @produce PNG Multiple files can be configured
    Copy the code
  • Param Parameter format: [Parameter Name Parameter Type Data Type Mandatory Remarks Restricted Attribute] Space split

    @Params userId query string true "User id" minlength(3) maxlength(100)
    @Params status query integer false "Status: 0 1" Enums(0.1) defualt(0) 
    Copy the code
    • Parameter available type [param type]
      • query
      • path
      • header
      • body
      • formDate
    • Data available type [data type]
      • string(string)
      • integer(int, uint, uint32, uint64)
      • boolean(bool)
      • user defined struct
    • Configurable property
      • Defualt * Parameter default value
      • Maximum number
      • Mininum number Minimum value
      • MaxLength Integer Indicates the maximum length
      • MinLength Integer Specifies the minimum length
      • Enums [*] Enumeration type
      • format string
      • CollectionFormat String Query Array division mode
  • Security safety

  • Success Response format: [Status code {Data type} Data Type Remarks]

    @Success 200 {object} Response "Return empty object"
    Copy the code
  • Failure Response format: [Status code {data type} Data type Remarks]

    @Failure 400 {object} ResponseError
    Copy the code
  • Header Format of the request header field: [Status code {Data type} Data type Remarks]

    // @Header 200 {string} Token "qwerty"
    Copy the code
  • Router Routing path

    // @Router /user/{userId} [get]
    Copy the code
  • X-name Indicates the extended field

    type Account struct {
        ID   string    `json:"id" extensions:"x-nullable,x-abc=def"` // The extended field must begin with "x-"
    }
    Copy the code

Structure description

  • Example example
type User struct{
	ID int `json:"id" example:"232323"`
	Name string `json:"name" example:"Coco" `
}
Copy the code
  • Limit properties

    type User struct{
    	ID int `json:"id" minLength:"3" maxLength:"100"`
    }
    Copy the code
  • Swaggerignore excludes fields

    type Account struct {
        ID   string    `json:"id"`
        Name string     `json:"name"`
        Ignored int     `swaggerignore:"true"` // Exclude the Ignored field
    }
    Copy the code
  • rename

    type Resp struct {
        Code int
    }//@name Response must be placed at the end of the structure
    Copy the code

Matters needing attention

  • Multi-field definitions cannot be cross-field

    // @Accept json
    // @Produce json
    // @param id query string false "user ID" default("") minlength(3) maxlength(100)
    // @produce json will Produce an error
    Copy the code
  • After modifying the definition, you need to run the command again to generate the command and restart the service

  • Import documents when configuring routes