当前位置:网站首页>Go|gin quickly use swagger
Go|gin quickly use swagger
2022-07-29 05:47:00 【Liaoshengping】

install
go get -u github.com/swaggo/swag/cmd/swag
Check Their own GOPATH Is it in the environment variable . It can be done by go env see

function
swag init
Will be generated under the directory docs Folder
│ go.mod
│ go.sum
│ main.exe
│ main.go
│
├─docs
│ docs.go
│ swagger.json
│ swagger.yaml
Example
package main
import (
"github.com/gin-gonic/gin"
ginSwagger "github.com/swaggo/gin-swagger"
swaggerFiles "github.com/swaggo/files"
_ "hello/docs" // Here, you need to import the local generated document
"net/http"
)
// @title Liaoshengping blog // @version 1.0 // @description swagger Getting started with examples func main() {
r := gin.Default() r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.GET("/get", Get)
r.POST("/post", Post)
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
//r.GET("/swagger/*any", handleReDoc)
r.Run() // listen and serve on 0.0.0.0:8080
}
type Response struct{
Code uint32 `json:"code"` Message uint32 `json:"message" description:" describe "` Data interface{
} `json:"data"`
}
type Requests struct{
Code uint32 `json:"code"` Message uint32 `json:"message"` Data interface{
} `json:"data"`
}
type ResponseError struct{
Code uint32 `json:"code"`
Message uint32 `json:"message"`
}
// @title Swagger Example API // @version 1.0 // @description This is a sample server celler server. // @termsOfService http://swagger.io/terms/ // @contact.name API Support // @contact.url http://www.swagger.io/support // @contact.email [email protected] // @license.name Apache 2.0 // @license.url http://www.apache.org/licenses/LICENSE-2.0.html // @securityDefinitions.basic BasicAuth // @Summary GET Example of a request // @Schemes // @Description GET Example description of the request // @Tags Request example // @Param id query int true "Account ID" // @Accept json // @Produce json // @Success 200 {
object} Response
// @Router /get [get] func Get(c *gin.Context){
res := Response{
Code: 1001, Message: 1, Data: "connect success !!!"}
c.JSON(http.StatusOK, res)
}
// @Summary POST Example of a request // @Description POST Example description of the request // @Tags Request example // @Param body body Requests true "JSON data " // @Accept json // @Produce json // @Success 200 {
object} Response --> The data structure is returned after success
// @Failure 400 {
object} ResponseError --> The data structure is returned after failure
// @Router /post [post] func Post(c *gin.Context){
res := Response{
Code: 1001, Message: 1, Data: "connect success !!!"}
c.JSON(http.StatusOK, res)
}
go run main.go

Generate a GET request .
Format notes
swag fmt
Parameters
Add header information
// @param Authorization header string true " Verify parameters Bearer and token Space splicing "
File upload example
// @Param file formData file true "this is a test file"
Request mode
// @Accept multipart/form-data
Ignore fields
type Ignored struct {
Field5 string `swaggerignore:"true"`
}
Rename the model
type Resp struct {
Code int
}//@name Response
Use enumerated
// @Param enumstring query string false "string enums" Enums(A, B, C)
// @Param enumint query int false "int enums" Enums(1, 2, 3)
// @Param enumnumber query number false "int enums" Enums(1.1, 1.2, 1.3)
String limit length
// @Param string query string false "string valid" minlength(5) maxlength(10)
// @Param int query int false "int valid" minimum(1) maximum(10)
verification
// @Security ApiKeyAuth
// @Security OAuth2Implicit[admin, write]
swag Return to tool
// Auth godoc
// @Summary Auth admin
// @Description get admin info
// @Tags accounts,admin
// @Accept json
// @Produce json
// @Success 200 {object} model.Admin
// @Failure 400 {object} httputil.HTTPError
// @Failure 401 {object} httputil.HTTPError
// @Failure 404 {object} httputil.HTTPError
// @Failure 500 {object} httputil.HTTPError
// @Security ApiKeyAuth
// @Router /admin/auth [post]
func (c *Controller) Auth(ctx *gin.Context) {
authHeader := ctx.GetHeader("Authorization")
if len(authHeader) == 0 {
httputil.NewError(ctx, http.StatusBadRequest, errors.New("please set Header Authorization"))
return
}
if authHeader != "admin" {
httputil.NewError(ctx, http.StatusUnauthorized, fmt.Errorf("this user isn't authorized to operation key=%s expected=admin", authHeader))
return
}
admin := model.Admin{
ID: 1,
Name: "admin",
}
ctx.JSON(http.StatusOK, admin)
}
- Data example
type Message struct {
Message string `json:"message" example:"message"`
}
- Support markdown
// @Description | Parameters | explain | remarks |
// @Description | :-----: | :----: | :----: |
// @Description | Parameters | explain | Assad |
边栏推荐
- DAY13:文件上传漏洞
- Relationship between redrawing and reflow
- DAY15(DAY16拓展):文件包含漏洞
- DAY15:文件包含漏洞靶场手册(自用 file-include 靶场)
- 2022 mathematical modeling competition summer training lecture - optimization method: goal planning
- The bear market is slow, and bit.store provides stable stacking products to help you get through the bull and bear market
- 超简单集成HMS ML Kit 人脸检测实现可爱贴纸
- Character type conversion
- Hcia-r & s self use notes (26) PPP
- Madonna "hellent" bought $1.3 million NFT boring ape, which is now considered too expensive
猜你喜欢

熊市慢慢,Bit.Store提供稳定Staking产品助你穿越牛熊

“山东大学移动互联网开发技术教学网站建设”项目实训日志四

熊市下PLATO如何通过Elephant Swap,获得溢价收益?

如何 Pr 一个开源composer项目
![[C language series] - string + partial escape character explanation + annotation tips](/img/75/698ba0672af9d6118ee7e2fdf6daae.png)
[C language series] - string + partial escape character explanation + annotation tips

Cmu15-213 shell lab experiment record

Wechat applet - component parameter transmission, state management

Fantom (FTM) 价格将在未来几天飙升 20%

Seay source code audit system

量化开发必掌握的30个知识点【什么是分笔逐笔数据】?
随机推荐
性能对比|FASS iSCSI vs NVMe/TCP
超简单集成HMS ML Kit 人脸检测实现可爱贴纸
WIN10 编译ffmpeg(包含ffplay)
nmap是什么以及使用教程
Wapiti是什么以及使用教程
Win10 搭建MSYS2环境
Sqlmap是什么以及使用方法
How can Plato obtain premium income through elephant swap in a bear market?
麦当娜“Hellbent”购买130万美元的nft无聊猿,现在被认为太贵了
MySQL decompressed version windows installation
DAY15:文件包含漏洞靶场手册(自用 file-include 靶场)
Fantom (FTM) prices will soar by 20% in the next few days
马斯克推崇的柏拉图式元宇宙,PlatoFarm早已验证出答案
Hcia-r & s self use notes (26) PPP
QT setting background image method
MOVE PROTOCOL全球健康宣言,将健康运动进行到底
使用Qss设置窗体样式
Record the SQL injection vulnerability of XX company
OpenAtom OpenHarmony分论坛圆满举办,生态与产业发展迈向新征程
[electronic circuit] how to select ADC chip