How to format your Go projects with gofmt, goimports and git

Rafał Gałus
2 min readMar 7, 2020

Keeping your code well formatted is a good practice. Sometimes formatting is sacrificed for delivery time but it comes back eventually. Readability suffers, maintainability too. You need to do small change in the project but you can’t stand this ugly code and you try to fix that too. In the end your small change is flooded with formatting fixes and code review suffers from that. Writing clean, well formatted code should be a habit for every developer and there are tools that can help.

gofmt is a tool that you can use to check your code formatting. You can find documentation here https://golang.org/cmd/gofmt/. It’s very easy to use and can automatically update your file or whole directories with correct formatting. As in example below:

We can see above that wrong indentation and too many blank lines are fixed.

goimports is another tool that do what gofmt does but also adds missing imports, sorts them and groups into native Go and third-party modules. Docs are available here https://godoc.org/golang.org/x/tools/cmd/goimports. Personally I also separate third group of modules that contains internal packages.

Above we can see that goimports have moved Go modules to the top and separated third-party modules with blank line:

Git provides us with hooks that we can use to apply additional checks on pre-commit, pre-push, etc. so you can integrate Go tools with them to make sure that formatting in your project is nice and cool.

For my use case I’ve chosen pre-commit hook and I’ve created small shell script so everyone involved with the project can easily run it and install hook on his local environment. The file looks like this:

The whole file is about putting stringified shell script into pre-commit file in Git hooks directory. The main logic of the hook is in this stringified code. There we are defining GOIMPORTS variable that contains path to goimports binary using GOPATH environment variable. Then we check if the binary exists, if not we throw an error with the message how to install it. Otherwise we run it, check if it listed any files with bad formatting, if yes we provide error message and abort the commit. Otherwise we continue and commit is made successfully.

This way every time you do git commit, pre-commit hook will check your code so you know that files in your remote repository are properly formatted.

You can’t ensure that everyone will have the hook installed though, so you can implement the same formatting checks in your CI pipeline.

--

--

Rafał Gałus

software development engineer with passion for coding