当前位置:网站首页>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
)
边栏推荐
- 研发团队资源成本优化实践
- Spark practice 1: build spark operation environment in single node local mode
- 太阳底下无新事,元宇宙能否更上层楼?
- SVN添加文件时的错误处理:…\conf\svnserve.conf:12: Option expected
- 【被动收入如何挣个一百万】
- Use docker to build sqli lab environment and upload labs environment, and the operation steps are provided with screenshots.
- Red hat satellite 6: better management of servers and clouds
- 服务器硬盘冷迁移后网卡无法启动问题
- Resolved (error in viewing data information in machine learning) attributeerror: target_ names
- The network card fails to start after the cold migration of the server hard disk
猜你喜欢

双向链表(我们只需要关注插入和删除函数)

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

DQL basic query

太阳底下无新事,元宇宙能否更上层楼?

Logback log sorting

Golang — 命令行工具cobra

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

Logseq evaluation: advantages, disadvantages, evaluation, learning tutorial

SQL Injection (AJAX/JSON/jQuery)
![[技術發展-24]:現有物聯網通信技術特點](/img/f3/a219fe8e7438b8974d2226b4c3d4a4.png)
[技術發展-24]:現有物聯網通信技術特點
随机推荐
[développement technologique - 24]: caractéristiques des technologies de communication Internet des objets existantes
常见的几种最优化方法Matlab原理和深度分析
树的深入和广度优先遍历(不考虑二叉树)
Mobile phones and computers can be used, whole people, spoof code connections, "won't you Baidu for a while" teach you to use Baidu
The latest BSC can pay dividends. Any B usdt Shib eth dividend destruction marketing can
Brief analysis of tensorboard visual processing cases
JVM系列——概述,程序计数器day1-1
Internet of things completion -- (stm32f407 connects to cloud platform detection data)
Heap structure and heap sort heapify
Students who do not understand the code can also send their own token, which is easy to learn BSC
Kivy教程之 盒子布局 BoxLayout将子项排列在垂直或水平框中(教程含源码)
MySQL installation, uninstallation, initial password setting and general commands of Linux
ThreadPoolExecutor realizes multi-threaded concurrency and obtains the return value (elegant and concise way)
Logseq 评测:优点、缺点、评价、学习教程
Flutter dynamic | fair 2.5.0 new version features
php 迷宫游戏
The difference between stratifiedkfold (classification) and kfold (regression)
windos 创建cordova 提示 因为在此系统上禁止运行脚本
The network card fails to start after the cold migration of the server hard disk
IBEM mathematical formula detection data set