Site icon Golang Libraries, Apps, Golang Jobs and Go Tutorials

How to create linter rules for Golang

Linters are the tools that help us write better source code. The first Linter was developed in 1978, as a means to analyze source code. Since then, Linters have evolved to perform tasks beyond their original specification. Nowadays, Linters can “perform Static Analysis, enforce configuration flags, check for compliance with a given style-guide or security rule, and a lot more.” Go’s standard library ships with a command gofmt , gofmt performs static analysis on specified source code. The command can also rewrite source code to improve formatting. gofmt is a Go Linter.

The OSS community offers its set of Go Linters as well. One of my favorite OSS projects is go-ruleguard . I find it useful because Go code defines the rules dynamically. go-ruleguard has a custom command to perform source code analysis. To run the command, you need to specify the go source with the rules and the files to analyze. If used correctly, go-ruleguardis a powerful tool to master.

Writing a linter rule for golang

The first rule I wrote detects if strings are being appended together with the + operator. Joining strings this way is not efficient on a large scale, hence my motivation for writing this. I began by writing source code that would break the rule on purpose. Here is the content of file main.go :

main.go

Next, I’ll create a file named rules.go , it’ll house my Linter rules :


There is no ads to display, Please add some
Exit mobile version