当前位置:网站首页>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
)
边栏推荐
- User and group command exercises
- SQL Injection (AJAX/JSON/jQuery)
- Mysql:insert date:SQL 错误 [1292] [22001]: Data truncation: Incorrect date value:
- [556. Next larger element III]
- When updating mysql, the condition is a query
- 太阳底下无新事,元宇宙能否更上层楼?
- Brief analysis of tensorboard visual processing cases
- Error handling when adding files to SVN:.... \conf\svnserve conf:12: Option expected
- ThreadPoolExecutor realizes multi-threaded concurrency and obtains the return value (elegant and concise way)
- Mobile phones and computers can be used, whole people, spoof code connections, "won't you Baidu for a while" teach you to use Baidu
猜你喜欢

Screenshot of the operation steps of upload labs level 4-level 9

Ocean CMS vulnerability - search php

Internet of things completion -- (stm32f407 connects to cloud platform detection data)

The principle of human voice transformer

用户和组命令练习

JVM系列——概述,程序计数器day1-1
![[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

SQL Injection (GET/Select)

CVPR 2022 | interpretation of 6 excellent papers selected by meituan technical team

MySQL constraints
随机推荐
Leetcode-1175.Prime Arrangements
Spark实战1:单节点本地模式搭建Spark运行环境
Complete deep neural network CNN training with tensorflow to complete picture recognition case 2
Golang — 命令行工具cobra
[how to solve FAT32 when the computer is inserted into the U disk or the memory card display cannot be formatted]
[quantitative trading] permanent portfolio, turtle trading rules reading, back testing and discussion
8 Queen question
栈应用(平衡符)
Libuv库 - 设计概述(中文版)
全面发展数字经济主航道 和数集团积极推动UTONMOS数藏市场
[how to earn a million passive income]
Unable to stop it, domestic chips have made another breakthrough, and some links have reached 4nm
顺序表(C语言实现)
【被动收入如何挣个一百万】
mysql更新时条件为一查询
MySQL constraints
Logseq 评测:优点、缺点、评价、学习教程
实现CNN图像的识别和训练通过tensorflow框架对cifar10数据集等方法的处理
MySQL installation, uninstallation, initial password setting and general commands of Linux
Box layout of Kivy tutorial BoxLayout arranges sub items in vertical or horizontal boxes (tutorial includes source code)