swaggo / http-swagger Goto Github PK
View Code? Open in Web Editor NEWDefault net/http wrapper to automatically generate RESTful API documentation with Swagger 2.0.
License: MIT License
Default net/http wrapper to automatically generate RESTful API documentation with Swagger 2.0.
License: MIT License
when run the sample go-chi (without any modification), and access the index.html, "No operations defined in spec!" is shown in the ui, and there is no API doc shown in swagger UI.
Running in latest Chrome.
This is a duplicate of:
package api
import (
"net/http"
"github.com/gorilla/mux"
httpSwagger "github.com/swaggo/http-swagger"
_ "github.com/swaggo/http-swagger/example/gorilla/docs"
)
// @title Swagger Coinss API
// @Version 1.0
// @description This is Coinss API
// @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 API() http.Handler {
router := mux.NewRouter()
router.PathPrefix("/swagger/").Handler(httpSwagger.Handler(
httpSwagger.URL("http://localhost:5000/swagger/doc.json"), //The url pointing to API definition
httpSwagger.DeepLinking(true),
httpSwagger.DocExpansion("none"),
httpSwagger.DomID("#swagger-ui"),
))
//user
router.HandleFunc("/signup", signup).Methods(http.MethodPost, http.MethodOptions)
router.HandleFunc("/signin", signin).Methods(http.MethodPost, http.MethodOptions)
router.Use(handlePanic)
router.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
next.ServeHTTP(w, r)
})
})
router.Use(mux.CORSMethodMiddleware(router))
return router
}
Hi, I'm quite newbie to the Go ecosystems and I chose Gorilla mux to start a new HTTP API.
However I can't figure it out how to use it with the gorilla muxer.
Anyone could help me out with a basic implementation?
I'm not entirely certain, but I'm wondering if it's possible to use Swaggo along with this package to document a Mux server without the use of Chi (as seen in most examples). Specifically, I'm interested in documenting a server structured like this:
package main
import (
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
})
http.ListenAndServe(":8080", mux)
}
In theory, since this follows a net/http structure, it seems feasible that this package could be utilized to document this type of API.
Thanks!
ref swaggo/swag#292
Hi,
Current version of golang is 1.17. Version 1.18 introduces generics which I believe are going to be widely adopted. Unfortunately, upon running swag init
I run into errors because of usage of generics. I see the bigger repo swag has already moved to 1.18. Would it be possible to move to >=1.18 here as well?
Cheers!
Hello,
I try to dokerize a simple application but it seems to fail: the url http://localhost:1323/doc/index.html returns a ERR_CONNECTION_REFUSED. Any Idea?
Here is my dockerfile:
FROM golang:alpine AS builder
RUN apk update && apk add --no-cache git
WORKDIR $GOPATH/src/testSwagger/
COPY . .
RUN go get -d -v
RUN go build -o /go/bin/testSwagger
FROM alpine:latest
COPY --from=builder /go/bin/testSwagger /
CMD ["/testSwagger"]
EXPOSE 1323
Blank page when accessing localhost:port/swagger/index.html
Console log show this err:
Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '##swagger-ui' is not a valid selector.
go version: 1.18
http-swagger: 1.3.3
At first request I get data race, but further requests are fine.
| ==================
| WARNING: DATA RACE
| Write at 0x00c0003dbb00 by goroutine 31:
| github.com/swaggo/http-swagger.wrapHandler.func1()
| /go/pkg/mod/github.com/swaggo/[email protected]/swagger.go:39 +0x120
| net/http.HandlerFunc.ServeHTTP()
| /usr/local/go/src/net/http/server.go:1964 +0x51
r.Get("/swagger/*", httpSwagger.WrapHandler)
Error in dependent library github.com/swaggo/swag. Details swaggo/swag#1568. As a temporary fix I had to upgrade swag to v1.16.2 in go.mod
Hi! I can't generate documentation to my project.
My project's structure looks like that:
- cmd
- api
main.go
- docs
docs.go
swagger.json
swagger.yaml
- internal
- domain
- handlers
users.go
...
I have the next annotation in /cmd/api/main.go:
// @title API for my application
// @version 0.1
// @description It's made for testing purposes only
// @host localhost:8080
// @BasePAth /
func main() { ... }
And this is in /internal/handlers/users.go:
// Returns full user info godoc
// @Description Returns lists
// @Summary Returns full user info
// @Tags Lists
// @Accept json
// @Produce json
// @Success default {object} domain.Response
// @Failure default {object} domain.Response
// @Router /users/full [get]
func (h userHandler) getFullUserInfo(w http.ResponseWriter, r *http.Request) { ... }
I'm running
swag init -g cmd/api/main.go --parseDependency --parseInternal
from the root directory of the project.
I'm getting
> Generate swagger docs....
> Generate general API Info, search dir:./
> warning: failed to get package name in dir: ./, error: execute go list command, exit status 1, stdout:, stderr:no Go files in /Users/stycho/GolandProjects/my_life
> create docs.go at docs/docs.go
> create swagger.json at docs/swagger.json
> create swagger.yaml at docs/swagger.yaml
and "No operations defined in spec!" when I enter http://localhost:8080/swagger/index.html .
I've tried different --parseDepth
values, no --parseDependency
or --parseInternal
. I've also tried to make blank import in /internal/handlers/users.go - all this doesn't help.
I tried to google the solution, but haven't find anything. I can't understand what I'm doing wrong. Could you help me please?
Hi, I cannot access my swagger UI, this is what I'm getting:
And this is what I'm doing:
func (a *APIHandler) initRoutes() {
a.router.HandleFunc("/anotherRoute", a.anotherRouteHandler).Methods("GET")
a.router.HandleFunc("/swagger/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/swagger/index.html", http.StatusMovedPermanently)
})
a.router.PathPrefix("/swagger/").Handler(httpSwagger.Handler(
httpSwagger.URL("/swagger/doc.json"),
))
...
Logs:
2021/08/11 07:25:11 http: panic serving 172.17.0.1:60664: not yet registered swag
goroutine 55 [running]:
net/http.(*conn).serve.func1(0xc0010e66e0)
/usr/local/go/src/net/http/server.go:1804 +0x153
panic(0x160ebe0, 0xc00013c050)
/usr/local/go/src/runtime/panic.go:971 +0x499
github.com/swaggo/http-swagger.Handler.func1(0x1a015b0, 0xc0000c2000, 0xc0000ae800)
/go/pkg/mod/github.com/swaggo/[email protected]/swagger.go:85 +0x3cd
net/http.HandlerFunc.ServeHTTP(0xc001093a40, 0x1a015b0, 0xc0000c2000, 0xc0000ae800)
/usr/local/go/src/net/http/server.go:2049 +0x44
github.com/gorilla/mux.(*Router).ServeHTTP(0xc000d1f680, 0x1a015b0, 0xc0000c2000, 0xc0000ae200)
/go/pkg/mod/github.com/gorilla/[email protected]/mux.go:210 +0xd3
github.com/rs/cors.(*Cors).Handler.func1(0x1a015b0, 0xc0000c2000, 0xc0000ae200)
/go/pkg/mod/github.com/rs/[email protected]/cors.go:219 +0x1b9
net/http.HandlerFunc.ServeHTTP(0xc0010d6440, 0x1a015b0, 0xc0000c2000, 0xc0000ae200)
/usr/local/go/src/net/http/server.go:2049 +0x44
net/http.serverHandler.ServeHTTP(0xc00108afc0, 0x1a015b0, 0xc0000c2000, 0xc0000ae200)
/usr/local/go/src/net/http/server.go:2867 +0xa3
net/http.(*conn).serve(0xc0010e66e0, 0x1a04280, 0xc00128c000)
/usr/local/go/src/net/http/server.go:1932 +0x8cd
created by net/http.(*Server).Serve
/usr/local/go/src/net/http/server.go:2993 +0x39b
I'm running my service via docker by mapping ports between host and container, Docker file is:
FROM golang:1.16 AS builder
WORKDIR /app
# Install dependencies
COPY go.mod go.sum ./
RUN go mod download && \
go get -u github.com/swaggo/swag/cmd/swag
# Copy the code from the host and compile it
COPY . ./
RUN swag init && CGO_ENABLED=0 go build -v -o ./my-service
FROM alpine:3.9
EXPOSE 8080
RUN apk add --no-cache ca-certificates
COPY --from=builder /app/my-service ./
ENTRYPOINT ["./my-service"]
What could be wrong here?
go version go1.18.9 windows/amd64
"RequestURI is the unmodified request-target of the Request-Line (RFC 7230, Section 3.1.1) as sent by the client to a server. Usually the URL field should be used instead."
so, file "swagger.go" line "201",r.RequestURI should be changed to r.URL.Path
r.URL.Path = matches[2] // r.RequestURI = matches[2]
Using Enums to declare a dropdown selection
// @Param state query string false "Order state" Enums(A, B, C)
In swagger, It looks like
swag version: v1.6.3
I've tested with v1.7.0 but It's not work as well
Hi people, wanted to know if is intentional or a possible bug, because I'm having some troubles when trying to show a single struct, like in the example bellow:
type PurchaseOutput struct { // Identificador da proposta no formato UUID ID string
json:"id" example:"6f1d7913-0a3b-41a0-93ce-0027aff9d1d2"`
// Status of Purchase
Status lang.TranslatedString `json:"status"`
// List of the products in this purchase
Products []products.ProductOutput `json:"products``
The first struct, lang.TranslatedString, don't show the value of description in the documentation, even tough in the file doc, he correctly appear. In the same time, the array of strings, load the description correct.
The documentation is straightforward and easy to follow and the 'copy' button is useful for quickly getting set up. However, while the leading $
does make it clear to the reader that snippet represents a CLI command, it also makes it an invalid command. The user has to go back and remove this character or else the command fails:
I can make the changes and link the pull request if the maintainers think this is a worthwhile tweak.
SwaggerUI have two different layouts, Standalone and Base, it would be nice to have the option to select the layout I want to implement
As per title, the Handler
has a data race in assigning Prefix
due to the sync.Once
being function scoped and Prefix
existing in the swaggo/files
package.
The problematic code:
Lines 157 to 159 in c8d62bf
This means that any reads to files.Handler.Prefix
are globally unsafe across all swaggo packages.
The race can be avoided by only ever invoking one handler. This is not very likely to happen in practice, but problematic in tests. The way it's written also unfortunately means it's impossible to serve on two different endpoints (just an observed behavior, not a requirement).
Hi,
It looks like the v0.20.5 tag of github.com/go-openapi/spec has been rewritten when v0.20.6 was released, causing "go get github.com/swaggo/http-swagger" to fail for all versions since v1.2.7 inclusive:
$ go get github.com/swaggo/http-swagger
go: github.com/swaggo/[email protected] requires
github.com/go-openapi/[email protected]: verifying go.mod: checksum mismatch
downloaded: h1:2OpW+JddWPrpXSCIX8eOx7lZ5iyuWj3RYR6VaaBKcWA=
sum.golang.org: h1:QbfOSIVt3/sac+a1wzmKbbcLXm5NdZnyBZYtCijp43o=
SECURITY ERROR
This download does NOT match the one reported by the checksum server.
The bits may have been replaced on the origin server, or an attacker may
have intercepted the download attempt.
For more information, see 'go help module-auth'.
Unless the go-openapi/[email protected] tag can be fixed rapidly, maybe this warrants a v1.3.1 release that upgrades to go-openapi/[email protected] ?
Currently these configs just replace the previous script, example:
r.Get("/swagger/*", httpSwagger.Handler(
httpSwagger.BeforeScript("console.log('before 1')"),
httpSwagger.BeforeScript("console.log('before 2')"),
httpSwagger.URL("http://localhost:1323/swagger/doc.json"), //The url pointing to API definition
))
// Only 'before 2' is printed
It makes hard to add multiple configuration scripts by forcing joing strings.
I am trying to deploy swagger below the basePath so that the swagger handler owns example.com/foo/swagger rather than example.com/swagger
When I open example.com/foo/swagger/index.html in the browser everything works as expected but example.com/foo/swagger/ redirects to example.com/swagger/index.html rather than to example.com/foo/swagger/index.html
http-swagger parses the request URL over here:
Line 68 in 58ac5e2
I suspect something is wrong with that regexp. I dunno if it is obvious what is going wrong from my description but I'll try to investigate further and provide a PR if that helps.
Currently these is no way to add more <script src="local or extern"> </script>
tags. Having this is useful to add local or external swagger-ui
plugins.
I'm thinking of this kind of config
r.Get("/swagger/*", httpSwagger.Handler(
httpSwagger.ScriptSrc("https://unpkg.com/[email protected]/dist/htm.js"),
httpSwagger.ScriptSrc("https://unpkg.com/[email protected]/umd/react.production.min.js"),
httpSwagger.ScriptSrc("/static/myplugin.js"),
httpSwagger.Plugins([]string{"MyPlugin"}),
httpSwagger.URL("http://localhost:1323/swagger/doc.json"), //The url pointing to API definition
))
I am new to go lang.
My go lang version: 1.11.3
I am using Gorilla mux for router.
Somehow I cannot able to integrate swaggo/swag in to my Go Web application. Please see the steps I have taken.
Step 1: Added comments to my API (main.go) source code (Refer: https://github.com/swaggo/http-swagger#canonical-example)
Step 2: Download swag and http-swagger
go get github.com/swaggo/swag/cmd/swag
go get -u github.com/swaggo/http-swagger
Step 3: Run swag (it will generate some files in a docs/ directory)
swag init
Add the following code in my main.go
import (
"github.com/swaggo/http-swagger"
_"mylocation/docs"
"net/http"
"github.com/gorilla/mux"
)
func main() {
router := mux.NewRouter()
router.PathPrefix("/documentation/").Handler(httpSwagger.WrapHandler)
http.ListenAndServe(":8000", router)
}
I can able to redirect to "/documentation" route but page is blank. And when I check network logs, following files are missing/ getting 404
I don't know what exactly happening. Please help
hello, i find a security bug about this project, and it affects many project who use this http-swagger
project.
how can i send report "safely" to you?
I have been facing this issue but not sure which steps I have missed.
Going through the steps in README, I have successfully
docs/swagger.json
with the correct routes using swag init
commandBut it loads a default template doc.json
from URL http://localhost:1323/swagger/doc.json, not the JSON file generated under docs/swagger.json
.
{
"schemes": [],
"swagger": "2.0",
"info": {
"description": "This is a sample server Petstore server.",
"title": "Swagger Example 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"
},
"host": "petstore.swagger.io",
"basePath": "/v2",
"paths": {}
}
I can use a workaround to serve docs/swagger.json
as a static file and load the JSON file from http://localhost:1323/docs/swagger.json instead of http://localhost:1323/swagger/doc.json.
But I assume this shouldn't be the way to go.
fileServer := http.FileServer(http.Dir("./docs/"))
r.Handle("/docs/swagger.json", http.StripPrefix("/docs", fileServer))
r.Get("/swagger/*", httpSwagger.Handler(
httpSwagger.URL("http://localhost:1323/docs/swagger.json"), // The url pointing to API definition
))
Environment:
_ "gitlab.com/golang_development/stand-alone-swagger/docs" // docs is generated by Swag CLI, you have to import it. _ "gitlab.com/golang_development/stand-alone-swagger/testdocs"
panic: Register called twice for swag: swagger
Hi, I followed instructions to annotate, generate and to host the swagger UI displaying my "docs". But the HTML string gets displayed on my browser, not being rendered.
What could possibly be causing this? How to fix?
I'm exploring the right way to dynamically generate an OpenAPI spec, given a real-time need. In other words, I have APIs that I generate, based on a pattern match.. and I'd love to be able to generate an OpenAPI spec that users can see.
I have a series of routes where the route matches a dynamic set of variables (think /{foo}/{bar}). The functions themselves are responsible for validating whether {foo} and {bar} above are valid, returning the correct error codes when they're not. I'd like to generate a spec (only) where {foo} and friends are pre-populated, meaning I won't have a doc.json - but instead would need to generate one as a string.
Is there a reasonable way to do this at runtime, with this library?
If I have in my code different swagger instances it is totally imposible to show differerent ones, the only one able to be shown is the swagger.json
The PR #20 does not solve the redirect when there is no slash at the end of the path.
swaggo/swag v1.8.1
swaggo/http-swagger v1.2.7
Recently I am trying to initiate a project with swaggo then encountered this error Uncaught Invariant Violation: Minified React error #37
I couldn't provide complete steps to reproduce this error because it's a new project that generated from a template automatically. But the main steps are:
First go get github.com/swaggo/swag, then swag init to generate /docs/swagger directory with docs.go, swagger.json and swagger.yaml files.
// routes.go setup
router.Mount("/docs/", httpSwagger.WrapHandler)
Then go to http://localhost:_port_/docs/index.html to see the blank page.
So there's actually no too much customization.
After searching a bit I found a similar issue in swagger-ui: swagger-api/swagger-ui#5608.
I've successfully fixed this error locally by changing the default dom_id
here to #swagger-ui
:
Line 117 in 285f7b0
func newConfig(configFns ...func(*Config)) *Config {
config := Config{
...
DomID: "#swagger-ui",
...
}
...
}
Please let me know if any concerns, it will not block my progress since I'll switch to edit the swagger doc manually, so not urgent here. 😄
I see there's another open issue at #7, but this race is on another line in the same file, so I'm presuming it's distinct.
Go version: 1.15
Swaggo version: 1.0.0
WARNING: DATA RACE
Write at 0x00c00014e300 by goroutine 57:
github.com/swaggo/http-swagger.Handler.func1()
/Users/[redacted]/vendor/github.com/swaggo/http-swagger/swagger.go:76 +0x145
net/http.HandlerFunc.ServeHTTP()
/usr/local/go/src/net/http/server.go:2042 +0x51
github.com/julienschmidt/httprouter.(*Router).Handler.func1()
/Users/[redacted]/vendor/github.com/julienschmidt/httprouter/router.go:275 +0x95
github.com/julienschmidt/httprouter.(*Router).ServeHTTP()
/Users/[redacted]/vendor/github.com/julienschmidt/httprouter/router.go:387 +0x1201
[redacted]/internal/observability.LoggingMiddleware.func1()
/Users/[redacted]/internal/observability/logging.go:21 +0x66e
net/http.HandlerFunc.ServeHTTP()
/usr/local/go/src/net/http/server.go:2042 +0x51
net/http.serverHandler.ServeHTTP()
/usr/local/go/src/net/http/server.go:2843 +0xca
net/http.(*conn).serve()
/usr/local/go/src/net/http/server.go:1925 +0x84c
Previous write at 0x00c00014e300 by goroutine 52:
github.com/swaggo/http-swagger.Handler.func1()
/Users/[redacted]/vendor/github.com/swaggo/http-swagger/swagger.go:76 +0x145
net/http.HandlerFunc.ServeHTTP()
/usr/local/go/src/net/http/server.go:2042 +0x51
github.com/julienschmidt/httprouter.(*Router).Handler.func1()
/Users/[redacted]/vendor/github.com/julienschmidt/httprouter/router.go:275 +0x95
github.com/julienschmidt/httprouter.(*Router).ServeHTTP()
/Users/[redacted]/vendor/github.com/julienschmidt/httprouter/router.go:387 +0x1201
[redacted]/internal/observability.LoggingMiddleware.func1()
/Users/[redacted]/internal/observability/logging.go:21 +0x66e
net/http.HandlerFunc.ServeHTTP()
/usr/local/go/src/net/http/server.go:2042 +0x51
net/http.serverHandler.ServeHTTP()
/usr/local/go/src/net/http/server.go:2843 +0xca
net/http.(*conn).serve()
/usr/local/go/src/net/http/server.go:1925 +0x84c
Goroutine 57 (running) created at:
net/http.(*Server).Serve()
/usr/local/go/src/net/http/server.go:2969 +0x5d3
main.run()
/Users/[redacted]/cmd/main/main.go:251 +0x28b4
main.main()
/Users/[redacted]/cmd/main/main.go:50 +0x49
Goroutine 52 (running) created at:
net/http.(*Server).Serve()
/usr/local/go/src/net/http/server.go:2969 +0x5d3
main.run()
/Users/[redacted]/cmd/main/main.go:251 +0x28b4
main.main()
/Users/[redacted]/cmd/main/main.go:50 +0x49
Currently, http-swagger expects the service, the API belongs to, to run on the same server, swagger-ui does.
This should be configurable programmatically and in the UI itself, to allow accessing different servers.
If I do:
r.Get("/swagger/*", swagger.Handler(swagger.URL("http://localhost/swagger/doc.json")))
returns the swagger json at http://localhost/swagger/doc.json
.
I would like to make the json available at http://localhost/swagger/swagger.json
.
If I do:
r.Get("/swagger/*", swagger.Handler(swagger.URL("http://localhost/swagger/swagger.json")))
I get a 404.
Is there a way to do that currently? If not, would you accept a PR to enable it?
hi there when i try to run the chi example i just get a blank screen
Hi, Would like it if I could configured what swagger the handler should read.
I'm currently working on project that thinking about having two different swaggers in the same server.
Something like extending the Config struct to
type Config struct {
URL string
DeepLinking bool
DocExpansion string
DomID string
Swagger swag.Swagger
}
Adding a config func for the Swagger field and then using config.Swagger.ReadDoc() instead of swag.ReadDoc(), if it has been configured.
I have the following code, which will return the root swagger, but it does not go into the routes themselves.
// @title Example
// @version v0.0.0
func main() {
r := chi.NewRouter()
r.Mount("/things", thing.Handler{}.Routes())
r.Get("/swagger/*", httpSwagger.Handler(
httpSwagger.URL("http://localhost:8000/swagger/doc.json"),
))
err = http.ListenAndServe(":8000", r)
if err != nil {
log.Fatal(err)
}
}
However, my handler which lives in ./api/thing/handler.go
which has the following code will not show in the swagger.json
, or in the UI.
// Get godoc
// @Summary gets a thing
// @Accept json
// @Produce json
// @Success 200
func (h Handler) Get(w http.ResponseWriter, r *http.Request) {
t := &Thing{}
t.ID = helpers.GetIDFromRequest(r)
t.Get()
helpers.RespondSuccess(w, t)
}
Not too sure how to get this one to work unfortunately.
When trying go-chi example https://github.com/swaggo/http-swagger/tree/master/example/go-chi I get a blank page.
Refused to apply style from 'http://localhost:1323/swagger/swagger-ui.css' because its MIME type ('text/plain') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
The issue seems to be V2 as if I try the example as is before #97 it works fine.
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.