Modules are the new way of doing dependency management in Golang.

A module is a collection of packages that are distributed together (e.g. a single binary). A module contains a go.mod file at its root.

With modules, it is not necessary to have our code in $GOPATH/src anymore, so we can create a project anywhere.

Let’s start a new project:

1
mkdir ~/project

And make it a module:

1
2
cd ~/project
go mod init mymodule/hello

This creates a go.mod file. Mine looks like this:

1
2
3
module mymodule/hello

go 1.15

Let’s create a main file in our module:

1
touch main.go

And add this content:

1
2
3
4
5
6
7
package main

import "fmt"

func main() {
    fmt.Println("hello world")
}

We can run our application:

1
go run main.go

Since the point of modules is managing dependencies, let’s add a dependency to our application:

1
2
3
4
5
6
7
8
package main

import "fmt"
import "rsc.io/quote"

func main() {
  fmt.Println(quote.Hello());
}

Next time we try to run it, all the dependencies will be downloaded and the dependencies’ versions will be added to go.mod:

1
2
3
4
5
module mymodule/hello

go 1.15

require rsc.io/quote v1.5.2 // indirect

There is also a file named go.sum created. This file contains information about all the dependencies (including dependencies of dependencies):

1
2
3
4
5
6
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c h1:qgOY6WgZOaTkIIMiVjBQcw93ERBE4m30iBm00nkL0i8=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
rsc.io/quote v1.5.2 h1:w5fcysjrx7yqtD/aO+QwRjYZOKnaM9Uh2b40tElTs3Y=
rsc.io/quote v1.5.2/go.mod h1:LzX7hefJvL54yjefDEDHNONDjII0t9xZLPXsUe+TKr0=
rsc.io/sampler v1.3.0 h1:7uVkIFmeBqHfdjD+gZwtXXI+RODJ2Wc4O7MPEh/QiW4=
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=

Both files should be checked into version control to provide reproducible builds.

We can also see all the dependencies in our module using go list:

1
go list -m all

To see the available versions of a specific module:

1
go list -m -versions rsc.io/sampler

We can upgrade a package to a specific version:

1
go get rsc.io/sampler@v1.3.1

To upgrade to the latest version, just omit the version

1
go get rsc.io/sampler

Conclusion

In this article we learned how to create a simple module and manage its dependencies. The system seems simple to use, and not having to put all our code in $GOPATH/src is a nice new feature.

[ golang  programming  ]
Google sign-in with Golang
Dealing with Firestore 10 limit when using IN operator
Using testify for Golang tests
Unit testing Golang code
Google auth with Beego