Lint your #golang code like a mad man!

Arsham Shirvani
2 min readJan 6, 2017

--

I use the following linters to lint my codes while excluding the vendor directory. I’m using GNU/Linux but with a little tweak you should be able to use the following scripts in your OS of choice. I use glide for vendoring, but you can easily replace the “glide nv” part with your vendoring tool. It lists all folders except the vendor folder, which is handy. In some cases “glide nv” didn’t do the job, so I had to do it in the old fashion way.

Note: I use the $ sign to indicate it’s a shell prompt.

Gofmt should be already installed with your go binary. To fmt your code run:

$ find . -name "*.go" -not -path "./vendor/*" -not -path ".git/*" | xargs gofmt -s -d

Gocyclo calculate cyclomatic complexities of functions in Go source code.

To install:

$ go get -u github.com/fzipp/gocyclo

Usage:

$ gocyclo -over 12 $(ls -d */ | grep -v vendor)

It lists all the codes with complexity of over 12. You also can list the top 10 (or any other numbers) by doing:

$ gocyclo -top 10 $(ls -d */ | grep -v vendor)

Interfacer is an interesting one. From author:

A linter that suggests interface types. In other words, it warns about the usage of types that are more specific than necessary.

Installation:

$ go get -u github.com/mvdan/interfacer/cmd/interfacer

Usage:

$ interfacer $(glide nv)

Deadcode will tell you any unused code snippets. To install:

$ go get -u github.com/tsenart/deadcode

Usage:

$ find . -type d -not -path "./vendor/*" | xargs deadcode

The gotype command does syntactic and semantic analysis of Go files and packages like the front-end of a Go compiler.

Installation:

$ go get -u golang.org/x/tools/cmd/gotype

Usage:

$ find . -name "*.go" -not -path "./vendor/*" -not -path ".git/*" -print0 | xargs -0 gotype -a

Spell checking:

$ go get -u github.com/client9/misspell

Usage:

$ find . -type f -not -path "./vendor/*" -print0 | xargs -0 misspell

Staticcheck is go vet on steroids, applying a ton of static analysis checks you might be used to from tools like ReSharper for C#.

Installation:

$ go get -u honnef.co/go/staticcheck/cmd/staticcheck

Usage:

$ staticcheck $(glide nv)

Gosimple is a linter for Go source code that specialises on simplifying code.

Installation:

$ go get -u honnef.co/go/simple/cmd/gosimple

Usage:

$ gosimple $(glide nv)

goconst From author:

Find in Go repeated strings that could be replaced by a constant

Installation:

$ go get -u github.com/jgautheron/goconst/cmd/goconst

Usage:

$ goconst ./… | grep -v vendor

Happy coding!

--

--