Static Analysis and Security

Overview

Go provides built-in and third-party tools for code quality and security analysis.

go vet

go vet ./...

Catches: - Printf format errors - Unreachable code - Suspicious constructs

staticcheck

go install honnef.co/go/tools/cmd/staticcheck@latest
staticcheck ./...

Catches: - Deprecated APIs - Simplifications - Performance issues

golangci-lint

# Install
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest

# Run all linters
golangci-lint run

govulncheck

go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...

Checks dependencies for known vulnerabilities.

gosec

go install github.com/securego/gosec/v2/cmd/gosec@latest
gosec ./...

Security-focused linter: - SQL injection - Hardcoded credentials - Weak crypto

Common Security Issues

// SQL injection - BAD
query := "SELECT * FROM users WHERE id = " + id

// Use parameters - GOOD
db.Query("SELECT * FROM users WHERE id = ?", id)

// Path traversal - BAD
path := filepath.Join(baseDir, userInput)

// Sanitize - GOOD
if strings.Contains(userInput, "..") {
    return errors.New("invalid path")
}

CI Integration

# .github/workflows/lint.yml
- name: Lint
  run: golangci-lint run

- name: Security scan
  run: |
    govulncheck ./...
    gosec ./...

Summary

Tool Focus
go vet Basic correctness
staticcheck Advanced analysis
golangci-lint Multiple linters
govulncheck Vulnerability scan
gosec Security issues