snippets > bootstrap-go-cobra-application-with-modules

July 16, 2020

Bootstrap a Go Cobra application with Go Modules

To bootstrap a Go application using the Cobra Generator and Go Modules, start by installing the Cobra command line tool:

# Install Cobra
go get github.com/spf13/cobra/cobra

Initialize your Cobra project, remembering to use your package’s fully qualified name (e.g., github.com/laurybueno/kubectl-hoggers). It does not matter if your package is not publicly available yet. Additionally, there is no need to place your source code inside GOPATH anymore (since Go 1.11):

cobra init --pkg-name <fully_qualified_package_name>

Initialize your new module:

go mod init <fully_qualified_package_name>

Recursively get all dependencies and install the application:

go get -d -v ./...
go install -v ./...

Your application’s command line is now ready to use:

kubectl-hoggers

Further reading

Docker and Go: https://www.docker.com/blog/docker-golang/

Go Modules: https://github.com/golang/go/wiki/Modules