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 ### Attributes of `buildGoModule` {#buildgomodule-parameters}
12 The `buildGoModule` function accepts the following parameters in addition to the [attributes accepted by both Go builders](#ssec-go-common-attributes):
14 - `vendorHash`: is the hash of the output of the intermediate fetcher derivation (the dependencies of the Go modules).
16 `vendorHash` can be set to `null`.
17 In that case, rather than fetching the dependencies, the dependencies already vendored in the `vendor` directory of the source repo will be used.
19 To avoid updating this field when dependencies change, run `go mod vendor` in your source repo and set `vendorHash = null;`.
20 You can read more about [vendoring in the Go documentation](https://go.dev/ref/mod#vendoring).
22 To obtain the actual hash, set `vendorHash = lib.fakeHash;` and run the build ([more details here](#sec-source-hashes)).
23 - `proxyVendor`: If `true`, the intermediate fetcher downloads dependencies from the
24 [Go module proxy](https://go.dev/ref/mod#module-proxy) (using `go mod download`) instead of vendoring them. The resulting
25 [module cache](https://go.dev/ref/mod#module-cache) is then passed to the final derivation.
27 This is useful if your code depends on C code and `go mod tidy` does not include the needed sources to build or
28 if any dependency has case-insensitive conflicts which will produce platform-dependent `vendorHash` checksums.
31 - `modPostBuild`: Shell commands to run after the build of the goModules executes `go mod vendor`, and before calculating fixed output derivation's `vendorHash`.
32 Note that if you change this attribute, you need to update `vendorHash` attribute.
33 - `modRoot`: The root directory of the Go module that contains the `go.mod` file.
34 Defaults to `./`, which is the root of `src`.
36 ### Example for `buildGoModule` {#ex-buildGoModule}
38 The following is an example expression using `buildGoModule`:
42 pet = buildGoModule rec {
46 src = fetchFromGitHub {
50 hash = "sha256-Gjw1dRrgM8D3G7v6WIM2+50r4HmTXvx0Xxme2fH9TlQ=";
53 vendorHash = "sha256-ciBIR+a1oaYH+H1PcC8cD8ncfJczk1IiJ8iYNM+R6aA=";
56 description = "Simple command-line snippet manager, written in Go";
57 homepage = "https://github.com/knqyf263/pet";
58 license = lib.licenses.mit;
59 maintainers = with lib.maintainers; [ kalbasit ];
65 ### Obtaining and overriding `vendorHash` for `buildGoModule` {#buildGoModule-vendorHash}
67 We can use `nix-prefetch` to obtain the actual hash. The following command gets the value of `vendorHash` for package `pet`:
71 nix-prefetch -E "{ sha256 }: ((import ./. { }).my-package.overrideAttrs { vendorHash = sha256; }).goModules"
74 To obtain the hash without external tools, set `vendorHash = lib.fakeHash;` and run the build. ([more details here](#sec-source-hashes)).
76 `vendorHash` can be overridden with `overrideAttrs`. Override the above example like this:
80 pet_0_4_0 = pet.overrideAttrs (
81 finalAttrs: previousAttrs: {
83 src = fetchFromGitHub {
84 inherit (previousAttrs.src) owner repo;
85 rev = "v${finalAttrs.version}";
86 hash = "sha256-gVTpzmXekQxGMucDKskGi+e+34nJwwsXwvQTjRO6Gdg=";
88 vendorHash = "sha256-dUvp7FEW09V0xMuhewPGw3TuAic/sD7xyXEYviZ2Ivs=";
94 ### Overriding `goModules` {#buildGoModule-goModules-override}
96 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. 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`:
100 pet-overridden = pet.overrideAttrs (
101 finalAttrs: previousAttrs: {
102 passthru = previousAttrs.passthru // {
103 # If the original package has an `overrideModAttrs` attribute set, you'd
104 # want to extend it, and not replace it. Hence we use
105 # `lib.composeExtensions`. If you are sure the `overrideModAttrs` of the
106 # original package trivially does nothing, you can safely replace it
107 # with your own by not using `lib.composeExtensions`.
108 overrideModAttrs = lib.composeExtensions previousAttrs.passthru.overrideModAttrs (
109 finalModAttrs: previousModAttrs: {
110 # goModules-specific overriding goes here
112 # Here you have access to the `vendor` directory.
113 substituteInPlace vendor/github.com/example/repo/file.go \
114 --replace-fail "panic(err)" ""
124 ## `buildGoPackage` (legacy) {#ssec-go-legacy}
126 The function `buildGoPackage` builds legacy Go programs, not supporting Go modules.
129 `buildGoPackage` is deprecated and will be removed for the 25.05 release.
132 ### Migrating from `buildGoPackage` to `buildGoModule` {#buildGoPackage-migration}
134 Go modules, released 6y ago, are now widely adopted in the ecosystem.
135 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.
137 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.
139 - Switch the builder from `buildGoPackage` to `buildGoModule`
140 - Remove `goPackagePath` and other attributes specific to `buildGoPackage`
141 - Set `vendorHash = null;`
142 - Run `go mod init <module name>` in `postPatch`
144 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.
145 Examples for the migration can be found in the [issue tracking migration withing nixpkgs](https://github.com/NixOS/nixpkgs/issues/318069).
147 ### Example for `buildGoPackage` {#example-for-buildgopackage}
149 In the following is an example expression using `buildGoPackage`, the following arguments are of special significance to the function:
151 - `goPackagePath` specifies the package's canonical Go import path.
152 - `goDeps` is where the Go dependencies of a Go program are listed as a list of package source identified by Go import path. It could be imported as a separate `deps.nix` file for readability. The dependency data structure is described below.
156 deis = buildGoPackage rec {
160 goPackagePath = "github.com/deis/deis";
162 src = fetchFromGitHub {
166 hash = "sha256-XCPD4LNWtAd8uz7zyCLRfT8rzxycIUmTACjU03GnaeM=";
174 The `goDeps` attribute can be imported from a separate `nix` file that defines which Go libraries are needed and should be included in `GOPATH` for `buildPhase`:
178 [ # goDeps is a list of Go dependencies.
180 # goPackagePath specifies Go package import path.
181 goPackagePath = "gopkg.in/yaml.v2";
183 # `fetch type` that needs to be used to get package source.
184 # If `git` is used there should be `url`, `rev` and `hash` defined next to it.
186 url = "https://gopkg.in/yaml.v2";
187 rev = "a83829b6f1293c91addabc89d0571c246397bbf4";
188 hash = "sha256-EMrdy0M0tNuOcITaTAmT5/dPSKPXwHDKCXFpkGbVjdQ=";
192 goPackagePath = "github.com/docopt/docopt-go";
195 url = "https://github.com/docopt/docopt-go";
196 rev = "784ddc588536785e7299f7272f39101f7faccc3f";
197 hash = "sha256-Uo89zjE+v3R7zzOq/gbQOHj3SMYt2W1nDHS7RCUin3M=";
203 To extract dependency information from a Go package in automated way use [go2nix (deprecated)](https://github.com/kamilchm/go2nix). It can produce complete derivation and `goDeps` file for Go programs.
205 You may use Go packages installed into the active Nix profiles by adding the following to your ~/.bashrc:
208 for p in $NIX_PROFILES; do
209 GOPATH="$p/share/go:$GOPATH"
213 ## Attributes used by both builders {#ssec-go-common-attributes}
215 Many attributes [controlling the build phase](#variables-controlling-the-build-phase) are respected by both `buildGoModule` and `buildGoPackage`. Note that `buildGoModule` reads the following attributes also when building the `vendor/` goModules fixed output derivation as well:
217 - [`sourceRoot`](#var-stdenv-sourceRoot)
218 - [`prePatch`](#var-stdenv-prePatch)
219 - [`patches`](#var-stdenv-patches)
220 - [`patchFlags`](#var-stdenv-patchFlags)
221 - [`postPatch`](#var-stdenv-postPatch)
222 - [`preBuild`](#var-stdenv-preBuild)
223 - `env`: useful for passing down variables such as `GOWORK`.
225 To control test execution of the build derivation, the following attributes are of interest:
227 - [`checkInputs`](#var-stdenv-checkInputs)
228 - [`preCheck`](#var-stdenv-preCheck)
229 - [`checkFlags`](#var-stdenv-checkFlags)
231 In addition to the above attributes, and the many more variables respected also by `stdenv.mkDerivation`, both `buildGoModule` and `buildGoPackage` respect Go-specific attributes that tweak them to behave slightly differently:
233 ### `ldflags` {#var-go-ldflags}
235 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`.
236 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:
241 "-X main.Version=${version}"
242 "-X main.Commit=${version}"
247 ### `tags` {#var-go-tags}
249 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:
260 Tags can also be set conditionally:
264 tags = [ "production" ] ++ lib.optionals withSqlite [ "sqlite" ];
268 ### `deleteVendor` {#var-go-deleteVendor}
270 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.
272 ### `subPackages` {#var-go-subPackages}
274 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.
276 Many Go projects keep the main package in a `cmd` directory.
277 Following example could be used to only build the example-cli and example-server binaries:
288 ### `excludedPackages` {#var-go-excludedPackages}
290 Specified as a string or list of strings. Causes the builder to skip building child packages that match any of the provided values.
292 ### `CGO_ENABLED` {#var-go-CGO_ENABLED}
294 When set to `0`, the [cgo](https://pkg.go.dev/cmd/cgo) command is disabled. As consequence, the build
295 program can't link against C libraries anymore, and the resulting binary is statically linked.
297 When building with CGO enabled, Go will likely link some packages from the Go standard library against C libraries,
298 even when the target code does not explicitly call into C dependencies. With `CGO_ENABLED = 0;`, Go
299 will always use the Go native implementation of these internal packages. For reference see
300 [net](https://pkg.go.dev/net#hdr-Name_Resolution) and [os/user](https://pkg.go.dev/os/user#pkg-overview) packages.
301 Notice that the decision whether these packages should use native Go implementation or not can also be controlled
302 on a per package level using build tags (`tags`). In case CGO is disabled, these tags have no additional effect.
304 When a Go program depends on C libraries, place those dependencies in `buildInputs`:
315 `CGO_ENABLED` defaults to `1`.
317 ### `enableParallelBuilding` {#var-go-enableParallelBuilding}
319 Whether builds and tests should run in parallel.
323 ### `allowGoReference` {#var-go-allowGoReference}
325 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.
329 ## Controlling the Go environment {#ssec-go-environment}
331 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.
333 ## Skipping tests {#ssec-skip-go-tests}
335 `buildGoModule` runs tests by default. Failing tests can be disabled using the `checkFlags` parameter.
336 This is done with the [`-skip` or `-run`](https://pkg.go.dev/cmd/go#hdr-Testing_flags) flags of the `go test` command.
338 For example, only a selection of tests could be run with:
342 # -run and -skip accept regular expressions
344 "-run=^Test(Simple|Fast)$"
349 If a larger amount of tests should be skipped, the following pattern can be used:
355 # Skip tests that require network access
358 "TestDatabase/with_mysql" # exclude only the subtest
362 [ "-skip=^${builtins.concatStringsSep "$|^" skippedTests}$" ];
366 To disable tests altogether, set `doCheck = false;`.
367 `buildGoPackage` does not execute tests by default.