1 # Go {#sec-language-go}
3 ## Building Go modules with `buildGoModule` {#ssec-language-go}
5 The function `buildGoModule` builds Go programs managed with Go modules. It builds [Go Modules](https://go.dev/wiki/Modules) through a two phase build:
7 - An intermediate fetcher derivation called `goModules`. This derivation will be used to fetch all the dependencies of the Go module.
8 - A final derivation will use the output of the intermediate derivation to build the binaries and produce the final output.
10 ### Example for `buildGoModule` {#ex-buildGoModule}
12 The following is an example expression using `buildGoModule`:
16 pet = buildGoModule rec {
20 src = fetchFromGitHub {
24 hash = "sha256-Gjw1dRrgM8D3G7v6WIM2+50r4HmTXvx0Xxme2fH9TlQ=";
27 vendorHash = "sha256-ciBIR+a1oaYH+H1PcC8cD8ncfJczk1IiJ8iYNM+R6aA=";
30 description = "Simple command-line snippet manager, written in Go";
31 homepage = "https://github.com/knqyf263/pet";
32 license = lib.licenses.mit;
33 maintainers = with lib.maintainers; [ kalbasit ];
39 ## Attributes of `buildGoModule` {#buildgomodule-parameters}
41 Many attributes [controlling the build phase](#variables-controlling-the-build-phase) are respected by `buildGoModule`. Note that `buildGoModule` reads the following attributes also when building the `vendor/` goModules fixed output derivation as well:
43 - [`sourceRoot`](#var-stdenv-sourceRoot)
44 - [`prePatch`](#var-stdenv-prePatch)
45 - [`patches`](#var-stdenv-patches)
46 - [`patchFlags`](#var-stdenv-patchFlags)
47 - [`postPatch`](#var-stdenv-postPatch)
48 - [`preBuild`](#var-stdenv-preBuild)
49 - `env`: useful for passing down variables such as `GOWORK`.
51 To control test execution of the build derivation, the following attributes are of interest:
53 - [`checkInputs`](#var-stdenv-checkInputs)
54 - [`preCheck`](#var-stdenv-preCheck)
55 - [`checkFlags`](#var-stdenv-checkFlags)
57 In addition to the above attributes, and the many more variables respected also by `stdenv.mkDerivation`, `buildGoModule` respects Go-specific attributes that tweak them to behave slightly differently:
59 ### `vendorHash` {#var-go-vendorHash}
61 Hash of the output of the intermediate fetcher derivation (the dependencies of the Go modules).
63 `vendorHash` can be set to `null`.
64 In that case, rather than fetching the dependencies, the dependencies already vendored in the `vendor` directory of the source repo will be used.
66 To avoid updating this field when dependencies change, run `go mod vendor` in your source repo and set `vendorHash = null;`.
67 You can read more about [vendoring in the Go documentation](https://go.dev/ref/mod#vendoring).
69 To obtain the hash, set `vendorHash = lib.fakeHash;` and run the build. ([more details here](#sec-source-hashes)).
70 Another way is to use use `nix-prefetch` to obtain the hash. The following command gets the value of `vendorHash` for package `pet`:
75 nix-prefetch -E "{ sha256 }: ((import ./. { }).my-package.overrideAttrs { vendorHash = sha256; }).goModules"
78 `vendorHash` can be overridden with `overrideAttrs`. Override the above example like this:
82 pet_0_4_0 = pet.overrideAttrs (
83 finalAttrs: previousAttrs: {
85 src = fetchFromGitHub {
86 inherit (previousAttrs.src) owner repo;
87 rev = "v${finalAttrs.version}";
88 hash = "sha256-gVTpzmXekQxGMucDKskGi+e+34nJwwsXwvQTjRO6Gdg=";
90 vendorHash = "sha256-dUvp7FEW09V0xMuhewPGw3TuAic/sD7xyXEYviZ2Ivs=";
96 ### `proxyVendor` {#var-go-proxyVendor}
98 If `true`, the intermediate fetcher downloads dependencies from the
99 [Go module proxy](https://go.dev/ref/mod#module-proxy) (using `go mod download`) instead of vendoring them. The resulting
100 [module cache](https://go.dev/ref/mod#module-cache) is then passed to the final derivation.
102 This is useful if your code depends on C code and `go mod tidy` does not include the needed sources to build or
103 if any dependency has case-insensitive conflicts which will produce platform-dependent `vendorHash` checksums.
108 ### `modPostBuild` {#var-go-modPostBuild}
110 Shell commands to run after the build of the goModules executes `go mod vendor`, and before calculating fixed output derivation's `vendorHash`.
111 Note that if you change this attribute, you need to update `vendorHash` attribute.
114 ### `modRoot` {#var-go-modRoot}
116 The root directory of the Go module that contains the `go.mod` file.
118 Defaults to `./`, which is the root of `src`.
120 ### `ldflags` {#var-go-ldflags}
122 A string list of flags to pass to the Go linker tool via the `-ldflags` argument of `go build`. Possible values can be retrieved by running `go tool link --help`.
123 The most common use case for this argument is to make the resulting executable aware of its own version by injecting the value of string variable using the `-X` flag. For example:
128 "-X main.Version=${version}"
129 "-X main.Commit=${version}"
134 ### `tags` {#var-go-tags}
136 A string list of [Go build tags (also called build constraints)](https://pkg.go.dev/cmd/go#hdr-Build_constraints) that are passed via the `-tags` argument of `go build`. These constraints control whether Go files from the source should be included in the build. For example:
147 Tags can also be set conditionally:
151 tags = [ "production" ] ++ lib.optionals withSqlite [ "sqlite" ];
155 ### `deleteVendor` {#var-go-deleteVendor}
157 If set to `true`, removes the pre-existing vendor directory. This should only be used if the dependencies included in the vendor folder are broken or incomplete.
159 ### `subPackages` {#var-go-subPackages}
161 Specified as a string or list of strings. Limits the builder from building child packages that have not been listed. If `subPackages` is not specified, all child packages will be built.
163 Many Go projects keep the main package in a `cmd` directory.
164 Following example could be used to only build the example-cli and example-server binaries:
175 ### `excludedPackages` {#var-go-excludedPackages}
177 Specified as a string or list of strings. Causes the builder to skip building child packages that match any of the provided values.
179 ### `CGO_ENABLED` {#var-go-CGO_ENABLED}
181 When set to `0`, the [cgo](https://pkg.go.dev/cmd/cgo) command is disabled. As consequence, the build
182 program can't link against C libraries anymore, and the resulting binary is statically linked.
184 When building with CGO enabled, Go will likely link some packages from the Go standard library against C libraries,
185 even when the target code does not explicitly call into C dependencies. With `CGO_ENABLED = 0;`, Go
186 will always use the Go native implementation of these internal packages. For reference see
187 [net](https://pkg.go.dev/net#hdr-Name_Resolution) and [os/user](https://pkg.go.dev/os/user#pkg-overview) packages.
188 Notice that the decision whether these packages should use native Go implementation or not can also be controlled
189 on a per package level using build tags (`tags`). In case CGO is disabled, these tags have no additional effect.
191 When a Go program depends on C libraries, place those dependencies in `buildInputs`:
202 `CGO_ENABLED` defaults to `1`.
204 ### `enableParallelBuilding` {#var-go-enableParallelBuilding}
206 Whether builds and tests should run in parallel.
210 ### `allowGoReference` {#var-go-allowGoReference}
212 Whether the build result should be allowed to contain references to the Go tool chain. This might be needed for programs that are coupled with the compiler, but shouldn't be set without a good reason.
216 ## Overriding `goModules` {#buildGoModule-goModules-override}
218 Overriding `<pkg>.goModules` by calling `goModules.overrideAttrs` is unsupported. Still, it is possible to override the `vendorHash` (`goModules`'s `outputHash`) and the `pre`/`post` hooks for both the build and patch phases of the primary and `goModules` derivation.
220 Alternatively, the primary derivation provides an overridable `passthru.overrideModAttrs` function to store the attribute overlay implicitly taken by `goModules.overrideAttrs`. Here's an example usage of `overrideModAttrs`:
224 pet-overridden = pet.overrideAttrs (
225 finalAttrs: previousAttrs: {
226 passthru = previousAttrs.passthru // {
227 # If the original package has an `overrideModAttrs` attribute set, you'd
228 # want to extend it, and not replace it. Hence we use
229 # `lib.composeExtensions`. If you are sure the `overrideModAttrs` of the
230 # original package trivially does nothing, you can safely replace it
231 # with your own by not using `lib.composeExtensions`.
232 overrideModAttrs = lib.composeExtensions previousAttrs.passthru.overrideModAttrs (
233 finalModAttrs: previousModAttrs: {
234 # goModules-specific overriding goes here
236 # Here you have access to the `vendor` directory.
237 substituteInPlace vendor/github.com/example/repo/file.go \
238 --replace-fail "panic(err)" ""
248 ## Controlling the Go environment {#ssec-go-environment}
250 The Go build can be further tweaked by setting environment variables. In most cases, this isn't needed. Possible values can be found in the [Go documentation of accepted environment variables](https://pkg.go.dev/cmd/go#hdr-Environment_variables). Notice that some of these flags are set by the builder itself and should not be set explicitly. If in doubt, grep the implementation of the builder.
252 ## Skipping tests {#ssec-skip-go-tests}
254 `buildGoModule` runs tests by default. Failing tests can be disabled using the `checkFlags` parameter.
255 This is done with the [`-skip` or `-run`](https://pkg.go.dev/cmd/go#hdr-Testing_flags) flags of the `go test` command.
257 For example, only a selection of tests could be run with:
261 # -run and -skip accept regular expressions
263 "-run=^Test(Simple|Fast)$"
268 If a larger amount of tests should be skipped, the following pattern can be used:
274 # Skip tests that require network access
277 "TestDatabase/with_mysql" # exclude only the subtest
281 [ "-skip=^${builtins.concatStringsSep "$|^" skippedTests}$" ];
285 To disable tests altogether, set `doCheck = false;`.
287 ## Migrating from `buildGoPackage` to `buildGoModule` {#buildGoPackage-migration}
290 `buildGoPackage` was removed for the 25.05 release. It was used to build legacy Go programs
291 that do not support Go modules.
294 Go modules, released 6y ago, are now widely adopted in the ecosystem.
295 Most upstream projects are using Go modules, and the tooling previously used for dependency management in Go is mostly deprecated, archived or at least unmaintained at this point.
297 In case a project doesn't have external dependencies or dependencies are vendored in a way understood by `go mod init`, migration can be done with a few changes in the package.
299 - Switch the builder from `buildGoPackage` to `buildGoModule`
300 - Remove `goPackagePath` and other attributes specific to `buildGoPackage`
301 - Set `vendorHash = null;`
302 - Run `go mod init <module name>` in `postPatch`
304 In case the package has external dependencies that aren't vendored or the build setup is more complex the upstream source might need to be patched.
305 Examples for the migration can be found in the [issue tracking migration withing nixpkgs](https://github.com/NixOS/nixpkgs/issues/318069).