当前位置:网站首页>Go language web development series 27: Gin framework: using gin swagger to implement interface documents
Go language web development series 27: Gin framework: using gin swagger to implement interface documents
2022-07-03 13:47:00 【Lao Liu, you are so awesome】
One , Libraries used for installation
1,swag The address of the library :
https://github.com/swaggo/swag
2, install swag command :
[email protected]:~$ go get -u github.com/swaggo/swag/cmd/swagTest the installation for success ?
[email protected]:/data/liuhongdi/digv27$ /home/liuhongdi/go/bin/swag -v
swag version v1.6.9Include in project main.go File directory :
[email protected]:~/go$ cd /data/liuhongdi/digv27
[email protected]:/data/liuhongdi/digv27$ /home/liuhongdi/go/bin/swag initYou can see swag init The command creates the file :
docs/docs.go This file is used for development
docs/swagger.json
docs/swagger.yaml3,gin-swagger The address of the library :
https://github.com/swaggo/gin-swagger
4, install gin-swagger:
[email protected]:/data/liuhongdi/digv27$ go get -u github.com/swaggo/gin-swaggerinstall swaggo/files
[email protected]:/data/liuhongdi/digv27$ go get -u github.com/swaggo/files explain : Liu Hongdi's go The forest is a focus golang The blog of ,
Address :https://blog.csdn.net/weixin_43881017
explain : author : Liu Hongdi mailbox : [email protected]
Two , Information about the demonstration project
1, Address :
2, Functional specifications : Demonstrates the use of gin-swagger Library implementation interface document
3, Project structure : Pictured :

3、 ... and ,go Code instructions
1,main.go
package main
import (
"github.com/liuhongdi/digv27/router"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
_ "github.com/liuhongdi/digv27/docs"
)
// @title E-commerce interface station document
// @version 1.0
// @description Electronic business platform ,api Document content of the interface station .
// @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
// @host api.estorelhd.com
func main() {
// Incoming routing
r := router.Router()
//swagger:
url := ginSwagger.URL("/swagger/doc.json") // The url pointing to API definition
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url))
//run
r.Run(":8080")
}2,controller/indexController.go
package controller
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/liuhongdi/digv27/global"
"time"
)
type IndexController struct{}
func NewIndexController() IndexController {
return IndexController{}
}
// @Summary Goods details
// @Description Show the details of the item
// @Produce json
// @Param goodsid path int true " goods id"
// @Success 200 {object} swag.ResultContGoods Return value after success
// @Router /index/goodsone/{goodsid} [get]
func (g *IndexController) GoodsOne(c *gin.Context) {
fmt.Println("controller:index: "+time.Now().String())
result := global.NewResult(c)
result.Success("success");
return
}
// @Summary List of goods
// @Description Show a list of products
// @Produce json
// @Param categoryId path int true " classification id"
// @Success 200 {object} swag.ResultContGoodsList Return value after success
// @Router /index/goodslist [get]
func (g *IndexController) GoodsList(c *gin.Context) {
fmt.Println("controller:index: "+time.Now().String())
result := global.NewResult(c)
result.Success("success");
return
}3,model/goods.go
package model
type Goods struct {
GoodsId int64 `gorm:"column:goodsId",json:"goodsid"` // goods id
GoodsName string `gorm:"column:goodsName",json:"goodsname"` // Commodity name
Subject string `gorm:"column:subject",json:"subject"` // Commodity Description
Price string `gorm:"column:price",json:"price"` // commodity price
Stock int `gorm:"column:stock",json:"stock"` // inventory
}
func (Goods) TableName() string {
return "goods"
}4,swag/result.go
package swag
import "github.com/liuhongdi/digv27/model"
// Goods details
type ResultContGoods struct {
Code int `json:"code" example:"0"` // Code ,0: success , Not 0: Failure
Msg string `json:"msg" example:" error "` // Error message
Data *model.Goods `json:"data" ` // Returned data
}
// List of goods
type ResultContGoodsList struct {
Code int `json:"code" example:"0"` // Code ,0: success , Not 0: Failure
Msg string `json:"msg" example:" error "` // Error message
Data []*model.Goods `json:"data" ` // List of goods
}
explain :swagger Yes interface{} The return data of class cannot be parsed ,
So we are for swag Defines the return result of the specified type ,
It can be compared with the actual returned type
5,global/result.go
package global
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Result struct {
Ctx *gin.Context
}
type ResultCont struct {
Code int `json:"code" example:"0"` // Code ,0: success , Not 0: Failure
Msg string `json:"msg" example:" error "` // Error message
Data interface{} `json:"data" ` // Returned data
}
func NewResult(ctx *gin.Context) *Result {
return &Result{Ctx: ctx}
}
// Return to success
func (r *Result) Success(data interface{}) {
if (data == nil) {
data = gin.H{}
}
res := ResultCont{}
res.Code = 0
res.Msg = ""
res.Data = data
r.Ctx.JSON(http.StatusOK,res)
}
// Return failed
func (r *Result)Error(code int,msg string) {
res := ResultCont{}
res.Code = code
res.Msg = msg
res.Data = gin.H{}
r.Ctx.JSON(http.StatusOK,res)
r.Ctx.Abort()
}
Four , The test results
1, To regenerate the doc, Under the project :
[email protected]:/data/liuhongdi/digv27$ /home/liuhongdi/go/bin/swag init
2021/02/03 16:49:59 Generate swagger docs....
2021/02/03 16:49:59 Generate general API Info, search dir:./
2021/02/03 16:49:59 Generating swag.ResultContGoods
2021/02/03 16:49:59 Generating model.Goods
2021/02/03 16:49:59 Generating swag.ResultContGoodsList
2021/02/03 16:49:59 create docs.go at docs/docs.go
2021/02/03 16:49:59 create swagger.json at docs/swagger.json
2021/02/03 16:49:59 create swagger.yaml at docs/swagger.yaml
2, visit :
http://localhost:8080/swagger/index.html#/return :

Look at the returned data :


5、 ... and , View the version of the library :
module github.com/liuhongdi/digv27
go 1.15
require (
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751
github.com/gin-gonic/gin v1.6.3
github.com/go-openapi/jsonpointer v0.19.5 // indirect
github.com/go-openapi/spec v0.19.13 // indirect
github.com/go-playground/validator/v10 v10.4.1 // indirect
github.com/golang/protobuf v1.4.3 // indirect
github.com/json-iterator/go v1.1.10 // indirect
github.com/mailru/easyjson v0.7.6 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/swaggo/files v0.0.0-20190704085106-630677cd5c14
github.com/swaggo/gin-swagger v1.3.0
github.com/swaggo/swag v1.6.9
github.com/ugorji/go v1.2.0 // indirect
golang.org/x/text v0.3.4 // indirect
google.golang.org/protobuf v1.25.0 // indirect
)
边栏推荐
- DQL basic query
- 挡不住了,国产芯片再度突进,部分环节已进到4nm
- [understanding by chance-37]: the structure of human sensory system determines that human beings are self-centered
- Anan's doubts
- Flutter动态化 | Fair 2.5.0 新版本特性
- 8 Queen question
- SQL Injection (POST/Search)
- Today's sleep quality record 77 points
- Unity Render Streaming通过Js与Unity自定义通讯
- SQL Injection (GET/Select)
猜你喜欢

PowerPoint 教程,如何在 PowerPoint 中將演示文稿另存為視頻?

Comprehensively develop the main channel of digital economy and digital group, and actively promote the utonmos digital Tibet market

Today's sleep quality record 77 points

Bidirectional linked list (we only need to pay attention to insert and delete functions)

Resource Cost Optimization Practice of R & D team

The solution of Chinese font garbled code in keil5

【电脑插入U盘或者内存卡显示无法格式化FAT32如何解决】

用户和组命令练习
![[机缘参悟-37]:人感官系统的结构决定了人类是以自我为中心](/img/06/b71b505c7072d540955fda6da1dc1b.jpg)
[机缘参悟-37]:人感官系统的结构决定了人类是以自我为中心

MySQL functions and related cases and exercises
随机推荐
SQL Injection (GET/Select)
PhpMyAdmin stage file contains analysis traceability
SwiftUI 开发经验之作为一名程序员需要掌握的五个最有力的原则
常见的几种最优化方法Matlab原理和深度分析
Spark实战1:单节点本地模式搭建Spark运行环境
JS 将伪数组转换成数组
编程内功之编程语言众多的原因
又一个行业被中国芯片打破空白,难怪美国模拟芯片龙头降价抛售了
MapReduce implements matrix multiplication - implementation code
Resource Cost Optimization Practice of R & D team
顺序表(C语言实现)
SVN添加文件时的错误处理:…\conf\svnserve.conf:12: Option expected
Red hat satellite 6: better management of servers and clouds
rxjs Observable filter Operator 的实现原理介绍
Unity Render Streaming通过Js与Unity自定义通讯
Sequence table (implemented in C language)
Logseq evaluation: advantages, disadvantages, evaluation, learning tutorial
[技术发展-24]:现有物联网通信技术特点
Resolved (error in viewing data information in machine learning) attributeerror: target_ names
The shadow of the object at the edge of the untiy world flickers, and the shadow of the object near the far point is normal