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

Go语言项目配置:同一端口4545同时运行Swagger UI与API服务

在Go项目同一端口同时运行API与Swagger UI的配置方案

核心逻辑是在同一个HTTP服务器实例上注册不同路径的路由:API路由处理根路径或业务子路径的请求,Swagger UI路由挂载到/docs路径下,这样同一端口就能同时响应两种请求。

以下是主流框架的具体实现:

1. 使用Gin框架

操作步骤:

  • 先安装Swagger相关依赖:
    go get github.com/swaggo/gin-swagger
    go get github.com/swaggo/files
    
  • 安装swag工具并生成项目Swagger文档:
    go install github.com/swaggo/swag/cmd/swag@latest
    swag init
    
  • 在主文件中同时注册API路由与Swagger路由:
package main

import (
    "github.com/gin-gonic/gin"
    swaggerFiles "github.com/swaggo/files"
    ginSwagger "github.com/swaggo/gin-swagger"
    _ "your-project/docs" // 替换为你的项目生成的docs包路径
)

// @title 你的API标题
// @version 1.0
// @description 你的API描述
// @host localhost:4545
// @BasePath /
func main() {
    r := gin.Default()

    // 注册业务API路由
    r.GET("/", func(c *gin.Context) {
        c.JSON(200, gin.H{"message": "API根路径"})
    })
    r.GET("/users", func(c *gin.Context) {
        c.JSON(200, gin.H{"data": []string{"user1", "user2"}})
    })

    // 注册Swagger UI路由,挂载到/docs路径
    r.GET("/docs/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))

    // 启动服务器监听4545端口
    r.Run(":4545")
}

启动后:

  • 访问http://localhost:4545触发API路由
  • 访问http://localhost:4545/docs打开Swagger UI

2. 使用标准库net/http

操作步骤:

  • 安装Swagger相关依赖:
    go get github.com/swaggo/http-swagger
    go get github.com/swaggo/files
    
  • 用swag init生成项目Swagger文档
  • 通过ServeMux管理多路径路由:
package main

import (
    "net/http"
    swaggerFiles "github.com/swaggo/files"
    httpSwagger "github.com/swaggo/http-swagger"
    _ "your-project/docs" // 替换为你的项目生成的docs包路径
)

// @title 你的API标题
// @version 1.0
// @description 你的API描述
// @host localhost:4545
// @BasePath /
func main() {
    mux := http.NewServeMux()

    // 注册API路由
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("API根路径"))
    })
    mux.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte(`{"data": ["user1", "user2"]}`))
    })

    // 注册Swagger UI路由
    mux.Handle("/docs/", httpSwagger.WrapHandler(swaggerFiles.Handler))

    // 启动服务器
    http.ListenAndServe(":4545", mux)
}

关键注意事项

  • 确保Swagger文档的@BasePath与实际API根路径一致,否则UI无法正确调用API接口
  • 避免路由冲突:不要将业务API路由设置为/docs或/docs/*,否则会覆盖Swagger路由
  • 禁止同时启动两个独立的HTTP服务器(比如一个跑API,一个跑Swagger),必须在同一个服务器实例上注册所有路由

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:41:30