· how to tips

Go modules are neat

I was chatting with a friend the other day and he mentioned that he really likes Go modules. For the unfamiliar (like me right before writing this), Go modules are an experimental feature in go 1.11. The intent of them is to give go a somewhat proper package management scheme like most other languages have. Though I think the actual package management scheme is slightly different than most other modern package managers like npm or cargo.

Anyway, a quick start example

You’ll probably find better information on the go modules wiki that I linked above. But it never hurts to retread good examples, so let’s do it!

Let’s say you want to write a quick program that just prints out 2 “random” IDs that also contain time stamps. You may want to use an external library for this. Maybe something like sanic ;)

So you create your project directory. It can be anywhere. It doesn’t even have to be in your go path!

mkdir -p ~/projects/idprinter && cd ~/projects/idprinter

(fun fact, the -p on mkdir just creates all the intermediate directories if they don’t exist)

Then we have to opt in to using modules with this:

go mod init github.com/yourname/idprinter

Now we write our id printer with this code:

package main

import (
	"fmt"

	"github.com/ifo/sanic"
)

func main() {
	w := sanic.NewWorker7()

	fmt.Println(w.IDString(w.NextID()))
	fmt.Println(w.IDString(w.NextID()))
}

Then build it and run it to get our two “random” ids:

$ go build
go: finding github.com/ifo/sanic latest
$ ./idprinter
AEROahU
AUROahU

Yes! And?

So now that your module is built, you’ll notice two new files: go.mod and go.sum. (If you’re keeping track of this new project with version control, you’ll want to checkin the go.mod and go.sum files with everything else like they suggest)

The go.mod should contain something like this

module github.com/yourname/idprinter

require github.com/ifo/sanic v0.0.0-20180325220412-3c19d12f362c

And is ensuring that you’re getting a specific version of the module you wanted. You can update it later if you’d like.

go.sum might be like this:

github.com/ifo/sanic v0.0.0-20180325220412-3c19d12f362c h1:+8D7QnjHQ/wemgTsugVUm0ztedyrYNXrxMs9jNk3oV4=
github.com/ifo/sanic v0.0.0-20180325220412-3c19d12f362c/go.mod h1:Mbw5N4YSs9UPV98tto5uuthoThp1Z+XzdVF7qhfJxCE=

And is a cryptographic check of the other packages you use in your package.

Interestingly enough, it’ll still include packages you no longer use. But they have an explanation for that. The short version is that if you ever want to use that package again, you’ll already have a known working checksum for it, which can help with security.

Anyway

Have fun playing with go modules everybody!

← I love code formatters Go and protobuf quick start →