从 Swagger/OpenAPI 规范在 Go 中生成 Swagger 文档服务器

问题描述

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

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

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

谢谢。

解决方法

您可以在 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

,

我不确定 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)))

    ...
,

有一个库将 Swagger UI 打包为 Go http.Handlerhttps://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。