Don’t Commit Improperly Formatted Go (golang) Code

I work on a lot of Go (golang) projects, and I still see simple things going wrong. One of them is improperly formatted Go code. I also include in the category of improperly formatted to mean any code that didn’t use go imports to sort the import statements.

On the surface, many people might think this is me being a little over-critical of the code quality. In part, that is true. However, the real issue is the fact that it creates unnecessary code-churn in your commits and code diffs. For instance, if I edit a file and make a one line change, but the code wasn’t formatted properly when I got to it, it may result in 10 lines of code changing that have nothing to do with my actual change. This leads to confusion in PR reviews, changes the blame on a line of code that shouldn’t have changed, etc.

All of this is very avoidable if you are using a technology like git and employ a hook.

You’ll find a directory in your git project at the root in .git/hooks. In there will already be some .sample hooks for you to look at. We are interested in the pre-commit hook.

This is what my pre-commit hook looks like for all of my Go projects:

Note: I didn’t come up with this pre-commit file. I learned this trick working with the great developers at Influx Data.

I have this in a gist as well. To install this gist in a pre-commit hook for your project, run these commands (be sure to be in the root of your project first):

And that’s it! Now, the next time you try to commit code that doesn’t pass go fmt or go vet you will get an error like this:

Feel free to contact me with suggestions and feedback on this article on twitter.

Are you a company looking for Buffalo or Go training? The Gopher Guides want to help. We offer a variety of options, including In Person Training, Instructor Led Online Workshops, Consulting, and Support Contracts, and our self paced Online Video Learning.

Get your first 3 months of www.gopherguides.tv for 25% off and use the code medium. This offer is only good for a limited time, and a limited number, so act fast!

--

--

Cory LaNou a full stack technologist who has specialized in start-ups for the last 20 years. Cory enjoys mentoring budding technologists and entrepreneurs .

Love podcasts or audiobooks? Learn on the go with our new app.

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
Cory LaNou

Cory LaNou

Cory LaNou a full stack technologist who has specialized in start-ups for the last 20 years. Cory enjoys mentoring budding technologists and entrepreneurs .