1# Go {#sec-language-go}
2
3## Building Go modules with `buildGoModule` {#ssec-language-go}
4
5The function `buildGoModule` builds Go programs managed with Go modules. It builds [Go Modules](https://go.dev/wiki/Modules) through a two phase build:
6
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.
9
10### Attributes of `buildGoModule` {#buildgomodule-parameters}
11
12The `buildGoModule` function accepts the following parameters in addition to the [attributes accepted by both Go builders](#ssec-go-common-attributes):
13
14- `vendorHash`: is the hash of the output of the intermediate fetcher derivation (the dependencies of the Go modules).
15
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.
18
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).
21
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.
26
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.
29
30 Defaults to `false`.
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`.
35
36### Example for `buildGoModule` {#ex-buildGoModule}
37
38The following is an example expression using `buildGoModule`:
39
40```nix
41{
42 pet = buildGoModule rec {
43 pname = "pet";
44 version = "0.3.4";
45
46 src = fetchFromGitHub {
47 owner = "knqyf263";
48 repo = "pet";
49 rev = "v${version}";
50 hash = "sha256-Gjw1dRrgM8D3G7v6WIM2+50r4HmTXvx0Xxme2fH9TlQ=";
51 };
52
53 vendorHash = "sha256-ciBIR+a1oaYH+H1PcC8cD8ncfJczk1IiJ8iYNM+R6aA=";
54
55 meta = {
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 ];
60 };
61 };
62}
63```
64
65## `buildGoPackage` (legacy) {#ssec-go-legacy}
66
67The function `buildGoPackage` builds legacy Go programs, not supporting Go modules.
68
69### Example for `buildGoPackage` {#example-for-buildgopackage}
70
71In the following is an example expression using `buildGoPackage`, the following arguments are of special significance to the function:
72
73- `goPackagePath` specifies the package's canonical Go import path.
74- `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.
75
76```nix
77{
78 deis = buildGoPackage rec {
79 pname = "deis";
80 version = "1.13.0";
81
82 goPackagePath = "github.com/deis/deis";
83
84 src = fetchFromGitHub {
85 owner = "deis";
86 repo = "deis";
87 rev = "v${version}";
88 hash = "sha256-XCPD4LNWtAd8uz7zyCLRfT8rzxycIUmTACjU03GnaeM=";
89 };
90
91 goDeps = ./deps.nix;
92 };
93}
94```
95
96The `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`:
97
98```nix
99# deps.nix
100[ # goDeps is a list of Go dependencies.
101 {
102 # goPackagePath specifies Go package import path.
103 goPackagePath = "gopkg.in/yaml.v2";
104 fetch = {
105 # `fetch type` that needs to be used to get package source.
106 # If `git` is used there should be `url`, `rev` and `hash` defined next to it.
107 type = "git";
108 url = "https://gopkg.in/yaml.v2";
109 rev = "a83829b6f1293c91addabc89d0571c246397bbf4";
110 hash = "sha256-EMrdy0M0tNuOcITaTAmT5/dPSKPXwHDKCXFpkGbVjdQ=";
111 };
112 }
113 {
114 goPackagePath = "github.com/docopt/docopt-go";
115 fetch = {
116 type = "git";
117 url = "https://github.com/docopt/docopt-go";
118 rev = "784ddc588536785e7299f7272f39101f7faccc3f";
119 hash = "sha256-Uo89zjE+v3R7zzOq/gbQOHj3SMYt2W1nDHS7RCUin3M=";
120 };
121 }
122]
123```
124
125To 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.
126
127You may use Go packages installed into the active Nix profiles by adding the following to your ~/.bashrc:
128
129```bash
130for p in $NIX_PROFILES; do
131 GOPATH="$p/share/go:$GOPATH"
132done
133```
134
135## Attributes used by both builders {#ssec-go-common-attributes}
136
137Many 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:
138
139- [`sourceRoot`](#var-stdenv-sourceRoot)
140- [`prePatch`](#var-stdenv-prePatch)
141- [`patches`](#var-stdenv-patches)
142- [`patchFlags`](#var-stdenv-patchFlags)
143- [`postPatch`](#var-stdenv-postPatch)
144- [`preBuild`](#var-stdenv-preBuild)
145- `env`: useful for passing down variables such as `GOWORK`.
146
147To control test execution of the build derivation, the following attributes are of interest:
148
149- [`checkInputs`](#var-stdenv-checkInputs)
150- [`preCheck`](#var-stdenv-preCheck)
151- [`checkFlags`](#var-stdenv-checkFlags)
152
153In 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:
154
155### `ldflags` {#var-go-ldflags}
156
157A 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`.
158The 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:
159
160```nix
161{
162 ldflags = [
163 "-X main.Version=${version}"
164 "-X main.Commit=${version}"
165 ];
166}
167```
168
169### `tags` {#var-go-tags}
170
171A 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:
172
173```nix
174{
175 tags = [
176 "production"
177 "sqlite"
178 ];
179}
180```
181
182Tags can also be set conditionally:
183
184```nix
185{
186 tags = [ "production" ] ++ lib.optionals withSqlite [ "sqlite" ];
187}
188```
189
190### `deleteVendor` {#var-go-deleteVendor}
191
192If 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.
193
194### `subPackages` {#var-go-subPackages}
195
196Specified 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.
197
198Many Go projects keep the main package in a `cmd` directory.
199Following example could be used to only build the example-cli and example-server binaries:
200
201```nix
202{
203 subPackages = [
204 "cmd/example-cli"
205 "cmd/example-server"
206 ];
207}
208```
209
210### `excludedPackages` {#var-go-excludedPackages}
211
212Specified as a string or list of strings. Causes the builder to skip building child packages that match any of the provided values.
213
214### `CGO_ENABLED` {#var-go-CGO_ENABLED}
215
216When set to `0`, the [cgo](https://pkg.go.dev/cmd/cgo) command is disabled. As consequence, the build
217program can't link against C libraries anymore, and the resulting binary is statically linked.
218
219When building with CGO enabled, Go will likely link some packages from the Go standard library against C libraries,
220even when the target code does not explicitly call into C dependencies. With `CGO_ENABLED = 0;`, Go
221will always use the Go native implementation of these internal packages. For reference see
222[net](https://pkg.go.dev/net#hdr-Name_Resolution) and [os/user](https://pkg.go.dev/os/user#pkg-overview) packages.
223Notice that the decision whether these packages should use native Go implementation or not can also be controlled
224on a per package level using build tags (`tags`). In case CGO is disabled, these tags have no additional effect.
225
226When a Go program depends on C libraries, place those dependencies in `buildInputs`:
227
228```nix
229{
230 buildInputs = [
231 libvirt
232 libxml2
233 ];
234}
235```
236
237`CGO_ENABLED` defaults to `1`.
238
239### `enableParallelBuilding` {#var-go-enableParallelBuilding}
240
241Whether builds and tests should run in parallel.
242
243Defaults to `true`.
244
245### `allowGoReference` {#var-go-allowGoReference}
246
247Whether 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.
248
249Defaults to `false`
250
251## Controlling the Go environment {#ssec-go-environment}
252
253The 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.
254
255## Skipping tests {#ssec-skip-go-tests}
256
257`buildGoModule` runs tests by default. Failing tests can be disabled using the `checkFlags` parameter.
258This is done with the [`-skip` or `-run`](https://pkg.go.dev/cmd/go#hdr-Testing_flags) flags of the `go test` command.
259
260For example, only a selection of tests could be run with:
261
262```nix
263{
264 # -run and -skip accept regular expressions
265 checkFlags = [
266 "-run=^Test(Simple|Fast)$"
267 ];
268}
269```
270
271If a larger amount of tests should be skipped, the following pattern can be used:
272
273```nix
274{
275 checkFlags =
276 let
277 # Skip tests that require network access
278 skippedTests = [
279 "TestNetwork"
280 "TestDatabase/with_mysql" # exclude only the subtest
281 "TestIntegration"
282 ];
283 in
284 [ "-skip=^${builtins.concatStringsSep "$|^" skippedTests}$" ];
285}
286```
287
288To disable tests altogether, set `doCheck = false;`.
289`buildGoPackage` does not execute tests by default.