You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go-Swagger生成Swagger.yaml时产品响应类型显示为array[any]问题求助

解决go-swagger识别响应为array[any]的问题

我用Golang开发REST API,采用go-swagger注释生成接口文档,但生成的swagger.yaml中,productsResponse的响应类型被识别为array[any],而非预期的Product数组。

问题代码

go.docs代码

// A list of products
// swagger:response productsResponse
type productsResponseWrapper struct {
    // All current products EXAMPLE
    // in: body

    // Required: true
    // Example: Expected type int
    Body []data.Product
}

get.go代码

// swagger:route GET /products products listProducts
// Return a list of products from the database
// responses:
//   200: productsResponse

// ListAll handles GET requests and returns all current products
func (p *Products) GetProducts(rw http.ResponseWriter, _ *http.Request) {
    p.l.Println("Get Product")
    lp := data.GetProducts()
    if err := lp.ToJson(rw); err != nil {
        http.Error(rw, "Unable to marshal json", http.StatusInternalServerError)
        return
    }
}

data/product.go代码

// Product defines the structure for an API product
// swagger:model Product
type Product struct {
    // the id of the user
    //
    // required: true
    // min: 1
    ID          int     `json:"id"`
    Name        string  `json:"name" validate:"required"`
    Description string  `json:"description"`
    Price       float32 `json:"price" validate:"gt=0"`
    SKU         string  `json:"sku" validate:"required,sku"`
    CreatedOn   string  `json:"-"`
    UpdatedOn   string  `json:"-"`
    DeletedOn   string  `json:"-"`
}

生成的错误swagger.yaml片段

productsResponse:
    description: A list of products
    headers:
        Body:
            description: 'Required: true'
            example: Expected type int
            items: {}
            type: array

问题原因

  1. 注释格式错误:Body字段的注释中,// in: body与后续的// Required: true之间存在空行,导致go-swagger解析错误,将Body识别为请求头而非响应体内容。
  2. 示例值不符合类型:Example字段的值为Expected type int,与[]data.Product类型完全不匹配,干扰了类型识别。

解决方案

修正响应结构体的注释格式

确保Body字段的swagger注释标签连续,无空行分隔,并修正示例值为符合Product数组的格式:

// A list of products
// swagger:response productsResponse
type productsResponseWrapper struct {
    // All current products
    // in: body
    // Required: true
    // Example: [{"id":1,"name":"Sample Product","description":"A sample product","price":9.99,"sku":"ABC123"}]
    Body []data.Product
}

重新生成swagger文档

执行go-swagger生成命令(如swagger generate spec -o ./swagger.yaml),此时生成的swagger.yaml中,productsResponse会正确识别响应体为Product数组:

productsResponse:
    description: A list of products
    schema:
        type: array
        items:
            $ref: '#/definitions/Product'

内容的提问来源于stack exchange,提问作者Guy-Arieli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 08:22:24