当前位置:网站首页>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
)
边栏推荐
- Screenshot of the operation steps of upload labs level 4-level 9
- Complete deep neural network CNN training with tensorflow to complete picture recognition case 2
- Resource Cost Optimization Practice of R & D team
- mysql中的字段问题
- 8皇后问题
- The solution of Chinese font garbled code in keil5
- When updating mysql, the condition is a query
- This math book, which has been written by senior ml researchers for 7 years, is available in free electronic version
- 又一个行业被中国芯片打破空白,难怪美国模拟芯片龙头降价抛售了
- AI scores 81 in high scores. Netizens: AI model can't avoid "internal examination"!
猜你喜欢

SQL Injection (POST/Select)

PowerPoint 教程,如何在 PowerPoint 中将演示文稿另存为视频?

Kivy教程之 盒子布局 BoxLayout将子项排列在垂直或水平框中(教程含源码)
![[quantitative trading] permanent portfolio, turtle trading rules reading, back testing and discussion](/img/3b/28327bbf5eb19254f03500a41e2adb.jpg)
[quantitative trading] permanent portfolio, turtle trading rules reading, back testing and discussion

The principle of human voice transformer

Halcon combined with C # to detect surface defects -- Halcon routine autobahn

rxjs Observable filter Operator 的实现原理介绍

This math book, which has been written by senior ml researchers for 7 years, is available in free electronic version

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

Comprehensive evaluation of double chain notes remnote: fast input, PDF reading, interval repetition / memory
随机推荐
SQL Injection (POST/Select)
The latest BSC can pay dividends. Any B usdt Shib eth dividend destruction marketing can
Unity render streaming communicates with unity through JS
父亲和篮球
【被动收入如何挣个一百万】
软件测试工作那么难找,只有外包offer,我该去么?
Kivy tutorial how to automatically load kV files
Anan's doubts
Spark实战1:单节点本地模式搭建Spark运行环境
记录关于银行回调post请求405 问题
Golang — 命令行工具cobra
树的深入和广度优先遍历(不考虑二叉树)
MapReduce implements matrix multiplication - implementation code
Realize the recognition and training of CNN images, and process the cifar10 data set and other methods through the tensorflow framework
Kivy教程之 盒子布局 BoxLayout将子项排列在垂直或水平框中(教程含源码)
8 Queen question
php 迷宫游戏
Flutter动态化 | Fair 2.5.0 新版本特性
栈应用(平衡符)
Red hat satellite 6: better management of servers and clouds