当前位置:网站首页>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/swag
Test the installation for success ?
[email protected]:/data/liuhongdi/digv27$ /home/liuhongdi/go/bin/swag -v
swag version v1.6.9
Include in project main.go File directory :
[email protected]:~/go$ cd /data/liuhongdi/digv27
[email protected]:/data/liuhongdi/digv27$ /home/liuhongdi/go/bin/swag init
You can see swag init The command creates the file :
docs/docs.go This file is used for development
docs/swagger.json
docs/swagger.yaml
3,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-swagger
install 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
)
边栏推荐
- Unity embeddedbrowser browser plug-in event communication
- Can newly graduated European college students get an offer from a major Internet company in the United States?
- Unity render streaming communicates with unity through JS
- User and group command exercises
- Unable to stop it, domestic chips have made another breakthrough, and some links have reached 4nm
- [quantitative trading] permanent portfolio, turtle trading rules reading, back testing and discussion
- MyCms 自媒体商城 v3.4.1 发布,使用手册更新
- RichView TRVStyle ListStyle 列表样式(项目符号编号)
- Static linked list (subscript of array instead of pointer)
- Comprehensively develop the main channel of digital economy and digital group, and actively promote the utonmos digital Tibet market
猜你喜欢
Unity embeddedbrowser browser plug-in event communication
Flutter动态化 | Fair 2.5.0 新版本特性
[bw16 application] instructions for firmware burning of Anxin Ke bw16 module and development board update
Introduction to the implementation principle of rxjs observable filter operator
MySQL functions and related cases and exercises
There is nothing new under the sun. Can the meta universe go higher?
Universal dividend source code, supports the dividend of any B on the BSC
When updating mysql, the condition is a query
mysql更新时条件为一查询
Logback log sorting
随机推荐
研发团队资源成本优化实践
实现CNN图像的识别和训练通过tensorflow框架对cifar10数据集等方法的处理
Setting up remote links to MySQL on Linux
Complete deep neural network CNN training with tensorflow to complete picture recognition case 2
pytorch 载入历史模型时更换gpu卡号,map_location设置
Spark practice 1: build spark operation environment in single node local mode
Stack application (balancer)
物联网毕设 --(STM32f407连接云平台检测数据)
PowerPoint 教程,如何在 PowerPoint 中将演示文稿另存为视频?
TensorBoard可视化处理案例简析
Error running 'application' in idea running: the solution of command line is too long
The principle of human voice transformer
Spark实战1:单节点本地模式搭建Spark运行环境
Halcon combined with C # to detect surface defects -- Halcon routine autobahn
Road construction issues
untiy世界边缘的物体阴影闪动,靠近远点的物体阴影正常
Comprehensive evaluation of double chain notes remnote: fast input, PDF reading, interval repetition / memory
Leetcode-1175.Prime Arrangements
The reasons why there are so many programming languages in programming internal skills
[how to earn a million passive income]