swaggo / gin-swagger Goto Github PK
View Code? Open in Web Editor NEWgin middleware to automatically generate RESTful API documentation with Swagger 2.0.
License: MIT License
gin middleware to automatically generate RESTful API documentation with Swagger 2.0.
License: MIT License
example in swagger:
model.Menu{
active string
description string
icon string
id string
name string
pid string
slug string
sort integer
url string
}
define in struct:
ID string
PID string
Name string
Icon string
Slug string
URL string
Active string
Description string
Sort int
it's not the same orders
how can i set to display in swagger with the same order with struct define
Success respond api comment:
// ...
// @Success 200 {object} utils.UserList
// ...
Success respond object:
type UserList struct {
Message string `json:"message" example:"OK"`
Code int `json:"code" example:"200"`
Data []struct {
Userid string `json:"userid" example:"userid"`
Name string `json:"name" example:"name"`
Mobile string `json:"mobile" example:"17371266666"`
Email string `json:"email" example:"ahsudhoa@jzdbcadg"`
Status int `json:"status" example:"ausgduga"`
Avatar string `json:"avatar" example:"http://p.qlogo.cn/bizmail/LIdibicNn9rcMNTXq4HzI8vkYib9XvU4H1mTgIonBt5gy4ibLNtuu"`
Telephone string `json:"telephone" example:""`
EnglishName string `json:"english_name" example:"fred"`
} `json:"data"`
}
Question:
Is there any way to use struct slices in respond object, without breaking models preview in webpages?
Hello,
Having this issue - No operations defined in spec!
json file is accessiable: http://localhost:8081/swagger/doc.json
{
"swagger": "2.0",
"info": {
"description": "This is a sample server Petstore server.",
"title": "Test api",
"termsOfService": "http://swagger.io/terms/",
"contact": {
"name": "API Support",
"url": "http://www.swagger.io/support",
"email": "[email protected]"
},
"license": {
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
},
"version": "1.0.0"
},
"host": "localhost:8081",
"basePath": "/api",
"paths": {}
}
I don't see any paths though.
Api itself works just fine.
Is there a way to debug this?
Thanks!
I am getting error Failed to load spec.
when I import docs package like myProject/docs
(Internal Server Error),
but when I import github.com/swaggo/swag/example/basic/docs
it is working properly, can anyone suggest what i'm doing wrong?
Since the addition of configuration while creating a handler, the default value of defaultConfig.URL
will break all services that has a custom hostname.
Through experiments, using swagger/doc.json
would be a better default url than http://localhost:8080/swagger/doc.json
.
this works: go get github.com/swaggo/swag/cmd/swag
but the swag-command doesn't work in the windows-cmd
for these both i get an error:
go get -u github.com/swaggo/gin-swagger --> package github.com/swaggo/gin-swagger: remote origin not found
go get -u github.com/swaggo/gin-swagger/swaggerFiles --> go get -u github.com/swaggo/gin-swagger/swaggerFiles
and internet is working
"hds/motion/vendor/" is my package
don't know if is a gin or a swag problem
When returning to an object:ImgWorkRes, if there is a struct: ImgWorkRes in the object, swag will not parse the contents of the struct:ImgWorkRes.
for example:
my code
type ImgWorkRes struct {
models.Work
CanLike bool json:"can_like"
CanFollow bool json:"can_follow"
CanCollect bool json:"can_collect"
}
// @summary 获取作品详情
// @produce json
// @param id path int true "作品id 默认 0"
// @param token query string false "token"
// @success 200 {object} v1.ImgWorkRes "成功"
// @failure 400 {object} e.HTTPError "客户端请求错误"
// @failure 401 {object} e.HTTPError "授权错误"
// @failure 422 {object} e.HTTPError "字段验证错误"
// @failure 404 {object} e.HTTPValidError "找不到资源错误"
// @failure 500 {object} e.HTTPError "服务器错误"
// @router /api/v1/img_work/{id} [get]
swag api doc
{
"can_collect": true,
"can_follow": true,
"can_like": true
}
I defined a struct with fields type is interface or json.RawMessage, when i exec command swag init
,i get some error: " Something goes wrong: &ast.InterfaceType{Interface:296, Methods:(*ast.FieldList)(0xc00029bd10), Incomplete:false}"
my struce :
type RespBody struct {
RequestID string `json:"request_id"`
Message string `json:"message"`
Code int `json:"code"`
ErrorCode string `json:"error_code,omitempty"`
Data interface{} `json:"data,omitempty"`
}
this is a bug? can you fix this ? thank you very much!
Giving swaggo a spin. It appears not to pull annotation information from a RouterGroup.
e.g.
main:
// @Summary Information about Foo APIs
// ...
// ...
func main(){
// ...
router := gin.New()
router.Use(gin.Recovery())
group := router.Group("/v1")
group.Use(gin.Logger(), cors)
p := bar.Project()
group.GET("/foo", p.List)
group.GET("/foo/:id", p.Get)
router.Run(host)
// ...
}
'Project'
//
// @Summary Get List
// @Description get List
// @Produce json
// @Success 200 "ok"
// @Router /v1/foo/[get]
func (bar Project) List(c *gin.Context) {
projects, err := bar.GetProjects()
if err != nil {
c.JSON(http.StatusNotFound, struct{}{})
return
}
c.JSON(http.StatusOK, projects)
}
do a swag init
, get a swagger.yaml
basePath: localhost:8080/
info:
contact:
email: [email protected]
name: API Support
url: http://www.swagger.io/support
description: GET method
license:
name: Apache 2.0
url: http://www.apache.org/licenses/LICENSE-2.0.html
termsOfService: http://swagger.io/terms/
title: Foo APIs
version: "1.0"
paths: {}
Issues:
$ go run main.go
# command-line-arguments
./main.go:28:13: undefined: ginSwagger.Config
./main.go:32:25: undefined: ginSwagger.CustomWrapHandler
below is some debug info
// cat go.mod
module godemo
go 1.12
require (
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.4.0 // indirect
github.com/go-openapi/spec v0.19.2 // indirect
github.com/go-openapi/swag v0.19.3 // indirect
github.com/kr/pty v1.1.8 // indirect
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e // indirect
github.com/mattn/go-isatty v0.0.8 // indirect
github.com/swaggo/gin-swagger v1.1.0 // indirect
github.com/swaggo/swag v1.6.0
github.com/ugorji/go v1.1.5-pre // indirect
golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 // indirect
golang.org/x/net v0.0.0-20190628185345-da137c7871d7 // indirect
golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb // indirect
golang.org/x/tools v0.0.0-20190701194522-38ae2c8f6412 // indirect
)
// $ cat main.go
package main
import (
"github.com/gin-gonic/gin"
"github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
_ "godemo/docs" // docs is generated by Swag CLI, you have to import it.
)
// @title Swagger Example API
// @version 1.0
// @description This is a sample server Petstore server.
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.url http://www.swagger.io/support
// @contact.email [email protected]
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host petstore.swagger.io
// @BasePath /v2
func main() {
r := gin.New()
config := &ginSwagger.Config{
URL: "http://localhost:8080/swagger/doc.json", //The url pointing to API definition
}
// use ginSwagger middleware to
r.GET("/swagger/*any", ginSwagger.CustomWrapHandler(config, swaggerFiles.Handler))
r.Run()
}
type ManagerEnabled int
type Manager struct {
Id int
Enabled ManagerEnabled
}
out: ManagerEnabled is not supported. but it will be set with string temporary. Please report any problems.2018/07/07 21:49:39 Generating a.Manager
I have API Gateway forwarding requests via proxy+
configuration.
I have the following routes configured with gin: GET /accounts
But when I set up GET /swagger/*any
I get a 404.
Using github.com/apex/gateway
to wrap the requests.
I have a orm model struct, I want to use it for @param's json body type. but there only two fields is needed.
How to ignore a field like go-swagger by using swagger:ignore
?
accept struct:
`
type ReqShopInfo struct {
ShopInfo ShopInfo `json:"shop_info"`
ShopStyle ShopStyle `json:"shop_style"`
ImgStyle []Image `json:"img_style"`
ImgShop []Image `json:"img_shop"`
}
`
this is my accept parameters struct
json data
`{
"shop_info":{
"shop_name":"测试2",
"type_id":1,
"shop_describe":"describe",
"market_price":20.5,
"discount_price":18.5,
"contact_type":1,
"contact_info":"wx1111111",
"sort_weight":1
},
"shop_style":{
"style_name":"A款",
"style_describe":"describe"
},
"img_style":[
{
"img_url":"localhost:5054/upload/images/8f81dcf6-b970-4ed1-bd02-ccf1c908c0f1.jpg",
"img_type":2,
"img_name":"simg2"
},
{
"img_url":"localhost:5054/upload/images/8f81dcf6-b970-4ed1-bd02-ccf1c908c0f1.jpg",
"img_type":2,
"img_name":"simg2"
}
],
"img_shop":[
{
"img_url":"localhost:5054/upload/images/8f81dcf6-b970-4ed1-bd02-ccf1c908c0f1.jpg",
"img_type":1,
"img_name":"pimg2"
},
{
"img_url":"localhost:5054/upload/images/8f81dcf6-b970-4ed1-bd02-ccf1c908c0f1.jpg",
"img_type":1,
"img_name":"pimg2"
}
]
}`
How do I write @Paramin my implementation method?
`// @summary 添加商品
// @description add by json ReqShopInfo
// @tags Admin
// @accept json
// @produce json
// @param shop_info body model.ShopInfo true "商品信息"
// @param shop_style body model.ShopStyle true "款式"
// @param {array} img_style body model.Image true "款式图片"
// @param {array} img_shop body model.Image true "商品图片"
// @success 200 {string} json "{"code":0,"data":null,"msg":"ok"}"
// @router /admin/v1/shop/ashop [post]`
I don't know how to write in swagger to get my json data.
@param how to write?
I first use it,please teach me,thank you!
type RevValueBase struct {
Status bool `json:"Status"`
Err int32 `json:"Err"`
Error RevError `json:"Error"`
}
type RevValue struct {
RevValueBase
Data int `json:"Data"`
}
when use composition return value, use swag init error
// @Success 200 {object} controllerparams.RevValue "ok"
panic: runtime error: index out of range
host config problem,this is code
"host": "petstore.swagger.io"
but add http://
by default, this is result
http://petstore.swagger.io
If I use https
,what should I do
Doc folder gets created with doc.go file however I am unable to find anything on localhost:8080/swagger. Could you please help?
Hi, following the instructions, but _ "./docs" doesn´t seem to be foundable. Could it be because we are using vgo modules and the project is not in the $GOPATH?
Is there any doc on how to go around this?
Thanks!
求解答
go get github.com/swaggo/swag/cmd/swag
package golang.org/x/net/idna: unrecognized import path "golang.org/x/net/idna" (https fetch: Get https://golang.org/x/net/idna?go-get=1: dial tcp 216.239.37.1:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)
package golang.org/x/text/unicode/norm: unrecognized import path "golang.org/x/text/unicode/norm" (https fetch: Get https://golang.org/x/text/unicode/norm?go-get=1: dial tcp 216.239.37.1:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)
package golang.org/x/text/width: unrecognized import path "golang.org/x/text/width" (https fetch: Get https://golang.org/x/text/width?go-get=1: dial tcp 216.239.37.1:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)
I have struct model and I want to make a parameter as required
type HTTPError struct {
Code int `json:"code" example:"400"`
Message string `json:"message" example:"Bad Request"`
ErrorType string `json:"type" example:"A0"`
}
I want to make Code as required.
Hi, I did do test one example https://github.com/swaggo/swag/blob/master/example/celler/main.go and I face this issue:
build command-line-arguments: cannot load github.com/ugorji/go/codec: ambiguous import: found github.com/ugorji/go/codec in multiple modules:
github.com/ugorji/go v1.1.4 (/Users/vzool/Workspace/go/pkg/mod/github.com/ugorji/[email protected]/codec)
github.com/ugorji/go/codec v0.0.0-20190320090025-2dc34c0b8780 (/Users/vzool/Workspace/go/pkg/mod/github.com/ugorji/go/[email protected])
How can I solve this?
Thanks
ref swaggo/swag#292
安装 gin-swaager 是 出现如下问题
go build github.com/ugorji/go/codec: no Go files in
该如何解决
I see there are query and body Params types. But no header? Anyway to put it on?
Sample Code :
package xyz
type Metadata struct{
id string json:"id,omitempty"
key string json:"key,omitempty"
}
package abc
import "xyz"
type Entity struct {
xyz.Metadata
Name string json:"name,omitempty"
}
If i try to generate Doc using swag init. But getting following error
2018/01/31 17:29:34 Generate swagger docs....
2018/01/31 17:29:34 Generate general API Info
panic: runtime error: index out of range
goroutine 1 [running]:
github.com/swaggo/swag.(*Parser).ParseDefinitions(0xc0421445c0)
C:/Users/gangab5/go/src/PersistenceService/src/github.com/swaggo/swag/parser.go:196 +0x652
github.com/swaggo/swag.(*Parser).ParseApi(0xc0421445c0, 0x7d4eb9, 0x2, 0x7d64ae, 0x9)
C:/Users/gangab5/go/src/PersistenceService/src/github.com/swaggo/swag/parser.go:70 +0x26f
github.com/swaggo/swag/gen.(*Gen).Build(0xc042059b50, 0x7d4eb9, 0x2, 0x7d64ae, 0x9, 0x0, 0x0)
C:/Users/gangab5/go/src/PersistenceService/src/github.com/swaggo/swag/gen/gen.go:27 +0x382
main.main.func1(0xc04206c2c0, 0xc04224c100, 0xc04206c2c0)
C:/Users/gangab5/go/src/PersistenceService/src/github.com/swaggo/swag/cmd/swag/main.go:23 +0x5c
github.com/urfave/cli.HandleAction(0x759d60, 0x7ec5e8, 0xc04206c2c0, 0x0, 0xc0421c6120)
C:/Users/gangab5/go/src/PersistenceService/src/github.com/urfave/cli/app.go:501 +0xd9
github.com/urfave/cli.Command.Run(0x7d54ca, 0x4, 0x0, 0x0, 0xc04224c0f0, 0x1, 0x1, 0x7d7f8e, 0xe, 0x0, ...)
C:/Users/gangab5/go/src/PersistenceService/src/github.com/urfave/cli/command.go:165 +0x4c2
github.com/urfave/cli.(*App).Run(0xc04202e000, 0xc0420023c0, 0x2, 0x2, 0x0, 0x0)
C:/Users/gangab5/go/src/PersistenceService/src/github.com/urfave/cli/app.go:259 +0x747
main.main()
C:/Users/gangab5/go/src/PersistenceService/src/github.com/swaggo/swag/cmd/swag/main.go:29 +0x1bd
Please help.
when use Type from external package ,It output error,
for example ,when reference gogs.CreateOrgOption from gopath,error occur:
ParseComment panic:Can not find ref type:"gogs.CreateOrgOption".
When using dep.
Packages including github.com/swaggo/gin-swagger, will save in /root/vendor.
And Swag will generate the comments from gin-swagger/examples too.
Can i exclude 'vendor' folder?
Gin route listening port 5050
Authorization configured:
// @in header
// @name Authorization
// @securitydefinitions.oauth2.implicit OAuth2Implicit
// @authorizationurl http://localhost:5000/connect/authorize
// @tokenUrl http://localhost:5000/connect/token
// @scope.basket-api
Invalid redirect_uri: http://localhost:3200/oauth2-redirect.html
{
"ClientId": "basket-api-swagger-ui",
"ClientName": "Basket API Swagger UI",
"AllowedRedirectUris": [
"http://localhost:5050/swagger/oauth2-redirect.html"
],
"SubjectId": "anonymous",
"RequestedScopes": "",
"Raw": {
"response_type": "token",
"client_id": "basket-api-swagger-ui",
"redirect_uri": "http://localhost:3200/oauth2-redirect.html",
"scope": "basket-api",
"state": "VHVlIEFwciAwOSAyMDE5IDE1OjE5OjA1IEdNVCswMjAwIChDZW50cmFsIEV1cm9wZWFuIFN1bW1lciBUaW1lKQ=="
}
}
AllowedRedirectUris
configured for port 5050 but swagger client sending port 3200
As mentioned here it must be configurable on SwaggerUIBundle.js I just wanted to figure out swagger-ui-bundle.js but everything encoded...
Unable to render this definition
The provided definition does not specify a valid version field.
Please indicate a valid Swagger or OpenAPI version field. Supported version fields are swagger: "2.0" and those that match openapi: 3.0.n (for example, openapi: 3.0.0).
1、main.go
file:
package main
import (
"fmt"
"net/http"
"xxx/routers"
"xxx/setting"
)
func main() {
router := routers.InitRouter()
s := &http.Server{
Addr: fmt.Sprintf(":%d", setting.HTTPPort),
Handler: router,
ReadTimeout: setting.ReadTimeout,
WriteTimeout: setting.WriteTimeout,
MaxHeaderBytes: 1 << 20,
}
s.ListenAndServe()
}
2、router.go
file:
package routers
import (
"github.com/gin-gonic/gin"
"github.com/swaggo/gin-swagger"
"github.com/swaggo/gin-swagger/swaggerFiles"
_ "xxx/docs"
)
func InitRouter() *gin.Engine {
r := gin.New()
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
return r
}
3、execute the following command, an error occurs
$ go run main.go
routers/router.go:26:50: cannot use ginSwagger.WrapHandler(swaggerFiles.Handler) (type "github.com/gin-gonic/gin".HandlerFunc) as type "xxx/vendor/github.com/gin-gonic/gin".HandlerFunc in argument to r.RouterGroup.GET
https://swaggo.github.io/swaggo.io/declarative_comments_format/api_operation.html#param-type
According to swagger spec, param type should be path, query ,header, cookie
hi,thank you for your extension here, i want to generate swagger 3.0 docs, is this support?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.