goimports
Automatically update Go import lines
TLDR
Display the completed import source file
Write the result back to the source file instead of stdout
Display diffs and write the result back to the source file
Set the import prefix string after 3rd-party packages (comma-separated list)
SYNOPSIS
goimports [flags] [path ...]
PARAMETERS
-d
Do not write to standard output. Check if the files are formatted correctly and print diffs to standard output.
-e
Report all errors (not just the first 10 on different lines).
-l
Do not write to standard output. List files whose formatting differs from goimports's.
-w
Do not write to standard output. Instead overwrite the files with goimports's results. If a write fails, the file's contents are likely lost.
-srcdir directory
Specify source directory for checking; useful for generated code.
-local package-prefix
Put imports beginning with this import path after 3rd-party packages; comma-separated list.
path
The path to the Go source file or directory to format.
DESCRIPTION
goimports is a tool for automatically formatting Go source code and managing import statements. It simplifies the process of organizing imports by automatically adding missing imports and removing unreferenced ones. It also formats code according to the standard Go style guidelines (similar to gofmt), ensuring consistency across projects. goimports is particularly useful in larger projects where manually managing imports can become tedious and error-prone.
The tool analyzes the Go source code, determines the necessary imports based on the used packages, and updates the import block accordingly. This eliminates the need for developers to manually add or remove imports, reducing the risk of errors and saving time. It runs as a gofmt wrapper. It takes the output of gofmt and then re-writes your imports to be properly grouped and sorted.
EXIT STATUS
The exit status is 0 if no errors occur during processing, and non-zero otherwise. The exit status is non-zero if any files were reformatted when using the -l option. The exit status is non-zero if the -d flag is used and differences exist.
USAGE EXAMPLES
Format a single file:
goimports my_file.go
Format all Go files in a directory:
goimports my_directory
Format all Go files in the current directory and subdirectories and overwrites the files:
goimports -w .
HISTORY
goimports was created to improve Go code formatting and import management. It evolved from gofmt by adding automatic import management capabilities. It became a standard tool for Go developers, simplifying project maintenance and improving code readability. Over time, it has been refined to handle more complex import scenarios and edge cases.