Using Swagger To Document Your Go Application

Photo by Bernd Klutsch on Unsplash

Go, commonly referred to as “Golang”, is a great language for writing RESTful service applications. Every good service application should have documentation describing its endpoints for future consumers, even if that consumer is you. Enter Swagger, one the best ways to document RESTful APIs. In this article I’ll talk about using a tool called swag to document and generate an endpoint for viewing your documentation.

Let’s start with a small, simple example application that exposes an endpoint that returns an array of values. In this example I’ll be using a framework called Echo, though you can just use the vanilla Go HTTP router if you so choose.

Next let’s make some documentation. To get started you will need to install swag. This is a command line tool used to generate documentation from annotations in your Go source code.

Now let’s modify our example by adding annotations in comments that will be the source for generating documentation.

Notice how we’ve added the following to our source code:

  • We’ve added echoSwagger which is a wrapper for the Echo framework to serve generated swagger documentation
  • We’ve imported the package where generated docs will live. Notice in my project it is github.com/adampresley/example/docs. Change this to match your package structure.
  • We’ve added an endpoint at /swagger/* to serve all swagger content
  • We’ve added comment documentation to the main function and our endpoint handler function

Now, to see this in action open a terminal command prompt and execute the following (in your source code directory): swag init. This will generate Go and YML config files which contains your documentation and place them in a folder named docs.

Do a go run . to run your project. Open your browser and navigate to http://localhost:8080/swagger/index.html and see the magic!

That about sums it up. See the swag documentation for more information on how to annotate your code. Happy coding!

Just a guy who loves his wife, kids, and writing software.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store