Golang中Swagger枚举输入参数的注解使用指南
Golang中Swagger枚举输入参数的注解使用指南
我正在尝试为Go代码添加注解,以便能够自动生成 swagger.yaml 文件(使用命令 swagger generate spec -o ./swagger.yaml --scan-models)。遗憾的是,我未能找到一个注解示例,其中REST调用期望一个字符串类型的输入参数,并且其值被限制在特定的值列表中。
如果我的理解正确(使用 swagger serve -F=swagger swagger.yaml 命令),界面上应该会有一个下拉菜单,包含这三个字符串值(containers/bundles/web),用户需要从中选择一个来发起REST调用。之前,我参考了这份文档来为输入参数创建注解。
希望找到一些代码示例。
更多关于Golang中Swagger枚举输入参数的注解使用指南的实战教程也可以访问 https://www.itying.com/category-94-b0.html
更多关于Golang中Swagger枚举输入参数的注解使用指南的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Go语言中,使用Swagger注解为REST API参数定义枚举值,可以通过swaggo/swag库的// @Param注解配合enum标签实现。以下是一个完整的示例,展示如何为字符串类型的查询参数或路径参数添加枚举约束:
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
// GetItems 处理GET请求,type参数必须是枚举值之一
// @Summary 获取项目列表
// @Description 根据类型过滤项目
// @Tags items
// @Accept json
// @Produce json
// @Param type query string true "项目类型" Enums(containers, bundles, web)
// @Success 200 {object} map[string]interface{}
// @Router /items [get]
func GetItems(c *gin.Context) {
itemType := c.Query("type")
c.JSON(http.StatusOK, gin.H{
"type": itemType,
"items": []string{"item1", "item2"},
})
}
// GetItemByType 处理路径参数中的枚举值
// @Summary 根据类型获取项目
// @Description 获取指定类型的项目详情
// @Tags items
// @Accept json
// @Produce json
// @Param type path string true "项目类型" Enums(containers, bundles, web)
// @Success 200 {object} map[string]interface{}
// @Router /items/{type} [get]
func GetItemByType(c *gin.Context) {
itemType := c.Param("type")
c.JSON(http.StatusOK, gin.H{
"type": itemType,
"data": "项目详情",
})
}
func main() {
r := gin.Default()
r.GET("/items", GetItems)
r.GET("/items/:type", GetItemByType)
r.Run(":8080")
}
对于请求体(JSON body)中的枚举字段,需要在结构体字段的注释中使用enums标签:
package main
// CreateItemRequest 创建项目的请求体
type CreateItemRequest struct {
// 项目名称
Name string `json:"name" example:"示例项目"`
// 项目类型,必须是枚举值之一
// 枚举值: containers, bundles, web
Type string `json:"type" enums:"containers,bundles,web"`
}
// CreateItem 处理POST请求
// @Summary 创建新项目
// @Description 创建指定类型的新项目
// @Tags items
// @Accept json
// @Produce json
// @Param request body CreateItemRequest true "请求体"
// @Success 200 {object} map[string]interface{}
// @Router /items [post]
func CreateItem(c *gin.Context) {
var req CreateItemRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{
"name": req.Name,
"type": req.Type,
})
}
生成Swagger文档的命令:
# 安装swag工具
go install github.com/swaggo/swag/cmd/swag@latest
# 生成swagger.yaml
swag init -o ./docs --outputTypes yaml
# 或者直接生成swagger.yaml(根据你的项目结构调整)
swag generate spec -o ./swagger.yaml --scan-models
生成的Swagger文档中,枚举参数会显示为下拉选择框。对于查询参数和路径参数,使用Enums(value1, value2, value3)语法;对于结构体字段,使用enums:"value1,value2,value3"标签。

