Manually fetch dependencies from go.mod?
It was an issue #26610, which is fixed now.
So now you can just use:
go mod download
For this to work you need just the go.mod
/ go.sum
files.
For example, here's how to have a cached multistage Docker build: (source)
FROM golang:1.17-alpine as builder
RUN apk --no-cache add ca-certificates git
WORKDIR /build
# Fetch dependencies
COPY go.mod go.sum ./
RUN go mod download
# Build
COPY . ./
RUN CGO_ENABLED=0 go build
# Create final image
FROM alpine
WORKDIR /
COPY --from=builder /build/myapp .
EXPOSE 8080
CMD ["./myapp"]
Also see the article Containerize Your Go Developer Environment – Part 2, which describes how to leverage the Go compiler cache to speed up builds even further.
I wanted to re-download all the dependencies using go mod
, this is what I did:
- Go to your
GOROOT
sudo rm -rf pkg/mod/
- Go to the directory where the
go.mod
file exists go mod download
You may use the go mod vendor
command which will create a vendor
folder in the main module's root folder, and copy all dependencies into it. After this you may pass the -mod=vendor
param to the go tool, and then dependencies from the vendor
folder will be used to build / compile / test your app.
So what you may do to speed up your builds:
- Run the
go mod vendor
command to have an actual version of your dependencies. - Save / cache this
vendor
folder. - During builds, restore this
vendor
folder, and build / install your app by passing the-mod=vendor
argument to the go tool, so no dependencies will be downloaded, but the content of thevendor
folder will be used.
Quoting from go help mod
:
Modules and vendoring
When using modules, the go command completely ignores vendor directories.
By default, the go command satisfies dependencies by downloading modules from their sources and using those downloaded copies (after verification, as described in the previous section). To allow interoperation with older versions of Go, or to ensure that all files used for a build are stored together in a single file tree, 'go mod vendor' creates a directory named vendor in the root directory of the main module and stores there all the packages from dependency modules that are needed to support builds and tests of packages in the main module.
To build using the main module's top-level vendor directory to satisfy dependencies (disabling use of the usual network sources and local caches), use 'go build -mod=vendor'. Note that only the main module's top-level vendor directory is used; vendor directories in other locations are still ignored.