Swagger allows developers to easily create api documentation which is defined using comments in the code and then generated as a yaml config file. In this post we’ll be using it alongside Go (golang).
Using tools like Swagger has many advantages, like allowing you to generate documentation automatically (saving you time) and that it keeps your code and documentation as close as possible (in distance terms). The idea being that if the docs are hard to update and far away, you just won’t.
Definitions are show like below, where we give the documentation a title:
1
// @title My API documentation
1. Grab the packages you need
We use the http-swagger package, which provides us with some middleware for showing the docs in our app.
1
go get "github.com/swaggo/http-swagger"
Run the command above to install it into your project.
2. Install Swag (cmd swagger generator)
We’ll also need the “Swag” tool to read our comments and generate the swag definition file.
Put it all together and we have our code, like shown below. The code could be shown in more detail, as many projects will - but it does show us a working example.
The important bit is add adding _ "swaggerexample/docs" and making a new router endpoint for it.
packagemainimport("encoding/json""log""net/http""os"// Super important: import the docs into project
// we used "swaggerexample" as that was our project name, use your own.
_"swaggerexample/docs"// Import the swagger docs middleware
httpSwagger"github.com/swaggo/http-swagger")typeHealthCheckResponsestruct{Resultstring`json:"result" example:"ok"`}// @title My API documentation
// @version 0.1
// @description A collection of fun related api endpoints.
// termsOfService http://swagger.io/terms/
// @x-logo {"url": "https://example.com/img.png", "backgroundColor": "#000000", "altText": "example logo", "href": "https://example.com/img.png"}
// contact.name API Support
// @contact.url https://gophercoding.com
// contact.email support@gophercoding.com
// @host api.gophercoding.com
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization
funcmain(){http.HandleFunc("/v1/health-check",HealthCheckHandler)http.HandleFunc("/docs/",httpSwagger.WrapHandler)http.HandleFunc("/",RootHandler)port:=os.Getenv("PORT")ifport==""{port="8080"}log.Println("App started on http://localhost:"+port)iferr:=http.ListenAndServe(":"+port,nil);err!=nil{panic(err)}}funcRootHandler(whttp.ResponseWriter,r*http.Request){http.Redirect(w,r,"/docs/",http.StatusTemporaryRedirect)}// HealthCheckHandler shows if the api is running
// @Summary Health Check
// @Description check api is running
// @Accept json
// @Produce json
// @Tags Tools
// @Security ApiKeyAuth
// @Success 200 {object} HealthCheckResponse
// @Router /v1/health-check [get]
funcHealthCheckHandler(whttp.ResponseWriter,r*http.Request){varhcHealthCheckResponsehc.Result="ok"json.NewEncoder(w).Encode(hc)}
Edd is a PHP and Go developer who enjoys blogging about his experiences, mostly about creating and coding new things he's working on and is a big beliver in open-source and Linux.