golang--swagger集成

# $GOROOT/bin下会发现swag二进制文件
go install github.com/swaggo/swag/cmd/swag@latest
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files

main.go文件

在包含main.go文件的项目根目录运行swag init。这将会解析注释并生成docs/docs.go和swagger所需的文件,最后引用docs_ “proj/docs”,proj是项目名。

package main
import (
_ "proj/docs"
	"github.com/gin-gonic/gin"
	ginSwagger "github.com/swaggo/gin-swagger"
	swaggerFiles "github.com/swaggo/files"
	)
// @title afaffaapi
// @version 1.0
func main() {
 engine := gin.Default()

 url := ginSwagger.URL("/swagger/doc.json")
 engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url))

 _ = engine.Run(":8081")
}

现在访问http://localhost:8081/swagger/index.html就会看到熟悉的swagger ui页面
在这里插入图片描述

API

package api

import "github.com/gin-gonic/gin"

type healthApi struct{}

// @Summary 健康监测
// @Description 健康监测
// @Tags 健康监测
// @Success 200 {string} string
// @Router /health [get]
func (ha *healthApi) Health(c *gin.Context) {
	c.JSON(200, "ok")
}
package query

type AbnormityQuery struct {
	SensorId      uint   `form:"sensorId"`
	LineId        uint   `form:"lineId"`
	StartDate     string `form:"startDate"`
	EndDate       string `form:"endDate"`
	AbnormityType bool   `form:"abnormityType"`
}
package response

type Response struct {
	Data interface{} `json:"data"`
	Msg  string      `json:"msg"`
}
func Result(code int, data interface{}, msg string, c *gin.Context) {
	c.JSON(code, Response{
		data,
		msg,
	})
}

自定义的vo结构体[get]


// @Summary 异常信息
// @Description 根据线路id,传感器id,日期区间,是否是线路或传感器异常异常数据
// @Tags 异常信息
// @Param object query  query.AbnormityQuery true "查询参数"
// @Success 200 {object} response.Response
// @Failure 200 {object} response.Response
// @Router /abnormity/getRecordBySensorIdAndDate [get]
func (aa *abnormityApi) GetRecordBySensorIdAndDate(c *gin.Context) {
	var q query.AbnormityQuery

	if err := c.ShouldBindQuery(&q); err == nil {
		result := service.AbnormityService.GetRecordBySensorIdAndDate(q.SensorId, q.LineId, q.StartDate, q.EndDate, q.AbnormityType)
		response.Result(http.StatusOK, result, "查询成功", c)
	} else {
		response.Result(http.StatusOK, nil, "参数错误", c)
	}
}

自定义的vo结构体[post]

// @Summary 传感器
// @Description 添加多个线路数据
// @Tags 传感器
// @Param object body query.SensorArrayQuery true "线路信息集合"
// @Success 200 {object} response.Response
// @Failure 200 {object} response.Response
// @Router /sensor/addRecords [post]
func (sa *sensorApi) AddRecords(c *gin.Context) {
	var recordQuray query.SensorArrayQuery
	if err := c.ShouldBindJSON(&recordQuray); err != nil {
		_, _ = fmt.Println("ShouldBindJSON ERR:", err)
		response.Result(http.StatusBadRequest, nil, "参数错误!", c)
	} else {
		if err := service.SensorService.AddRecords(recordQuray); err != nil {
			response.Result(http.StatusInternalServerError, nil, "数据添加错误", c)
		} else {
			response.Result(http.StatusOK, nil, "添加成功", c)
		}
	}
}

每次重新配置swagger之后,就重新执行 swag init

Tags

用来给API分组

Accept

接收的参数类型,支持表单(mpfd) 和 JSON(json)

Produce

返回的数据结构,一般都是json, 其他支持如下表:

Mime Type声明
application/jsonjson
text/xmlxml
text/plainplain
htmlhtml
multipart/form-datampfd
application/x-www-form-urlencodedx-www-form-urlencoded
application/vnd.api+jsonjson-api
application/x-json-streamjson-stream
application/octet-streamcotet-stream
image/pngpng
image/jpegjpeg
image/gifgif

Param

参数,从前往后分别是:

@Param 1.参数名 2.参数类型 3.参数数据类型 4.是否必须 5.参数描述 6.其他属性

参数类型

  • header

  • body
    参数类型主要有三种:

  • path 该类型参数直接拼接在URL中,如Demo中HandleGetFile:

@Param id path integer true "文件ID"
  • query 该类型参数一般是组合在URL中的
@Param who query string true "人名"
  • formData 该类型参数一般是POST,PUT方法所用,
@Param user formData string true "用户名 default(admin)

参数数据类型

数据类型主要支持一下几种:

  • string (string)
  • integer (int, uint, uint32, uint64)
  • number (float32)
  • boolean (bool)
  • user defined struct
    注意,如果你是上传文件可以使用file, 但参数类型一定是formData, 如下:
@Param file formData file true "文件"

是否是必须

表明该参数是否是必须需要的,必须的在文档中会黑体标出,测试时必须填写。

参数描述

就是参数的一些说明

其他属性

Success

指定成功响应的数据。格式为:

 @Success 1.HTTP响应码 {2.响应参数类型} 3.响应数据类型 4.其他描述

响应参数类型 / 3.响应数据类型

返回的数据类型,可以是自定义类型,可以是json。

  • 自定义类型
    在平常的使用中,我都会返回一些指定的模型序列化JSON的数据,这时,就可以这么写:
@Success 200 {object} main.File

其中,模型直接用包名.模型即可。你会说,假如我返回模型数组怎么办?这时你可以这么写:

@Success 200 {anrry} main.File
  • json
    将如你只是返回其他的json数据可如下写:
@Success 200 {string} json ""

Router

指定路由与HTTP方法。格式为:

@Router /path/to/handle [HTTP方法]

​ 不用加基础路径

参考资料

swaggo
github
swaggo-Go文档

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值