当前位置:网站首页>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 | 参数 | 说明 | 阿萨德 |
边栏推荐
猜你喜欢
HCIA-R&S自用笔记(27)综合实验
QPalette学习笔记
365 day challenge leetcode1000 question - day 036 binary tree pruning + subarray and sorted interval sum + delete the shortest subarray to order the remaining arrays
Seay source code audit system
Longest string without duplicate characters
php写一个购买全网最低价的纸尿裤
Qt布局管理--部件拉伸(Stretch)原理及大小策略(sizePolicy)
Clickhouse learning (V) cluster operation
Sqlmap是什么以及使用方法
微信小程序-组件传参,状态管理
随机推荐
组件传参与生命周期
Hcia-r & s self use notes (25) NAT technical background, NAT type and configuration
ClickHouse学习(一)ClickHouse?
Solve the problem that the prompt information of form verification does not disappear and the assignment does not take effect
href与src的区别
shell基本操作(下)
Set the background color of a cell in the table
Clickhouse learning (VII) table query optimization
B - identify floating point constant problems
ClickHouse学习(七)表查询优化
Masscan使用教程.
Clickhouse learning (IV) SQL operation
Fvuln automated web vulnerability detection tool
Dynamic sorting of DOM object element blocks in applets
nmap是什么以及使用教程
Cmu15-213 shell lab experiment record
uniapp之常用提示弹框
Playwright实战案例之爬取js加密数据
eggjs 创建应用知识点
shell基本操作(上)