How to Use goimports for Import Management

Cli
Use `goimports` to automatically format your Go code and manage imports by adding missing ones, removing unused ones, and grouping them in the standard order.

Use goimports to automatically format your Go code and manage imports by adding missing ones, removing unused ones, and grouping them in the standard order. It is a drop-in replacement for gofmt that handles import logic while maintaining the same formatting rules, making it ideal for keeping your codebase clean and consistent.

Install the tool via go install if you haven't already:

go install golang.org/x/tools/cmd/goimports@latest

Once installed, you can format a single file or an entire directory. The -w flag writes the changes directly to the file, while omitting it prints the formatted output to stdout.

# Format a single file and write changes back
goimports -w main.go

# Format all Go files in the current directory and subdirectories
goimports -w ./...

For CI/CD pipelines or pre-commit hooks, you can check if files are already formatted without modifying them by using the -d (diff) flag. This returns a non-zero exit code if changes are needed, which is useful for failing builds on style violations.

# Check for formatting issues without modifying files
goimports -d ./...

You can also configure goimports to respect local import paths or specific formatting rules by setting the GOIMPORTSFLAGS environment variable or using the -local flag to prioritize local packages in the import grouping. For example, if your project is github.com/myorg/myproject, you can ensure imports from that organization are grouped together:

goimports -local=github.com/myorg -w ./...

Integrating this into your editor is highly recommended. Most Go editors (VS Code, GoLand, Vim with Go plugin) have built-in support or extensions that run goimports on save. In VS Code, ensure the gofmt tool setting is set to goimports in your settings.json:

{
    "go.formatTool": "goimports"
}

This setup ensures that every time you save a file, imports are automatically organized and unused ones are removed, preventing merge conflicts related to import ordering and keeping your code compliant with Go standards without manual intervention.