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 | module gomodtest |
Now let’s use this package. Create a zaptest.og
file:
1 | package main |
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 | module gomodtest |
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 | go mod init modtest2 |
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 ./...