...

/

How to Use Go Modules in a REST App

How to Use Go Modules in a REST App

Learn how modules work by using them to manage dependencies in the coffee shop app.

Earlier, in the “Environment Setup and Scaffolding” lesson, we created the coffee.go file for our coffee shop.

Press + to interact
package coffee
var coffees = map[string]float32{"Latte":2.5, "Cappuccino": 2.75, "Flat White": 2.25}
func GetCoffees() map[string]float32 {
return coffees
}

At that time, executing the go run or go build commands via the “Run” button threw the following error:

go: go.mod file not found in current directory or any parent directory; see ‘go help modules

To counter this now, we need to initialize a module for our project.

Reorganizing the code

But before that, let's create another folder in the project root called coffee and move the file coffee.go to it.

This is done to move the files in the package to its separate folder so that the code remains organized and easy to navigate.

The project structure should now look like this:

coffeeshop
|__ coffee
|__ coffee.go

Initializing a module

To initialize the coffeeshop module for our web app, we'll use the following command:

Press + to interact
go mod init coffeeshop

Executing it returns:

Press + to interact
go: creating new go.mod: module coffeeshop
go: to add module requirements and sums:
go mod tidy

For now, let's ignore line 2. We'll get to it soon enough. In line 1, we create the module ...