Tuesday, August 9, 2022
HomeWeb DevelopmentLinting Go applications: A information to enhancing code high quality

Linting Go applications: A information to enhancing code high quality


Utilizing linters improves readability by highlighting issues earlier than they’re executed, and it helps with the standardization of your codebase. An excellent linter has configuration settings that assist to minimize warnings for guidelines you don’t care about, making code simpler to understand, modify, and keep.

On this article, we’ll be studying extra about linting via these matters:

golint has been probably the most broadly used linter for Go over time. Sadly, it’s now formally deprecated and archived. The problem with golint is that it doesn’t provide any configuration choices and at all times applies all the principles, which results in warnings for guidelines you don’t care about. On this article, we’ll use the revive bundle in addition to exploring different go linting packages.

Conversely, revive is a quick, configurable, extensible, adaptable, and delightful linter for Go. It serves as golint’s drop-in alternative.

Right here’s how revive is completely different from golint:

  • Permits us to allow or disable guidelines utilizing a configuration file
  • Permits us to configure the linting guidelines with a TOML file
  • Is 2 instances quicker working the identical guidelines as golint
  • Gives performance for disabling a selected rule or your complete linter for a file or a variety of traces (golint permits this just for generated information)
  • Optionally available sort checking. Most guidelines in golint don’t require sort checking. In the event you disable them within the config file, revive will run over six instances quicker than golint
  • Gives a number of formatters that allow us customise the output
  • Permits us to customise the return code for your complete linter or primarily based on the failure of just some guidelines
  • Everybody can prolong it simply with customized guidelines or formatters
  • revive offers extra guidelines in comparison with golint

Establishing a venture with revive

Open a terminal and create a venture folder. Navigate to the venture folder and run the next command to start out a brand new venture:

go mod init venture

Navigate to your Go venture and run the next command to put in the revive linter bundle:

go set up github.com/mgechev/[email protected]

Create a essential.go file and add the next code snippet to the essential.go file:

bundle essential
import (
    "fmt"
)
func essential() {
    PrintName("Emmanuel")
    PrintAge(23)
}
func PrintName(title string) {
    fmt.Println(title)
}
func PrintAge(age int) {
    fmt.Println(age)
}

Now, run the revive command on the venture terminal and you must get the next report:

essential.go:11:1: exported perform PrintName ought to have remark or be unexported
essential.go:15:1: exported perform PrintAge ought to have remark or be unexported

In Go, the primary letter of an exported perform is normally an uppercase. A correctly documented codebase requires that exported capabilities be commented with a quick overview of the perform’s goal, so everybody can perceive what it does. Now we are able to see how the revive bundle helps us write well-documented code.


Extra nice articles from LogRocket:


Now, let’s add some feedback to those capabilities:

...
// This perform makes use of the fmt.Println perform to print a string.
func PrintName(title string) {
    fmt.Println(title)
}
// This perform makes use of the fmt.Println perform to print a quantity.
func PrintAge(age int) {
    fmt.Println(age)
}

Execute the revive command and you must have the next report:

essential.go:12:1: touch upon exported perform PrintName ought to 
be of the shape "PrintName ..."
essential.go:17:1: touch upon exported perform PrintAge ought to be of the shape "PrintAge ..." 

Revive tells us that our remark ought to start with the title of our exported capabilities for a correctly documented codebase.

Let’s change our feedback to the next:

...
// PrintName makes use of the fmt.Println perform to print a string.
func PrintName(title string) {
    fmt.Println(title)
}
// PrintAge makes use of the fmt.Println perform to print a quantity.
func PrintAge(age int) {
    fmt.Println(age)
}

With this, execute the revive command and you should not have any report.

Suppressing linting errors with revive

Typically, it’s essential to disable particular linting points that seem in a file or bundle. Each feedback and exclusion guidelines within the configuration file can be utilized to do that. Let’s look at every technique in flip.

The feedback technique is useful if you need to disable warnings for a sure part of code however nonetheless need to apply the rule to different elements of the venture.

Right here is disable particular linting points utilizing feedback:

bundle essential
import (
    "fmt"
)
func essential() {
    PrintName("Emmanuel")
}
// revive:disable:exported
func PrintName(title string) {
    fmt.Println(title)
}

The syntax for that is revive, adopted by a colon, then disable. If desired, add one other colon adopted by the title of a linter rule.

Establishing configurations for linters

That is one superb characteristic of the revive linter bundle that deal with the most important problem with the favored golint linter bundle.

Let’s see configure the revive linter bundle to disable some linting guidelines with the intention to scale back pointless warnings.

Add a file named revive.toml to the venture folder with the default revive configuration:

ignoreGeneratedHeader = false
severity = "warning"
confidence = 0.8
errorCode = 0
warningCode = 0

[rule.blank-imports]
[rule.context-as-argument]
[rule.context-keys-type]
[rule.dot-imports]
[rule.error-return]
[rule.error-strings]
[rule.error-naming]
[rule.exported]
[rule.if-return]
[rule.increment-decrement]
[rule.var-naming]
[rule.var-declaration]
[rule.package-comments]
[rule.range]
[rule.receiver-naming]
[rule.time-naming]
[rule.unexported-return]
[rule.indent-error-flow]
[rule.errorf]
[rule.empty-block]
[rule.superfluous-else]
[rule.unused-parameter]
[rule.unreachable-code]
[rule.redefines-builtin-id]

Now, take away all feedback and run the next command to make use of the linter with the configuration file:

revive -config revive.toml

To disable any of those guidelines, you’ll be able to both take away them or add # earlier than the required rule as follows:

#[rule.exported]

Establishing linting in code editors

Some code editors assist linting code mechanically; Visible Studio Code is one in every of them.

Let’s see arrange the revive linter in Visible Studio Code.

Open VS Code and set up the go extension for VS Code. Then, choose the File tab > Preferences > Settings and add go.lint to the search discipline and choose revive within the Go: Lint Device part.

Go Lint in Search Field

The default Go linter for Visible Studio Code is staticcheck.

Exploring the go vet command

In distinction to linters, the go vet command identifies code that compiles however most likely gained’t carry out as supposed.

Let’s contemplate a standard self task bug in our Golang code. Replace essential.go file as follows:

bundle essential
import (
    "fmt"
)
func essential() {
    PrintName("Emmanuel")
}
// revive:disable:exported
func PrintName(title string) {
    title = title
    fmt.Println(title)
}

The above code will compile even with this bug. Executing the revive linter command gained’t report any problem regarding this bug. That is the place the go vet command is useful.

Run the go vet command and you must have the next end result as a substitute:

$ go vet
# pattern
.essential.go:10:2: self-assignment of title to call

Different packages for linting in Go

If revive isn’t your choice, here’s a record of Go linters which were constructed and maintained by the neighborhood.

golangci-lint

golangci-lint is a quick Go linters runner. It integrates with each main IDE, employs caching, permits YAML configuration, executes linters in parallel, and comes with a lot of linters.

staticcheck

staticcheck is a cutting-edge Go programming language linter. It employs static evaluation to establish bugs and efficiency issues, present simplifications, and implement model pointers.

Conclusion

Go takes documentation severely as a result of the better it’s for builders to provide good documentation, the higher for everybody.

On this article, we’ve explored linting in Golang, my most well-liked linting bundle, and different packages for linting in Go. I hope you’ll like working with revive!

: Full visibility into your net and cellular apps

LogRocket is a frontend utility monitoring resolution that allows you to replay issues as in the event that they occurred in your personal browser. As a substitute of guessing why errors occur, or asking customers for screenshots and log dumps, LogRocket permits you to replay the session to rapidly perceive what went incorrect. It really works completely with any app, no matter framework, and has plugins to log extra context from Redux, Vuex, and @ngrx/retailer.

Along with logging Redux actions and state, LogRocket data console logs, JavaScript errors, stacktraces, community requests/responses with headers + our bodies, browser metadata, and customized logs. It additionally devices the DOM to document the HTML and CSS on the web page, recreating pixel-perfect movies of even probably the most complicated single-page net and cellular apps.

.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments