当前位置:网站首页>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 |
边栏推荐
- 熊市慢慢,Bit.Store提供稳定Staking产品助你穿越牛熊
- Hcia-r & s self use notes (25) NAT technical background, NAT type and configuration
- DAY15(DAY16拓展):文件包含漏洞
- 改哭了,终于解决了Cannot read properties of undefined (reading ‘parseComponent‘)
- Fvuln automated web vulnerability detection tool
- 如何零代码制作深度学习的趣味app(适合新手)
- Detailed steps of JDBC connection to database
- Qt布局管理--部件拉伸(Stretch)原理及大小策略(sizePolicy)
- Sliding switch of tab of uniapp component
- Character type conversion
猜你喜欢
DAY4:MySQL 数据库的建立及简单实用
Dao race track is booming. What are the advantages of m-dao?
“山东大学移动互联网开发技术教学网站建设”项目实训日志三
“山东大学移动互联网开发技术教学网站建设”项目实训日志一
Hcia-r & s self use notes (27) comprehensive experiment
熊市下PLATO如何通过Elephant Swap,获得溢价收益?
Starfish OS: create a new paradigm of the meta universe with reality as the link
Detailed steps of JDBC connection to database
Laravel Swagger添加访问密码
sql-server 数据表的简单操作
随机推荐
Okaleido tiger logged into binance NFT on July 27, and has achieved good results in the first round
Windows下cmd窗口连接mysql并操作表
Installation steps and environment configuration of vs Code
DAY15(DAY16拓展):文件包含漏洞
[typescript] type reduction (including type protection) and type predicate in typescript
华为2020校招笔试编程题 看这篇就够了(下)
大部分PHP程序员,都搞不懂如何安全代码部署
Shanzhai coin Shib has a US $548.6 million stake in eth whale's portfolio - traders should be on guard
“山东大学移动互联网开发技术教学网站建设”项目实训日志七
Masscan tutorial
Strategic cooperation with many institutions shows the strength of the leading company of platofarm yuancosmos
Qtcreator+cmake compiler settings
Detailed installation and use tutorial of MySQL (nanny installation with pictures and texts)
Relative positioning and absolute positioning
Sqlmap是什么以及使用方法
Fvuln automated web vulnerability detection tool
Plato farm is expected to further expand its ecosystem through elephant swap
超简单集成HMS ML Kit 人脸检测实现可爱贴纸
Qt布局管理--部件拉伸(Stretch)原理及大小策略(sizePolicy)
QT layout management -- Part stretch principle and sizepolicy