In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of "golang component swagger generation interface document method". Xiaobian shows you the operation process through actual cases. The operation method is simple, fast and practical. I hope this article "golang component swagger generation interface document method" can help you solve the problem.
Swagger presentation
Swagger is essentially an interface description language for describing RESTful APIs expressed in JSON. Swagger works with a set of open source software tools to design, build, document, and consume RESTful Web services. Swagger includes automated documentation, code generation and test case generation.
In the process of project development separated from the front and back ends, if the back-end students can provide a clear interface document, it can greatly improve the communication efficiency and development efficiency of everyone. But writing interface documentation has always been a headache, and the subsequent maintenance of interface documentation is also very energy consuming.
It would be nice to have a solution that both meets our output documentation needs and automatically updates with code changes, and Swagger is the kind of tool that helps us solve interface documentation problems.
Take the gin framework as an example, using the gin-swagger library to automatically generate RESTful API documentation using Swagger 2.0.
gin-swagger combat
To use gin-swagger to automatically generate interface documentation for your code, there are generally three steps:
Add declarative comments to the interface code according to swagger requirements, refer to declarative comment format for details.
Scan code with swag tool to automatically generate API interface documentation data
Rendering online interface documentation pages using gin-swagger
Step 1: Add comments
Write project information in comments on the program entry main function.
package main// @title Write title here// @version 1.0// @description Write description herecontact.name @ www. example. com Write contact information here//support@swagger.io// @ www. example. license.name Apache 2.0// @license.url http://www.apache.org/licenses/LICENSE-2.0.html// @host Write host of interface service here// @BasePath Write base pathfunc main() {contact.email http://www.swagger.io/support//http://swagger.io/terms/// r := gin.New() // liwenzhou.com ... r.Run()}
The interface functions that handle requests in your code (usually at the controller level) are commented as follows:
//GetPostListHandler2 Upgraded Post List Interface// @Summary Upgraded Post List Interface// @Description Query Post List Interface by Community Sorted by Time or Score// @Tags Post Related Interface// @Accept application/json// @Produce application/json// @Param Authorization header string false "Bearer User Token"// @Param object query models.ParamPostList false "Query Parameters"// @Security ApiKeyth// @Success 200 {object} _ResponsePostList// @Router /posts2 [get]func GetPostListHandler2(c *gin.Context) { // GET request parameters (query string):/api/v1/posts2? page=1&size=10&order=time //Specify initial parameters when initializing a structure p := &models.ParamPostList{ Page: 1, Size: 10, Order: models.OrderTime, } if err := c.ShouldBindQuery(p); err != nil { zap.L().Error("GetPostListHandler2 with invalid params", zap.Error(err)) ResponseError(c, CodeInvalidParam) return } data, err := logic.GetPostListNew(p) //Get data if err != nil { zap.L().Error("logic.GetPostList() failed", zap.Error(err)) ResponseError(c, CodeServerBusy) return } ResponseSuccess(c, data) //return response}
In the above comments, the parameter type uses object, and the specific definition of models.ParamPostList is as follows:
// bluebell/models/params.go// ParamPostList Get list of posts query string parameter type ParamPostList struct { CommunityID int64 `json:"community_id" form:"community_id"` //can be empty Page int64 `json:"page" form:"page" example:"1"` //page number Size int64 `json:"size" form:"size" example:"10"` //Amount of data per page Order string `json:"order" form:"order" example:"score"` //sort by}
The response data type also uses object, and I personally have a habit of defining a docs_models.go file at the controller layer to store the response data model used in the document.
// bluebell/controller/docs_models.go// _ResponsePostList interface response data type _ResponsePostList struct { Code ResCode `json:"code"` //Service Response Status Code Message string `json:"message"` //prompt message Data []*models.ApiPostDetail `json:"data"` //Data} Step 2: Generate interface document data
After you write your comments, install the swag tool using the following command:
go get -u github.com/swaggo/swag/cmd/swag
Use the swag tool to generate interface documentation data by executing the following command in the project root directory.
swag init
After executing the above command, if your comments are formatted correctly, you will have an additional docs folder in your project root directory.
./ docs <$── docs.go <$── swagger.json <$── swagger.yaml Step 3: Introducing gin-swagger to render document data
Then introduce the gin-swagger correlation in the project code where the route is registered as follows:
import ( // liwenzhou.com ... _ "bluebell/docs" //Don't forget to import the docs you generated last step gs "github.com/swaggo/gin-swagger" "github.com/swaggo/gin-swagger/swaggerFiles" "github.com/gin-gonic/gin")
Register swagger api related routes
r.GET("/swagger/*any", gs.WrapHandler(swaggerFiles.Handler))
To get your project up and running, open your browser and visit http://localhost:8080/swagger/index.html to see the Swagger 2.0 Api documentation.
gin-swagger also provides a DisablingWrapHandler function that allows us to disable Swagger by setting certain environment variables. For example:
r.GET("/swagger/*any", gs.DisablingWrapHandler(swaggerFiles.Handler, "NAME_OF_ENV_VARIABLE"))
If the environment variable NAME_OF_ENV_VARIABLE is set to any value,/swagger/*any returns a 404 response, just as if no route was specified.
The content of "golang component swagger generation interface document method" is introduced here, thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the industry information channel. Xiaobian will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.