www/content/resources/cookbooks/build-go-modules.md
With the default configuration, you can build a Go module without issues.
But if you want to access module information at runtime (for example, through
debug.BuildInfo or go version -m $binary), you need to set up GoReleaser to
"proxy" that module before building it.
To do that, add this to your configuration:
gomod:
proxy: true
In practice, what this does is:
dist/proxy/{{ build.id }};go.mod for a module named after the build id;go.sum to that directory.go get module@versionIn which:
id property in your build definition;go list -m;main;So, let's say:
github.com/goreleaser/nfpm/v2;nfpmmain: ./cmd/nfpm/;v2.5.0.GoReleaser will create a go.mod like:
module nfpm
Then it'll copy the go.sum into this directory, and run:
go get github.com/goreleaser/nfpm/[email protected]
And, to build, it will use something like:
go build -o nfpm github.com/goreleaser/nfpm/v2/cmd/nfpm
This will resolve the source code from the defined module proxy using proxy.golang.org.
Your project's go.sum will be used to verify any modules that are downloaded, with sum.golang.org "filling in" any gaps.
You can also get the module version at runtime using debug#ReadBuildInfo.
It is useful to display the version of your program to the user, for example.
package main
import (
"fmt"
"runtime/debug"
)
func main() {
if info, ok := debug.ReadBuildInfo(); ok && info.Main.Sum != "" {
fmt.Println(info)
}
}
You can also use go version -m my_program to display the go module information.
You can find more information about it on the issue that originated it and its subsequent pull request.
Make sure to also read the relevant documentation for more options.
Source code of a working example can be found at goreleaser/example-mod-proxy.