go-generate
Generate Go source code
TLDR
Generate Go files by running commands within source files
SYNOPSIS
go generate [build flags] [packages]
Examples:
go generate
go generate ./...
go generate -run "stringer" ./pkg/mytypes
go generate -v -x
PARAMETERS
-run regexp
Only commands whose directives match the provided regular expression are executed. Useful for running specific generation steps, particularly in projects with many //go:generate lines.
-v
Prints the names of packages as they are processed by go generate, providing verbose output about the progress.
-n
Performs a dry run; it prints the commands that would be executed but does not actually run them. This is useful for debugging or previewing the generation process without making changes.
-x
Prints the commands as they are executed, showing the exact command lines being run, including any environment variables expanded.
[packages]
Specifies which Go packages to generate. If omitted, go generate operates on the package in the current working directory. This can be a package path (e.g., ./... to generate all packages in the current directory and its subdirectories, or github.com/my/project for a specific remote package).
DESCRIPTION
The go generate command is a powerful tool part of the Go ecosystem, designed to automate the execution of external commands defined within Go source files. It scans Go files (ending in .go) for lines containing the special directive //go:generate, followed by a command string. When found, go generate executes these commands in the context of the package containing the directive. This mechanism is crucial for tasks like
generating boilerplate code, embedding static assets, creating mock interfaces, processing protocol buffers, or any other pre-build steps that are not natively handled by the Go compiler. It standardizes and makes explicit the external dependencies and build-time transformations required for a Go project, ensuring reproducibility across different development environments. By integrating these steps directly into the source code, go generate simplifies the build process, making projects easier to maintain and share.
CAVEATS
Security Risk: go generate executes arbitrary commands found in source files. Exercise caution when running it on untrusted code, as it could lead to arbitrary code execution on your system.
External Dependencies: The commands specified in //go:generate directives must be installed and accessible in the system's PATH. go generate does not manage the installation or versioning of these external tools.
Performance: For large projects with numerous generation steps or complex commands, go generate can be time-consuming, as it executes commands sequentially per directive within a package.
Environment Variables: The special environment variables ($GOFILE, $GOLINE, etc.) are only available within the command executed by go generate. These are not general shell variables and are reset for each directive.
DIRECTIVE FORMAT AND ENVIRONMENT VARIABLES
The //go:generate directive must appear as a full line comment in a Go source file, typically at the top or immediately after the package clause. The command string following the directive is executed as if by a shell. Before executing the command, go generate sets several useful environment variables specific to the current context:
$GOARCH (target architecture), $GOOS (target operating system), $GOFILE (name of the current Go file), $GOLINE (line number of the directive), $GOPACKAGE (name of the Go package), $GOROOT (Go installation root), and $GOPATH (Go workspace). These variables enable the generation command to be context-aware and flexible, for instance, by operating on the specific file it was found in.
COMMON USE CASES
go generate is widely adopted for automating various development tasks:
• Stringer: Automatically generating String() methods for iota-defined constants or custom types, improving readability and debugging.
• Mocking Frameworks: Creating mock implementations of interfaces for robust unit testing (e.g., using mockgen or go.mock).
• Asset Embedding: Bundling static assets (like HTML templates, CSS, JavaScript, images) directly into Go binaries, making them self-contained and easy to deploy.
• Protocol Buffers/gRPC: Generating Go code from .proto definitions for data serialization and RPC service definitions.
• Schema/Model Generation: Automatically creating Go structs from database schemas, API definitions (e.g., OpenAPI), or JSON/YAML files.
HISTORY
The go generate command was introduced with Go 1.4, released in December 2014. Its inception addressed a long-standing need within the Go community for a standardized way to automate pre-processing and code generation steps that are integral to a project's build but fall outside the scope of the Go compiler itself. Prior to its introduction, developers often relied on custom shell scripts, Makefiles, or other build automation tools, which introduced inconsistencies and portability issues across different development environments. go generate provided a Go-native, declarative mechanism to embed these automation instructions directly within the source code, thereby simplifying project setup and ensuring that necessary code generation steps are always performed as part of a Go project's build lifecycle.