簡述 Gin 框架如何集成swagger


簡述Gin框架集成swagger過程

1、安裝 swag

go get github.com/swaggo/swag/cmd/swag

swag 用於生成 docs 文件夾(swagger文檔程序使用)

安裝完成后會在 ${GOPATH}/bin生成一個執行文件

2、安裝依賴包

github.com/gin-gonic/gin
github.com/swaggo/gin-swagger

3、示例程序一


package main

import (
	_ "./docs"
	"github.com/gin-gonic/gin"
	"github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"
	"net/http"
)


// @title 開發文檔
// @version 0.0.1
// @BasePath /api/v1/

// @title  haimait.com開發文檔
// @version 1.0
// @description  Golang api of demo
// @termsOfService haimait.com

// @contact.name API Support
// @contact.url haimait.com
// @contact.email ×××@qq.com
// @BasePath /api/v1/
func main() {
	r := gin.New()
        swagHandler := true
        if swagHandler {
		// 文檔界面訪問URL
		// http://127.0.0.1:8080/swagger/index.html
		r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	}

	// 創建路由組
	v1 := r.Group("/api/v1")

	v1.GET("/getUser/:id", getUser)

	r.Run()
}

// @Tags 測試
// @Summary  獲取指定getUser記錄1
// @Description 獲取指定getUser記錄2
// @Param Authorization	header string true "Bearer 31a165baebe6dec616b1f8f3207b4273"
// @Accept  json
// @Product json
// @Param   id     query    int     true        "用戶id"
// @Param   name   query    string  false        "用戶name"
// @Success 200 {object} string	"{"code": 200, "data": [...]}"
// @Router /getUser/:id [get]
func getUser(c *gin.Context) {
	var r req
	Id:= c.DefaultQuery("id", "0")
	r.Id,_ = strconv.Atoi(Id)
	r.Name = c.DefaultQuery("name", "")
	Age, _ := strconv.Atoi(c.DefaultQuery("age", "0"))
	r.Age = Age
	fmt.Println(r)
	c.JSON(http.StatusOK, r)
}

type req struct {
	Id   int    `json:"id" form:"id" example:"1"`
	Name string `json:"name" form:"name" example:"用戶name"`
	Age  int    `json:"age" form:"age" example:"123"`
}

4、生成文檔

在項目執行 swag init

執行 go run main.go

進入 http://127.0.0.1:8080/swagger/index.html 查看文檔

這些注釋字段,我們一個個解釋。

使用token

如果你的程序中使用了token中間鍵,只需要添加下面兩行注釋即可

// @Security x-token
// @param x-token header string true "Authorization"

4、示例程序二

type req struct {
	Id   int    `json:"id" form:"id" example:"1"`  //用戶id
	Name string `json:"name" form:"name" example:"用戶name"`  //用戶姓名
	Age  int    `json:"age" form:"age" example:"123"`        //用戶年齡
}

// @Summary  獲取指定record記錄1
// @Description 獲取指定record記錄2
// @Tags 測試
// @Accept  json
// @Product json
// @Param data body req true "請示參數data"
// @Success 200 {object} req
// @Router /updateUser [POST]
func updateUser(c *gin.Context) {
	var r req
	err := c.ShouldBindJSON(&r)
	fmt.Println("err11", err)
	c.JSON(http.StatusOK, r)
}

5、示例程序三

type GetOperationLogListResponse struct {
	List  *[]req `json:"list"`
	Total int    `json:"total"`
}
type req struct {
	Id   int    `json:"id" form:"id" example:"1"`  //用戶id
	Name string `json:"name" form:"name" example:"用戶name"`  //用戶姓名
	Age  int    `json:"age" form:"age" example:"123"`        //用戶年齡
}
// @Title 應用中心操作日志
// @Author mengyilingjian@outlook.com
// @Description 獲取應用中心操作日志
// @Tags operationlog
// @Param Authorization	header string true "Bearer 31a165baebe6dec616b1f8f3207b4273"
// @Param route formData string false "路由"
// @Param operator formData string false "操作者"
// @Param operation_type formData string false "操作類型 1 新增、2 刪除、3 更新"
// @Param description formData string false "操作描述"
// @Param start_time formData int64 false "開始時間"
// @Param end_time formData int64 false "結束時間"
// @Param page formData int true "頁數"
// @Param size formData int true "數據條數"
// @Success 200 {object} GetOperationLogListResponse "{"deploy_env": "測試deploy_env"}"
// @Router	/api/v1/appcenter [get]
func GetOperationLogList(c *gin.Context) {
	c.JSON(http.StatusOK, "ok")
}

6、示例程序四

type TemplateAddBody struct {
	Name               string `json:"name" example:"用戶name"`
	DeployEnv          string `json:"deploy_env" example:"例子deploy_env"`
	GitlabType         int    `json:"gitlab_type" example:"1"`
	GitlabBranchName   string `json:"gitlab_branch_name" example:"例子description"`
	IsAutoRelease      int    `json:"is_auto_release" example:"12"`
	Description        string `json:"description" example:"例子description"`
	GitlabCITemplateID int32  `json:"gitlab_ci_template_id" example:"123"`
	GitlabID           uint32 `json:"gitlab_id" example:"222"`
}

// @Title 新增模版
// @Author mengyilingjian@outlook.com
// @Description 新增模版
// @Tags release template
// @Param Authorization	header	string true "Bearer 31a165baebe6dec616b1f8f3207b4273"
// @Param body body	TemplateAddBody true "JSON數據"
// @Success 200 {object} TemplateAddBody
// @Router	/api/v1/release/template/add [post]
func ReleaseTemplateAdd(c *gin.Context) {

}


API 注釋定義

參考下面連接
鏈接:https://www.jianshu.com/p/4875b5ac9feb

官網文檔:
https://swaggo.github.io/swaggo.io/declarative_comments_format/general_api_info.html

更多參考文檔:

http://www.topgoer.com/其他/Swagger.html

https://blog.csdn.net/weixin_42661321/article/details/108887918


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM