Go Mod

We’ve reviewed two older methods managing Go packages before, now let’s review Go Mod method.

Use Go Mod

Let’s try to pull zap package.

The command to install the package is go get -u go.uber.org/zap.

Now the go.mod file is updated as:

1
2
3
4
5
6
7
8
module gomodtest

go 1.16

require (
go.uber.org/multierr v1.7.0 // indirect
go.uber.org/zap v1.16.0 // indirect
)

Now let’s use this package. Create a zaptest.og file:

1
2
3
4
5
6
7
8
package main

import "go.uber.org/zap"

func main() {
logger, _ := zap.NewProduction()
logger.Warn("warning test")
}

Run this file, the output will be:

1
{"level":"warn","ts":1620616442.774267,"caller":"gomodtest/zaptest.go:7","msg":"warning test"}

Now all the packages are stored here:

Use different versions

If we want to use a different version, we can do the following.

Let’s first pull the different version:

1
go get -u go.uber.go/zap@v1.11

go.mod file will change to v1.11.0 with additional configurations.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
module gomodtest

go 1.16

require (
github.com/pkg/errors v0.8.1 // indirect
go.uber.org/multierr v1.7.0 // indirect
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee // indirect
go.uber.org/zap v1.11.0 // indirect
golang.org/x/lint v0.0.0-20190930215403-16217165b5de // indirect
golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5 // indirect
gopkg.in/yaml.v2 v2.2.2 // indirect
honnef.co/go/tools v0.0.1-2019.2.3 // indirect
)

To add packages, we could either add it in the go.mod file or import it directly in the code file.

1
go get github.com/gin-gonic/gin

If we have removed go.mod file, to re-configure the project:

1
2
go mod init modtest2
go build ./...

To Summarize

  • go mod use go command to manage all packages and users don’t need to care much about the directory structure
  • To initialize: go mode init proj_name
  • To add dependencies: go get
  • To update dependencies: go get[@v...] go mod tidy
  • To build the project: go build ./...