当前位置:网站首页>Go|Gin 快速使用Swagger
Go|Gin 快速使用Swagger
2022-07-29 05:19:00 【廖圣平】
安装
go get -u github.com/swaggo/swag/cmd/swag
检查 自己的 GOPATH 是否再环境变量中。可通过 go env
查看
运行
swag init
会再目录下生成docs 文件夹
│ go.mod
│ go.sum
│ main.exe
│ main.go
│
├─docs
│ docs.go
│ swagger.json
│ swagger.yaml
例子
package main
import (
"github.com/gin-gonic/gin"
ginSwagger "github.com/swaggo/gin-swagger"
swaggerFiles "github.com/swaggo/files"
_ "hello/docs" // 这里需要引入本地已生成文档
"net/http"
)
// @title 廖圣平博客 // @version 1.0 // @description swagger 入门使用例子 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:"描述"` 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请求的例子 // @Schemes // @Description GET请求的例子描述 // @Tags 请求例子 // @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请求的例子 // @Description POST请求的例子描述 // @Tags 请求例子 // @Param body body Requests true "JSON数据" // @Accept json // @Produce json // @Success 200 {
object} Response --> 成功后返回数据结构
// @Failure 400 {
object} ResponseError --> 失败后返回数据结构
// @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
生成一个GET 请求。
格式化备注信息
swag fmt
参数
添加头信息
// @param Authorization header string true "验证参数Bearer和token空格拼接"
文件上传例子
// @Param file formData file true "this is a test file"
请求方式
// @Accept multipart/form-data
忽略字段
type Ignored struct {
Field5 string `swaggerignore:"true"`
}
对模型进行重命名
type Resp struct {
Code int
}//@name Response
枚举使用
// @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)
字符串限制长度
// @Param string query string false "string valid" minlength(5) maxlength(10)
// @Param int query int false "int valid" minimum(1) maximum(10)
验证
// @Security ApiKeyAuth
// @Security OAuth2Implicit[admin, write]
swag 返回工具
// 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)
}
- 数据例子
type Message struct {
Message string `json:"message" example:"message"`
}
- 支持markdown
// @Description | 参数 | 说明 |备注|
// @Description | :-----: | :----: | :----: |
// @Description | 参数 | 说明 | 阿萨德 |
边栏推荐
猜你喜欢
Question swiping Madness - leetcode's sword finger offer58 - ii Detailed explanation of left rotation string
ClickHouse学习(四)SQL操作
Qframe class learning notes
实现table某个单元格背景色设置
[C language series] - three methods to simulate the implementation of strlen library functions
Fvuln automated web vulnerability detection tool
Qt布局管理--部件拉伸(Stretch)原理及大小策略(sizePolicy)
Wechat applet - screen height
Do students in the science class really understand the future career planning?
ClickHouse学习(九)clickhouse整合mysql
随机推荐
Related knowledge of elastic box
Using POI TL to insert multiple pictures and the same data of multiple rows of cells into the table cells of word template at one time, it is a functional component for automatic merging
[sword finger offer] - explain the library function ATOI and simulate the realization of ATOI function
Clickhouse learning (XI) clickhouseapi operation
Common characteristic engineering operations
如何 Pr 一个开源composer项目
【电子电路】ADC芯片如何选型
HCIA-R&S自用笔记(27)综合实验
Qtcreator+cmake compiler settings
Database operation day 6
Cmu15-213 shell lab experiment record
[C language series] - storage of deep anatomical data in memory (I) opening of summer vacation
[C language series] - realize the exchange of two numbers without creating the third variable
字符类型转换
Relative positioning and absolute positioning
ClickHouse学习(四)SQL操作
Installation steps and environment configuration of vs Code
DAY6:利用 PHP 编写文件上传页面
【TypeScript】深入学习TypeScript对象类型
Day 3