Creating a linter in Go is surprisingly easy! I wrote one and integrated it with golangci-lint to diagnose "fat contexts". This post documen

I wrote a linter!

submited by
Style Pass
2024-05-05 17:30:03

Creating a linter in Go is surprisingly easy! I wrote one and integrated it with golangci-lint to diagnose "fat contexts". This post documents the process.

A few weeks ago, I published an article titled Context-induced performance bottleneck in Go, in which I discuss a misuse of Go's context.Context. I didn't find any linter already handling this in golangci-lint, our meta linter of choice, so I decided to create one!

As it turns out, creating a linter is surprisingly easy. Since my intention was to add it to golangci-lint, I headed to their website and found they had published some guidance. This post from one of golangci-lint's maintainers was especially helpful and well written.

The meat of the linter is in pkg/analyzer/analyzer.go and it fits in ~115 lines of code, including ~30 lines just to suggest a fix (which golangci-lint doesn't even support yet).

Testing it was also simple (and built-in). You have to write a small test file which will trigger go/analysis test runner, and some source code as test cases. The test source should be annotated with special comments signaling to go/analysis/analysistest that we expect a report on a line. It will then ensure that your analysis is complete and precise:

Leave a Comment