fiber middleware to automatically generate RESTful API documentation with Swagger
- Add comments to your API source code,See Declarative Comments Format.
- DownloadSwagfor Go by using:
go get -u github /swaggo/swag/cmd/swag
#1.16 or newer
go install github /swaggo/swag/cmd/swag@latest
- Run theSwagin your Go project root folder which contains
main.go
file,Swagwill parse comments and generate required files(docs
folder anddocs/doc.go
).
swag init
- Downloadswaggerby using:
go get -u github /gofiber/swagger
And import following in your code:
import"github /gofiber/swagger"// swagger handler
packagemain
import(
"github /gofiber/swagger"
"github /gofiber/fiber/v2"
// docs are generated by Swag CLI, you have to import them.
// replace with your own docs folder, usually "github /username/reponame/docs"
_"github /gofiber/swagger/example/docs"
)
// @title Fiber Example API
// @version 1.0
// @description This is a sample swagger for Fiber
// @termsOfService http://swagger.io/terms/
// @contact.name API Support
// @contact.email [email protected]
// @license.name Apache 2.0
// @license.url http:// apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
// @BasePath /
funcmain() {
app:=fiber.New()
app.Get("/swagger/*",swagger.HandlerDefault)// default
app.Get("/swagger/*",swagger.New(swagger.Config{// custom
URL:"http://example /doc.json",
DeepLinking:false,
// Expand ( "list" ) or Collapse ( "none" ) tag groups by default
DocExpansion:"none",
// Prefill OAuth ClientId on Authorize popup
OAuth:&swagger.OAuthConfig{
AppName:"OAuth Provider",
ClientId:"21bb4edc-05a7-4afc-86f1-2e151e4ba6e2",
},
// Ability to change OAuth2 redirect uri location
OAuth2RedirectUrl:"http://localhost:8080/swagger/oauth2-redirect.html",
}))
app.Listen(":8080")
}
- Run it, and browser tohttp://localhost:8080/swagger,you can see Swagger 2.0 Api documents.