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

Docker+Swaggo v2环境下Swagger UI生成畸形请求URL的解决方法

问题:Swaggo v2生成OpenAPI3文档后Swagger UI请求URL畸形

环境与配置

Go项目Swaggo注解

// @title           project
// @version         1.0
// @host            localhost:4000
// @BasePath        /v1
// @securitydefinitions.bearerauth BearerAuth

生成的swagger.yml片段

...
openapi: 3.1.0
servers:
 - url: localhost:4000/v1

Docker Compose运行Swagger UI配置

services:
  swagger-ui:
    image: swaggerapi/swagger-ui:v5.19.0
    ports:
      - "8080:8080"
    environment:
      - URL=http://localhost:4000/docs/swagger.json  # 可从宿主机访问

问题现象

通过Swagger UI执行请求时,生成的URL出现畸形,例如:localhost://localhost:40004000/v1/healthcheck。移除@host注解可解决该问题,但会使用默认主机/端口,不符合需求。

解决方案

方法1:修改@host注解,添加协议前缀

在@host注解中明确指定协议(如http://),让Swaggo生成包含完整协议的servers URL:

// @title           project
// @version         1.0
// @host            http://localhost:4000  // 添加http://协议
// @BasePath        /v1
// @securitydefinitions.bearerauth BearerAuth

重新生成文档后,swagger.yml中的servers配置会变为:

...
openapi: 3.1.0
servers:
 - url: http://localhost:4000/v1

此时Swagger UI会基于这个完整的基础URL构造请求,不会出现拼接错误。

方法2:通过Swaggo生成参数指定完整服务器URL

如果不想修改代码注解,可在执行swag init时添加--host参数指定包含协议的完整地址:

swag init --host http://localhost:4000

该参数会覆盖代码中的@host注解配置,生成正确的servers URL。

方法3:调整Swagger UI配置(备选)

在Docker Compose的Swagger UI服务中添加BASE_URL环境变量,强制指定基础路径,但此方法优先级低于OpenAPI文档中的servers配置,建议优先使用前两种方法:

services:
  swagger-ui:
    image: swaggerapi/swagger-ui:v5.19.0
    ports:
      - "8080:8080"
    environment:
      - URL=http://localhost:4000/docs/swagger.json
      - BASE_URL=http://localhost:4000/v1

内容的提问来源于stack exchange,提问作者Kingindanord

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 18:23:12