gin-swagger 安装&使用手册&问题

官方地址

https://github.com/swaggo/gin-swagger

安装教程

#!/bin/bash
# install swag
go get -u github.com/swaggo/swag/cmd/swag

#Download gin-swagger by using:
go get -u github.com/swaggo/gin-swagger
go get -u github.com/swaggo/files
  • init
swag init

特别提醒

swag 之后会默认生成docs目录,请在项目中导入

import _ "Your/Project/RootPath/docs"

API信息

官方文档: https://swaggo.github.io/swaggo.io/declarative_comments_format/

快速上手

gin-swagger

import (
	_ "Your/Project/RootPath/docs"
	"github.com/gin-gonic/gin"
	ginSwagger "github.com/swaggo/gin-swagger"
	"github.com/swaggo/gin-swagger/swaggerFiles"
)
// @title ioc api
// @version v0.0.1
// @description null
// @termsOfService http://swagger.io/terms/
// @contact.name puhao
// @contact.url puhao
// @contact.email puhao
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host 0.0.0.0:8989
// @BasePath
func main() {

	r := gin.Default()
  r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	r.Run("0.0.0.0:8989")
}

API Info

// Login godoc
// @Summary login with user and password, get token
// @Tags login
// @version 1.0
// @Accept application/x-json-stream
// @Param user query string true "user name"
// @Param pd query string true "user's password"
// @Router /openapi/login [get]
// @Success 200 {object} YOURObject "{"code":200,"data": {"token": ""},"msg":""}"
// @Failure 403 {object} YOURObject {"code":200,"data":null,"msg":""}
func Login(c *gin.Context) {
   //...Your logic

}

遇到的问题

Type definition of type ‘*ast.InterfaceType’ is not supported yet. Using ‘object’ instead.

go get -u github.com/swaggo/swag/cmd/swag@v1.6.7

Failed to load spec. (同时会有panic信息)

import _ "Your/Project/RootPath/docs"

TypeError: Failed to fetch

摁F12,看报错详情,一般会有 has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’,那么这是跨域问题

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐