Skip to content
Golang Tools πŸ› οΈ

Golang tools: your code’s best friends πŸ› οΈ

Ah, the wonderful world of Go tools. If you thought writing code was enough, get ready to discover a universe of tools that will make your code cleaner than a kitchen after a visit from the mother-in-law.

πŸ“ Gofmt: your code’s hairdresser

πŸ”— Official documentation

gofmt is Go’s official formatting tool. It doesn’t just format code, it also makes it comply with the Go community’s style conventions. The -s option applies simplifications to the code, -l lists modified files, and -w writes the changes directly to the files.

Benefits:

  • eliminates code-style debates within the team
  • ensures consistency across the whole codebase
  • improves code readability
  • reduces cognitive load during code review
1
2
3
4
5
6
7
8
# Format all Go files in the current directory and subdirectories
gofmt -s -l -w .

# Format a specific file
gofmt -s -w main.go

# Show diffs without modifying files
gofmt -d main.go
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// Before
type Person struct{
  Name string
  Age int
}

func (p Person)SayHello(){
  fmt.Println("Hello!")
}

// After gofmt
type Person struct {
  Name string
  Age  int
}

func (p Person) SayHello() {
  fmt.Println("Hello!")
}

πŸ” Golangci-lint: the perfectionist detective

πŸ”— Official documentation

golangci-lint is a meta-linter that combines dozens of static analyzers into a single tool. It doesn’t just find errors, it also suggests improvements for performance, security, and code maintainability.

Benefits:

  • finds bugs before they reach production
  • improves code quality through best practices
  • reduces technical debt
  • speeds up the code review process
1
2
3
4
5
6
7
8
# Run all enabled linters
golangci-lint run

# Run specific linters
golangci-lint run --disable-all --enable=errcheck,gosimple

# Analyze only files changed compared to main
golangci-lint run --new-from-rev=HEAD
1
2
3
4
5
6
7
8
9
# .golangci.yml example
linters:
  enable:
    - govet     # analyzes code for common mistakes
    - errcheck  # verifies error handling
    - staticcheck  # advanced static analyzer
    - gosimple  # simplifies code
    - dupl      # finds duplicated code
    - goconst   # finds strings that could be constants

πŸ› Go vet: your code’s doctor

πŸ”— Official documentation

go vet is a static analysis tool that finds subtle bugs the compiler might miss. It’s particularly good at catching errors in function calls, struct construction, and Printf usage.

Benefits:

  • catches subtle bugs before execution
  • improves code reliability
  • reduces production bugs
  • zero false positives
1
2
3
4
5
6
7
8
# Analyze the current package
go vet

# Analyze all packages in the project
go vet ./...

# Analyze a specific file
go vet main.go
1
2
3
4
func example() {
  var x string
  fmt.Printf("%d", x)  // go vet will flag this format error
}

πŸ”Ž Revive: the code inspector

πŸ”— Official documentation

revive is a fast, configurable, and extensible linter for Go. It’s like an inspector making sure your code follows all the rules of “programming etiquette”.

Benefits:

  • faster and more flexible than golint
  • highly configurable with customizable rules
  • supports excluding files and directories
  • generates reports in multiple formats (JSON, HTML, XML)
1
2
3
4
5
6
7
8
# Install revive
go install github.com/mgechev/revive@latest

# Run the base analysis
revive ./...

# Use a custom configuration
revive -config config.toml ./...
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# revive.toml example
ignoreGeneratedHeader = false
severity = "warning"
confidence = 0.8

[rule.cyclomatic]
  arguments = [15]
[rule.function-length]
  arguments = [50]
[rule.var-naming]
  arguments = [["ID", "URL"]]

πŸ”’ Gosec: the security guard

πŸ”— Official documentation

gosec is your code’s bodyguard. It searches for security vulnerabilities like a metal detector at the airport.

Benefits:

  • identifies critical security vulnerabilities
  • prevents common attacks
  • enforces security best practices
  • reduces the risk of data breaches
1
2
3
4
5
# Analyze all packages in the project
gosec ./...

# Analyze a specific file
gosec main.go
1
2
3
func insecure() {
  exec.Command("ls", os.Args[1]) // gosec will warn about the potential injection risk
}

🎯 Trivy: the dependency scanner

πŸ”— Official documentation

trivy is like a metal detector for vulnerabilities in your dependencies. Because even the packages you use might hide surprises.

Benefits:

  • scans for known vulnerabilities in dependencies
  • keeps the production environment secure
  • provides detailed reports
  • supports multiple technologies
1
2
3
4
5
# Scan the current directory for vulnerabilities
trivy fs .

# Scan a specific file
trivy fs main.go
1
2
3
# Sample output
CRITICAL go:gin-gonic/gin:v1.7.0
    β†’ Gin before v1.7.1 allows remote attackers to exploit a vulnerability in...

🐳 Hadolint: the Dockerfile art critic

πŸ”— Official documentation

hadolint is the art critic judging your Dockerfiles. Because even containers deserve some elegance.

Benefits:

  • enforces Dockerfile best practices
  • optimizes container images
  • reduces security vulnerabilities
  • improves maintainability
1
2
3
4
5
# Analyze a Dockerfile
hadolint Dockerfile

# Analyze a specific Dockerfile
hadolint -f json Dockerfile
1
2
3
4
5
6
# Hadolint approves πŸ‘
FROM golang:1.21-alpine
COPY . /app
WORKDIR /app
RUN go build -o main .
CMD ["./main"]

πŸ•΅οΈ Trufflehog: the secret hunter

πŸ”— Official documentation

trufflehog is like a metal detector for secrets in your code. It finds passwords, API keys, and other secrets that shouldn’t be in the repository.

Benefits:

  • prevents sensitive data leaks
  • automates the search for exposed credentials
  • supports searching through Git history
  • reduces the risk of credential compromise
1
2
3
4
5
# Scan the entire repository for secrets
trufflehog --regex --entropy=True .

# Scan a specific file
trufflehog --regex --entropy=True main.go
1
2
3
# Sample output
Found possible AWS key in commit a1b2c3d4:
    AWS_SECRET_KEY=AKIAIOSFODNN7EXAMPLE

πŸ“ Ls-lint: the guardian of project structure

πŸ”— Official documentation

ls-lint is an ultra-fast linter for file and directory structure. It ensures file and folder names follow the team’s conventions.

Benefits:

  • keeps the project structure consistent
  • prevents naming confusion
  • speeds up code navigation
  • zero dependencies and simple configuration
1
2
3
4
5
# Install ls-lint
npm install -g @ls-lint/ls-lint

# Run ls-lint
ls-lint
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# .ls-lint.yml example
ls:
  .dir: kebab-case
  .go: kebab-case
  models:
    .go: PascalCase
  handlers:
    .go: snake_case

ignore:
  - node_modules
  - .git

πŸ’‘ Conclusion

These tools are like a team of superheroes protecting your code from bugs, vulnerabilities, and questionable formatting. Use them regularly and your code will thank you (and so will your teammates).

πŸ’ͺ Pro tip: integrate these tools into your CI/CD pipeline. It’s like having a review team that never complains about overtime!

πŸ”— Useful references

Last updated on