【问题标题】:Generate Swagger documentation server in Go from Swagger/OpenAPI specification根据 Swagger/OpenAPI 规范在 Go 中生成 Swagger 文档服务器
【发布时间】:2021-05-26 03:14:06
【问题描述】:

我有一个 OpenAPI 规范,并且我使用了 openapi-generator 来生成 Golang gin 服务器。

从 OpenAPI 规范生成 Swagger 文档服务器的常规方法是什么?

我已经尝试过swag:它会在 http://localhost:8080/swagger/index.html 端点上生成文档。但这需要在代码注释中描述 API。我正在寻找我已经拥有的 OpenAPI 规范中的 Swagger UI 生成器。

谢谢。

【问题讨论】:

  • 你是什么意思“来自开放 API 规范的招摇接口”? Swagger 是 OpenAPI 的旧 2.0 名称。 OpenAPI 用于 3.0 以后的版本。

标签: go swagger openapi go-gin


【解决方案1】:

有一个库将 Swagger UI 打包为 Go http.Handler: https://github.com/swaggest/swgui

package main

import (
    "net/http"

    "github.com/swaggest/swgui/v3emb" // For go1.16 or later.
    // "github.com/swaggest/swgui/v3" // For go1.15 and below.
)

func main() {
    http.Handle("/", v3.NewHandler("My API", "/swagger.json", "/"))
    http.ListenAndServe(":8080", nil)
}

"/swagger.json" 在此示例中是 OpenAPI 规范文件的 URL。

【讨论】:

    【解决方案2】:

    我不确定 Gin,但我很高兴分享我的解决方案(基于 go-server):

    1. 在项目根目录中创建一个名为 ./swagger-ui 的目录
    2. 将swagger-ui (https://github.com/swagger-api/swagger-ui/tree/master/dist)的dist/*下的文件复制到这里
    3. swagger-ui/index.html 中将 api 规范的位置更新为url: "/api/openapi.yaml"
    4. main.go 中创建一个带有//go:embed swagger-ui/* api/openapi.yaml 注释的新变量(后一个目录由openapi-generator CLI 创建)
    5. main.go中的(生成的)路由器下方添加:router.PathPrefix("/").Handler(http.FileServer(http.FS(staticFiles)))

    就是这样 - 您将在 /swagger-ui 下获得 Swagger UI,并从 /api/openapi.yaml 自动加载 api 定义

    package main
    
    import (
        "context"
        ...
    )
    
    //go:embed swagger-ui/* api/openapi.yaml
    var staticFiles embed.FS
    
    func main() {
        router := ....
    
        // Embed the Swagger UI within Go binary
        router.PathPrefix("/").Handler(http.FileServer(http.FS(staticFiles)))
    
        ...
    

    【讨论】:

      【解决方案3】:

      您可以在 docker 容器中运行 swagger 编辑器。从https://hub.docker.com/r/swaggerapi/swagger-editor 拉取它,运行它,将浏览器指向 http://localhost:8080,然后加载 api.yaml 文件。你也可以运行 swagger ui https://hub.docker.com/r/swaggerapi/swagger-ui

      【讨论】:

        猜你喜欢
        • 2021-10-24
        • 1970-01-01
        • 1970-01-01
        • 2018-03-02
        • 1970-01-01
        • 1970-01-01
        • 2019-09-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多