This tutorial aims to guide you through dependency management in a Go project using the Go module system. Dependency management is crucial as it allows us to control which version of an external package our project relies on.
By the end of this tutorial, you'll know how to add, update, and remove module dependencies in a Go project.
This tutorial assumes that you have a basic understanding of Go programming language and you have Go installed on your machine.
Go introduced modules in version 1.11 to manage dependencies. A module is a collection of Go packages stored in a file tree with a go.mod
file at its root. The go.mod
file defines the module’s module path and its dependency requirements.
To add a dependency, use the go get
command followed by the package URL. For example, to add the gorilla/mux
package, you would type:
go get -u github.com/gorilla/mux
To update a dependency, you can use the go get
command with the -u
flag:
go get -u github.com/gorilla/mux
To remove a dependency, simply remove all the import statements in your code that use the package, and then run go mod tidy
.
Let's add the gorilla/mux
package to our project:
go get -u github.com/gorilla/mux
Check your go.mod
file, you will see the added package:
module mymodule
go 1.16
require github.com/gorilla/mux v1.8.0 // indirect
If we want to remove the gorilla/mux
package, we first remove all the import statements that use it. Then, run:
go mod tidy
Check your go.mod
file, and you'll see that gorilla/mux
is no longer there.
In this tutorial, we learned about Go modules and how to add, update, and remove dependencies. We also learned how to check our go.mod
file to see our current dependencies.
gorilla/mux
as a dependency.gorilla/mux
dependency to a new version.gorilla/mux
dependency from your module.To create a new module named mymodule
, run go mod init mymodule
. Then, add gorilla/mux
by running go get -u github.com/gorilla/mux
.
To update gorilla/mux
, run go get -u github.com/gorilla/mux
.
To remove gorilla/mux
, remove all import statements in your code that use it, and then run go mod tidy
.
Explore adding and removing multiple dependencies. Try to add dependencies that depend on other packages and observe how Go handles it.