Dependency Handling

Tutorial 2 of 4

1. Introduction

1.1 Tutorial Goal

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.

1.2 Learning Outcome

By the end of this tutorial, you'll know how to add, update, and remove module dependencies in a Go project.

1.3 Prerequisites

This tutorial assumes that you have a basic understanding of Go programming language and you have Go installed on your machine.

2. Step-by-Step Guide

2.1 Understanding Go Modules

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.

2.2 Adding Dependencies

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

2.3 Updating Dependencies

To update a dependency, you can use the go get command with the -u flag:

go get -u github.com/gorilla/mux

2.4 Removing Dependencies

To remove a dependency, simply remove all the import statements in your code that use the package, and then run go mod tidy.

3. Code Examples

3.1 Adding a Dependency

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

3.2 Removing a Dependency

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.

4. Summary

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.

5. Practice Exercises

  1. Create a new Go module and add gorilla/mux as a dependency.
  2. Update the gorilla/mux dependency to a new version.
  3. Remove the gorilla/mux dependency from your module.

Solutions

  1. 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.

  2. To update gorilla/mux, run go get -u github.com/gorilla/mux.

  3. To remove gorilla/mux, remove all import statements in your code that use it, and then run go mod tidy.

Further Practice

Explore adding and removing multiple dependencies. Try to add dependencies that depend on other packages and observe how Go handles it.