微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Swagger UI 仍在显示示例

如何解决Swagger UI 仍在显示示例

我想在 Go 和 Gin 的 RESTFul API 文档中使用 Swagger。

我在 main.go 中有这个代码: 包主

import (
    "gowebservice/config"
    "gowebservice/controllers"

    "github.com/gin-gonic/gin"
    swaggerFiles "github.com/swaggo/files"
    ginSwagger "github.com/swaggo/gin-swagger"

    _ "github.com/swaggo/gin-swagger/example/basic/docs"
)

// @title Students API
// @version 1.0
// @description This is a basic API Students using Gin and Gorm.

// @host localhost:8080
// @BasePath /

func main() {
    r := gin.Default()

    config.ConnectDatabase()

    v1 := r.Group("/api/v1")
    {
        v1.GET("students/all",controllers.GetStudents)
    }

    r.GET("/swagger/*any",ginSwagger.WrapHandler(swaggerFiles.Handler))

    r.Run()
}

这是我的具有 GET 方法的端点:

package controllers

import (
    "gowebservice/config"
    "gowebservice/models"
    "net/http"

    "github.com/gin-gonic/gin"
)

// GetStudents godoc
// @Summary Show a list of students
// @Accept  json
// @Produce  json
// @Router /students [get]
func GetStudents(c *gin.Context) {
    var students []models.Student

    if err := config.DB.Find(&students).Error; err != nil {
        c.JSON(http.StatusBadRequest,gin.H{"error": "Record not found!"})
        return
    }
    c.JSON(http.StatusOK,students)
}

当我使用 swag initgo run main.go 时,Swagger UI 仍然显示示例而不是我的端点。

enter image description here

有人可以帮我吗?

解决方法

我也遇到了这个?

问题是我们导入了基本的示例文档:

import (
    ...

    _ "github.com/swaggo/gin-swagger/example/basic/docs"
)

您需要将其更改为由 swag init 生成的 docs 包。 假设您的模块名称为 gowebservice,则:

import (
    ...

    _ "gowebservice/docs"
)

在那之后运行 go run main.go 应该会让 Swagger UI 找到您自己的文档! :D

,

这些文件是否已经生成?

docs.go      swagger.json swagger.yaml
 swag help init
NAME:
   swag init - Create docs.go

USAGE:
   swag init [command options] [arguments...]

OPTIONS:
   --generalInfo value,-g value       Go file path in which 'swagger general API Info' is written (default: "main.go")
   --dir value,-d value               Directory you want to parse (default: "./")
   --propertyStrategy value,-p value  Property Naming Strategy like snakecase,camelcase,pascalcase (default: "camelcase")
   --output value,-o value            Output directory for all the generated files(swagger.json,swagger.yaml and doc.go) (default: "./docs")
   --parseVendor                       Parse go files in 'vendor' folder,disabled by default
   --parseDependency                   Parse go files in outside dependency folder,disabled by default
   --markdownFiles value,--md value   Parse folder containing markdown files to use as description,disabled by default
   --generatedTime                     Generate timestamp at the top of docs.go,true by default

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。