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

go-swagger如何从代码生成security部分的多个必填请求头?

解决Swagger Meta注解生成"与"关系Security的问题

你遇到的核心问题是注解使用方式错误,导致swagger generate spec生成了"或"关系的security配置。要实现两个请求头的"与"验证,需要按以下步骤调整:

1. 正确定义两个独立的Security Scheme

首先在代码中分别为两个请求头定义ApiKey类型的Security Scheme:

// swagger:security authorization1
// SecurityScheme:
//   type: apiKey
//   in: header
//   name: authorization1

// swagger:security authorization2
// SecurityScheme:
//   type: apiKey
//   in: header
//   name: authorization2

2. 在接口上用同一Security块引用两个Scheme

关键是不要分开写两个swagger:security注解,而是在同一个Security:块中同时指定两个Scheme:

// swagger:route GET /your/api/path example getExample
// Security:
//   authorization1: []
//   authorization2: []
// Responses:
//   200: ExampleResponse

这样生成的swagger.json中security部分会是你期望的"与"关系:

"security": [
  {
    "authorization1": [],
    "authorization2": []
  }
]

常见错误点

  • 你之前可能在接口上分开写了两个swagger:security注解,比如:
    // swagger:security authorization1
    // swagger:security authorization2
    
    这种写法会被swagger解析为两个独立的security规则,也就是"或"关系,导致生成的spec中出现两个独立对象。
  • 另外要确保swagger generate spec命令正确扫描到所有包含注解的文件,比如使用-o swagger.json指定输出路径,或用-scan-models包含模型定义。

内容的提问来源于stack exchange,提问作者David Michael Gang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 17:45:06