What are Go Modules?

Go modules is the long-awaited dependency management solution for Golang. In this short blog post, we will explore how we can use it in your next project.

In order to use go modules, you should be using go 1.11.x Modules are an experimental opt-in feature in go 1.11 and are expected to be GA in 1.13.

Using it is very easy. As simple as creating your project outside $GOPATH.Using it inside $GOPATH requires you to do the following,

export GO111MODULE=on

So we can start off by creating our project outside $GOPATH. Let us create a directory,

mkdir hello

Now let's write some code by creating a file hello.go. Our toy module here will have a single function

package hello

import "fmt"

func SayHello() {
    fmt.Println("Hello")
}

Now we can initialize this as a go module by doing the following

14:09:23 ▶ go mod init github.com/scriptonist/hello
go: creating new go.mod: module github.com/scriptonist/hello

That's it! our module is ready. Now we'll commit and push this to github for other people to use.

hello master L ✔ ✘-1
12:27:33 ▶ git add -A && git commit -m "First Commit" && git push origin master

Go modules works very closely with semantic versioning and there are some additional quirks, which we'll see later. For now, we'll push a 1.0.0 tag to GitHub.

hello master L ✔ ✔
11:05:03git tag -a "v1.0.0" -m "My first version"
hello master L ✔ ✔
11:06:48git push origin --tags

Now we'll create a new project which has the module as a dependency.

I named the project as moduleuser and wrote the following code.

moduleuser master L …312:22:04 ▶ cat main.go
package main

import (
    "github.com/scriptonist/hello"
)

func main() {
    hello.SayHello()
}

Now we initialize this as go module and run the program.

moduleuser master L …1 ✘-1
12:09:58go mod init moduleuser
go: creating new go.mod: module moduleuser
moduleuser master L …212:20:33 ▶ go run main.go
go: finding github.com/scriptonist/hello v1.0.0
Hello

As you can see go pulled down our module and used it in our project. This a very basic quick start, to using go modules in your project. There are a lot more quirks and features to it. Which we'll visit in another post. Let me know if you have any questions about this topic in the comment section below 🙂

You can find more information about go modules in the following links.

Aravind

Foodie🍗 | Motorhead 🏎️ | GSW 🏀 | Software Engineer @hashnode 🖥️

Write your comment…

Be the first one to comment