fasthttp middleware to automatically generate RESTFUL API documentation with Swagger 2.0.
- Add comments to your API source code, See Declarative Comments Format.
- Download Swag for Go by using:
go get -u github.com/swaggo/swag/cmd/swag
- Run the Swag at your Go project root path(for instance
~/root/go-peoject-name
), Swag will parse comments and generate required files(docs
folder anddocs/doc.go
) at~/root/go-peoject-name/docs
.
swag init
- Download fasthttp-swagger by using:
go get -u github.com/swaggo/fasthttp-swagger
go get -u github.com/swaggo/files
Import following in your code:
import "github.com/swaggo/fasthttp-swagger" // fasthttp-swagger middleware
Now assume you have implemented a simple api as following:
// A get function which returns a hello world string by json
func Helloworld(ctx *fasthttp.RequestCtx) {
ctx.SetStatusCode(http.StatusOK)
ctx.Write([]byte("helloworld"))
}
So how to use fasthttp-swagger on api above? Just follow the following guide.
- Add Comments for apis and main function with fasthttp-swagger rules like following:
// @BasePath /api/v1
// PingExample godoc
// @Summary ping example
// @Schemes
// @Description do ping
// @Tags example
// @Accept json
// @Produce json
// @Success 200 {string} Helloworld
// @Router /example/helloworld [get]
func Helloworld(ctx *fasthttp.RequestCtx) {
ctx.SetStatusCode(http.StatusOK)
ctx.Write([]byte("helloworld"))
}
- Use
swag init
command to generate a docs, docs generated will be stored at - import the docs like this:
I assume your project named
github.com/go-project-name/docs
.
import (
docs "github.com/go-project-name/docs"
)
-
build your application and after that, go to http://localhost:8080/swagger/index.html ,you to see your Swagger UI.
-
The full code and folder relatives here:
package main
import (
_ "github.com/go-project-name/docs"
fasthttpSwagger "github.com/swaggo/fasthttp-swagger"
)
// @BasePath /api/v1
// PingExample godoc
// @Summary ping example
// @Schemes
// @Description do ping
// @Tags example
// @Accept json
// @Produce json
// @Success 200 {string} Helloworld
// @Router /example/helloworld [get]
func Helloworld(ctx *fasthttp.RequestCtx) {
ctx.SetStatusCode(http.StatusOK)
ctx.Write([]byte("helloworld"))
}
func main() {
fasthttp.ListenAndServe(":8080", func(ctx *fasthttp.RequestCtx) {
path := string(ctx.RequestURI())
switch {
case strings.HasPrefix(path, "/swagger"):
fastHttpSwagger.WrapHandler(fastHttpSwagger.InstanceName("swagger"))(ctx)
case path == "/api/v1/example/helloworld":
Helloworld(ctx)
}
})
}
Demo project tree, swag init
is run at relative .
.
├── docs
│ ├── docs.go
│ ├── swagger.json
│ └── swagger.yaml
├── go.mod
├── go.sum
└── main.go