【发布时间】:2022-11-24 17:12:56
【问题描述】:
我正在尝试使用 swag init 生成 swagger.json。这是我的代码:
package main
import (
_ "album/docs"
"context"
"fmt"
"net/http"
"os"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
)
// album represents data about a record album.
// @title Gin Album Service
// @version 1.0
// @description A albums management service API in Go using Gin framework.
// @termsOfService https://example.dev
// @contact.name Santosh Kumar
// @contact.url https://twitter.com/example
// @contact.email example@gmail.com
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /
func main() {
<some code>
}
// GetAlbums godoc
// @Summary Retrieves user based on given ID
// @Produce json
// @Router /albums/ [get]
func GetAlbums(c *gin.Context) {
<some code>
}
然后
赃物初始化我有 swagger.json 文件:
{
"swagger": "2.0",
"info": {
"description": "A albums management service API in Go using Gin framework.",
"title": "Gin Album Service",
"termsOfService": "https://example.dev",
"contact": {
"name": "Santosh Kumar",
"url": "https://twitter.com/example",
"email": "example@gmail.com"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
},
"version": "1.0"
},
"host": "localhost:8080",
"basePath": "/",
"paths": {}
}
为什么“路径”是空的?我对 GetAlbums 的注释有什么问题?
看来我按照来源做了一切:https://github.com/swaggo/swag
【问题讨论】:
-
GetAlbums上面的评论对我有用。/albums/出现在我的swagger.json-paths中。我需要有关您的代码的更多详细信息。 -
swag.exe 版本 v1.8.6 可能是 swag 版本的问题? GetAlbum 只是返回所有专辑的 json 的函数
func GetAlbums(c *gin.Context) { rows, err := conn.Query(context.Background(), "select * from \"Album\"") if err != nil { fmt.Println("err - ", err) return } var res = []album{} var al album for rows.Next() { err := rows.Scan(&al.ID, &al.Title, &al.Artist, &al.Price) if err != nil { return } res = append(res, al) } c.IndentedJSON(http.StatusOK, res) } -
不,我指的是
main函数或者你设置的ruote函数。我使用swag version v1.8.4。 -
我尝试了不同的选择。在我看来,函数的内容与 swag init 无关。或者不是吗?
func main() { var err error conn, err = pgx.Connect(context.Background(), "postgres://postgres:1234@localhost:5432/albums") if err != nil { fmt.Println("Unable to connect to database", err) os.Exit(1) } else { fmt.Println("db ok") } defer conn.Close(context.Background()) router := gin.Default() router.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) router.GET("/albums", GetAlbums) router.Run("localhost:8080") }