Sobes.tech
Junior

How to use linters in Go?

sobes.tech AI

Answer from AI

Linters in Go check code for errors, stylistic inconsistencies, and potential issues without executing it.

Main steps for using linters:

  1. Tool installation: The most popular is golangci-lint, which combines many linters.

    # Installing golangci-lint
    go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
    
  2. Configuration (optional): Create a .golangci.yml file in the project root for configuring linters, rules, and exclusions.

    # .golangci.yml
    run:
      timeout: 5m
    
    linters:
      enable:
        - gofmt
        - goimports
        - revive
        # Add other linters as needed
      disable:
        - errcheck # Example of disabling
    
  3. Running the linter: Execute the command in the project root to check the code.

    # Check current directory and subdirectories
    golangci-lint run ./...
    
    # Automatically fix some errors (e.g., formatting)
    golangci-lint run --fix ./...
    
  4. Integration into CI/CD: Add a linter check step into the continuous integration pipeline for automatic verification of each commit/pull request.

Examples of common linters included in golangci-lint:

Linter Purpose
gofmt Code formatting according to standards
goimports Ordering and adding/removing imports
revive More flexible and configurable golint
errcheck Checking for ignored error errors
staticcheck Detecting static errors and atypical constructs
unused Finding unused code