I recently assembled a CLI app using Go and Open API and wanted to share some of the process.
Summary of Steps
- Acquire an Open API spec
- Generate a Go API client using OpenAPI Generator
- Generate a Go CLI using Cobra
- Integrate the API Client into the CLI
I wanted to automate pulling search results from Sumo Logic, and took a look at the Search Job API. Sumo Logic provides a pretty robust Open API spec for most of the APIs they offer, but unfortunately Search Job API is not covered. I started from their existing API spec, and adapted it for the Search Job API using the provided Search Job API documentation. The API spec can be referenced here.
After the API spec was assembled, I was able to use that to generate a Go API client library using the OpenAPI Generator command line tool:
openapi-generator-cli generate -i sumologic-search-job-api.yaml -g go -o client
Many programming languages besides Go are supported by the openapi-generator tool. This is great because it makes it easy to create any API client you need from a single spec resource.
I published the API client to a new GitHub repository, which I was then able to reference as a dependency.
For the CLI, I initialized a new Go project and pulled in the API client:
mkdir sumo-search-job-cli cd sumo-search-job-cli go mod init sumo-search-job-cli go get github.com/nhoag/sumologic-search-job-client-go
I then added the Cobra Go CLI framework as a dependency and got to work generating the CLI and commands:
cobra init --viper cobra add command-name
I added a command for each available operation, including a
execute function for each. I also created an interface to the API client library for handling shared configuration injection logic that might be coming from a config file or from command options. I then created a “full process” command to tie everything together into a single user action. This was pretty convenient, as I could reference
execute functions from atomic commands when creating the “full process” command.
The final product for the CLI can be found on GitHub. Instructions for installation and usage are provided in the README and via command help (