- Notifications
You must be signed in to change notification settings - Fork0
Home
vinod edited this pageJan 16, 2024 ·2 revisions
gin middleware to automatically generate RESTful API documentation with Swagger 2.0.
- Add comments to your API source code,See Declarative Comments Format.
- DownloadSwag for Go by using:
go get -u github.com/swaggo/swag/cmd/swag
Starting in Go 1.17, installing executables withgo get
is deprecated.go install
may be used instead:
go install github.com/swaggo/swag/cmd/swag@latest
- Run theSwag at your Go project root path(for instance
~/root/go-project-name
),Swag will parse comments and generate required files(docs
folder anddocs/doc.go
)at~/root/go-project-name/docs
.
swag init
- Downloadgin-swagger by using:
go get -u github.com/swaggo/gin-swaggergo get -u github.com/swaggo/files
Import following in your code:
import"github.com/swaggo/gin-swagger"// gin-swagger middlewareimport"github.com/swaggo/files"// swagger embed files
Now assume you have implemented a simple api as following:
// A get function which returns a hello world string by jsonfunchelloCall(c*gin.Context) {c.JSON(http.StatusOK, gin.H{"message":"Hello, You created a Web App!"})}
So how to use gin-swagger on api above? Just follow the following guide.
- Add Comments for apis and main function with gin-swagger rules like following:
// helloCall godoc// @Summary hellow example// @Schemes// @Description Hello// @Tags example// @Accept json// @Produce json// @Success 200 {string} Hello, You created a Web App!// @Router / [get]funchelloCall(c*gin.Context) {c.JSON(http.StatusOK, gin.H{"message":"Hello, You created a Web App!"})}
- Use
swag init
command to generate a docs, docs generated will be stored atdocs/
. - import the docs like this:I assume your project named
github.com/go-project-name/docs
.
import ( _"github.com/vinodnextcoder/go-web-app/docs")
build your application and after that, go tohttp://localhost:3001/swagger/index.html ,you to see your Swagger UI.
The full code and folder relatives here:
package mainimport ("net/http""github.com/gin-gonic/gin"swaggerFiles"github.com/swaggo/files"ginSwagger"github.com/swaggo/gin-swagger"_"github.com/vinodnextcoder/go-web-app/docs")// @title Swagger Example API// @version 1.0// @description This is a sample gin web server// @contact.name vinod// @contact.url http://www.swagger.io/support// @contact.email support@swagger.io// @host localhost:3001// @BasePath /// @externalDocs.description OpenAPI// @externalDocs.url https://swagger.io/resources/open-api/funcmain() {router:=gin.Default()router.GET("/",helloCall)router.GET("/about",aboutCall)router.GET("/user/:name",getUser)router.GET("/user",getUsers)router.POST("/user",addUser)router.GET("/userData/:id",getUserByID)router.GET("/swagger/*any",ginSwagger.WrapHandler(swaggerFiles.Handler))router.Run(":3001")}
Demo project tree,swag init
is run at relative.
.├── docs│ ├── docs.go│ ├── swagger.json│ └── swagger.yaml├── go.mod├── go.sum└── main.go