As someone who offers a REST API, we at Romana project wanted to provide documentation on it via Swagger. But writing out JSON files by hand seemed not just tedious (and thus error-prone), but also likely to result in an outdated documentation down the road.
Why not automate this process, sort of like godoc? Here I walk you through an initial attempt at doing that — a Go program that takes as input Go-based REST service code and outputs Swagger YAML files.
It is not yet available as a separate project, so I will go over the code in the main Romana code base.
NOTE: This approach assumes the services are based on the Romana-specific REST layer on top of Negroni and Gorilla MUX. But a similar approach can be taken without Romana-specific code — or Romana approach can be adopted.
The entry point of the doc tool for generating the Swagger docs is in doc.go.
The first step is to run Analyzer on the entire repository. The Analyzer:
- Walks through all directories and tries to import each one (using Import()). If import is unsuccessful, skip this step. If successful, it is a package.
- For each *.go and *.cgo file in the package, parse the file into its AST
- Using the above, compute docs and collect godocs for all methods
The next step is to run the Swaggerer — the Swagger YAML generator.
At the moment we have 6 REST services to generate documentation for. For now, I’ll explicitly name them in main code. This is the only hardcoded/non-introspectable part here.
From here we, for each service, Initialize Swaggerer and call its Process() method, which will, in turn, call the main workhorse, the getPaths() method, which will, for each Route:
- Get its Method and Pattern — e.g., “POST /addresses”
- Get the Godoc string of the Handler (from the Godocs we collected in the previous step)
- Figure out documentation for the body, if any. For that, we use reflection on the MakeMessage field — the mechanism we used for sort-of-strong-dynamic typing when consuming data, as seen in a prior installment on this topic.
This is pretty much it.
As an example, here is Swagger YAML for the Policy service.