Learn Go Β· 9/18

Project Structure and Modules

7 min read

Project Structure and Modules in Go πŸš—

Welcome, Gophers! Today, we're diving into the essential art of structuring your Go projects and managing your code like a pro. A well-organized project is like a well-organized toolbox; you know exactly where everything is, making your work faster, more efficient, and a lot less frustrating. Let's get our hands dirty!


1. Go Modules: Managing Dependencies (go.mod) πŸ“¦

The Problem: Imagine you're building a LEGO masterpiece. You need specific bricks (code libraries) from different sets (other people's projects). How do you keep track of which bricks you need, and what happens if those bricks change? This is the challenge of dependency management. In the early days of Go, managing these "bricks" could get messy, leading to the infamous "dependency hell."

The Solution: Go Modules

Go Modules are the official and modern way to manage dependencies in your Go projects. A module is a collection of related Go packages that are versioned together as a single unit. This system is centered around a special file: go.mod.

The go.mod file is the heart of your project's dependency management. It does three crucial things:

  1. Declares the module's path: This is a unique name for your project.
  2. Specifies the Go version: It tells Go which version of the language your code is written for.
  3. Lists the dependencies: It keeps a record of all the external packages your project needs and their specific versions.

Getting Started with go mod

Let's create a new Go module.

  1. Create a new directory for your project:

    bash
    mkdir my-awesome-project
    cd my-awesome-project
  2. Initialize the module using the go mod init command. You'll need to give your module a path. A common practice is to use a path related to your Git repository, like github.com/your-username/my-awesome-project.

    bash
    go mod init github.com/your-username/my-awesome-project

    This command creates a go.mod file in your directory. It will look something like this:

    go
    module github.com/your-username/my-awesome-project
    
    go 1.22.0

    Fun Fact: Before Go modules, developers often used tools like dep or glide, or relied on the GOPATH environment variable to manage dependencies, which could be quite a headache!

Adding a Dependency

Let's say we want to use a popular package for generating UUIDs. We can simply import it in our code.

Create a main.go file:

go
package main

import (
	"fmt"
	"github.com/google/uuid"
)

func main() {
	id := uuid.New()
	fmt.Println("Generated UUID:", id)
}

Now, run the go mod tidy command in your terminal.

bash
go mod tidy

This command is your best friend for module management. It does two things:

  • It finds all the packages you've imported in your code and adds them to your go.mod file.
  • It removes any dependencies that you are no longer using.

After running go mod tidy, your go.mod file will be updated:

go
module github.com/your-username/my-awesome-project

go 1.22.0

require github.com/google/uuid v1.6.0

You'll also notice a new file called go.sum. This file contains the cryptographic hashes of the direct and indirect dependencies to ensure that the packages you download haven't been tampered with. You should commit both go.mod and go.sum to your version control system.


2. Organizing Code into Packages πŸ“

The Problem: As your project grows, putting all your code in a single main.go file becomes chaotic and unmanageable. Imagine trying to find a specific recipe in a cookbook with no chapters or index. That's what a single-file project feels like.

The Solution: Packages

Packages are Go's way of organizing code. A package is simply a directory containing one or more Go files. All files in the same directory must belong to the same package.

Creating and Using a Package

Let's create a greeter package in our project.

  1. Inside your my-awesome-project directory, create a new directory called greeter.

    bash
    mkdir greeter
  2. Inside the greeter directory, create a file named greeter.go.

    go
    // greeter/greeter.go
    package greeter
    
    func SayHello(name string) string {
        return "Hello, " + name + "!"
    }

    Notice the package greeter declaration at the top. This tells Go that this file is part of the greeter package.

Now, let's use this package in our main.go.

go
// main.go
package main

import (
	"fmt"
	"github.com/your-username/my-awesome-project/greeter" // Import our local package
)

func main() {
	message := greeter.SayHello("Gopher")
	fmt.Println(message)
}

To import our local package, we use the module path we defined in go.mod followed by the path to the package directory.

Your project structure should now look like this:

maxima
my-awesome-project/
β”œβ”€β”€ go.mod
β”œβ”€β”€ go.sum
β”œβ”€β”€ main.go
└── greeter/
    └── greeter.go

This is a clean and scalable way to organize your code! πŸš€


3. Exported vs. Unexported Identifiers (Visibility) πŸ‘οΈ

The Problem: When you have multiple packages, you might not want all the functions, variables, and types from one package to be accessible by another. Some things should be kept private to the package they are defined in. Think of it like a restaurant's kitchen; customers can see the menu (exported items), but they can't see the secret sauce recipe (unexported items).

The Solution: Capitalization

Go has a very simple rule for determining visibility:

  • Exported: If an identifier (like a function, variable, or type name) starts with a capital letter, it is "exported," meaning it can be accessed from other packages.
  • Unexported: If an identifier starts with a lowercase letter, it is "unexported," meaning it can only be accessed from within the same package.

Example

Let's modify our greeter package to include a private helper function.

go
// greeter/greeter.go
package greeter

// SayHello is an exported function because it starts with a capital letter.
func SayHello(name string) string {
	return createMessage(name)
}

// createMessage is an unexported function because it starts with a lowercase letter.
// It can only be called by other functions within the 'greeter' package.
func createMessage(name string) string {
	return "Hello, " + name + "!"
}

In our main.go, we can call greeter.SayHello(), but if we try to call greeter.createMessage(), we will get a compilation error.

go
// main.go
package main

import (
	"fmt"
	"github.com/your-username/my-awesome-project/greeter"
)

func main() {
	message := greeter.SayHello("Gopher") // This works!
	fmt.Println(message)

	// privateMessage := greeter.createMessage("Gopher") // This will cause a compile error!
}

This simple convention is a powerful feature in Go that encourages well-structured and maintainable code.


4. Third-Party Packages: go get and external code 🌐

The Problem: You don't want to reinvent the wheel for every single task. There's a vast ecosystem of open-source Go packages that can do everything from handling web requests to advanced data processing. How do you easily bring these packages into your project?

The Solution: go get

The go get command is used to download and install packages from remote sources, like GitHub.

How to Use go get

Let's say we want to use a popular package for routing HTTP requests called gorilla/mux.

You can explicitly add it to your project by running:

bash
go get github.com/gorilla/mux

This command will download the package and add it to your go.mod and go.sum files.

Alternatively, you can do what we did earlier: import the package in your code and then run go mod tidy.

Let's see an example with gorilla/mux.

go
// main.go
package main

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
)

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello, world!")
	})

	fmt.Println("Starting server on :8080")
	http.ListenAndServe(":8080", r)
}

After adding the import, run go mod tidy in your terminal. Your go.mod file will be updated with the new dependency.

bash
go mod tidy

Now you can run your main.go file, and you'll have a running web server!

Industry Practice: It's common to see developers import the package first and then run go mod tidy as it integrates seamlessly into the coding workflow.


References for Extra Reading πŸ“š

Challenge

You are tasked with structuring a small Go application. Your goal is to demonstrate your understanding of Go modules, package organization, and visibility rules.

Simulate a project with the module path github.com/my-user/my-app. The project should have the following structure:

  • go.mod
  • main.go
  • calculator/calculator.go
  • logger/logger.go

Your task is to write the contents of all four files within the single editor window provided, using comments to delineate each file.

Requirements:

  1. // file: go.mod:

    • Define the module path as github.com/my-user/my-app.
    • Specify Go version 1.21.
    • Include a dependency on the github.com/sirupsen/logrus package, version v1.9.0.
  2. // file: logger/logger.go:

    • Declare this file as part of the logger package.
    • Create an exported function Log(message string) that uses the fmt package to print the message to the console, prefixed with "[INFO] ".
  3. // file: calculator/calculator.go:

    • Declare this file as part of the calculator package.
    • Import your local logger package using its full module path: github.com/my-user/my-app/logger.
    • Create an unexported function record(operation string) which calls logger.Log with a formatted string like "Performed operation: [operation]".
    • Create an exported function Add(a, b int) int. This function must call the record function with the string "addition" before returning the sum of a and b.
  4. // file: main.go:

    • Declare this file as part of the main package.
    • Import your local calculator package (github.com/my-user/my-app/calculator).
    • Import the third-party logrus package.
    • In the main function:
      • Call the calculator.Add function with two integers and store the result.
      • Use logrus.Infof to print the result in the format "The result from the calculator is: [result]".

Expected result

The final code should correctly implement a multi-package Go application within a single block, delineated by file comments.

  • go.mod: The file should contain the module declaration, the go version, and the required logrus dependency with the correct version.
  • logger/logger.go: It must define the logger package and an exported Log function that properly imports and uses the fmt package.
  • calculator/calculator.go: It must define the calculator package, correctly import the local logger package using the full module path, define an unexported record function, and an exported Add function that calls the unexported record function.
  • main.go: It must define the main package, correctly import both the local calculator package and the third-party logrus package. The main function should correctly call functions from both imported packages as specified.

The capitalization for exported (e.g., Add, Log) and unexported (e.g., record) identifiers must be correct across all packages.

go

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.