当前位置:网站首页>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 | 参数 | 说明 | 阿萨德 |
边栏推荐
猜你喜欢

OpenAtom OpenHarmony分论坛圆满举办,生态与产业发展迈向新征程

Hcia-r & s self use notes (25) NAT technical background, NAT type and configuration

DAY6:利用 PHP 编写文件上传页面

Selenium实战案例之爬取js加密数据

ClickHouse学习(五)集群操作

QT layout management -- Part stretch principle and sizepolicy

Qtcreator+cmake compiler settings

Li Kou 994: rotten orange (BFS)

DAY14:Upload-labs 通关教程

365 day challenge leetcode 1000 questions - day 035 one question per day + two point search 13
随机推荐
Hcia-r & s self use notes (27) comprehensive experiment
[typescript] learn typescript object types in depth
Clickhouse learning (x) monitoring operation indicators
On Paradigm
·Let's introduce ourselves to the way of programming·
HCIA-R&S自用笔记(26)PPP
Longest string without duplicate characters
相对定位和绝对定位
Abstract classes and interfaces
QFrame类学习笔记
表格与表单相关知识点总结
Do students in the science class really understand the future career planning?
How does the MD editor of CSDN input superscripts and subscripts? The input method of formula and non formula is different
如何 Pr 一个开源composer项目
link与@import导入外部样式的区别
字符类型转换
微信小程序更改属性值-setData-双向绑定-model
Selection options of uniapp components (such as package selection)
Clickhouse learning (IV) SQL operation
JS simple code determines whether the device that opens the page is the PC end of the computer, the H5 end of the mobile phone, or the wechat end