The Go toolchain, modules and packages
Install Go, read a go.mod, understand what a package is, how imports resolve inside a module, and how the standard commands (build, run, test, vet, fmt) fit together.
Learning outcomes
- Run go version, go env, go build, go run, go test, go vet and gofmt, and say what each does.
- Create a module with go mod init and read every line of go.mod and go.sum.
- Explain what a package is and why one directory holds exactly one package.
- Lay out a service with cmd/ for binaries and internal/ for private packages, and say why internal/ exists.
- Import your own packages by module path and your dependencies from the module cache.
Why the Go toolchain matters
Before writing a rate limiter or an HTTP handler, you need to understand how Go turns source code into a running program. Go is a compiled programming language. This means your .go files are not executed directly by the computer. They are processed by a collection of tools that check, compile, test, and package your code.
This collection of tools is called the Go toolchain.
The toolchain is deliberately small. Most of your daily development work happens through one command: go. Instead of installing separate tools for compiling, managing dependencies, running tests, and formatting code, Go provides these capabilities through a unified command-line interface.
By the end of this lesson, you will understand how a Go project is organized, how Go identifies packages, how dependencies are managed, and how to use the commands that will become part of your daily development workflow.
Installing Go
Go is distributed as an official installer for each supported operating system.
Visit go.dev/dl and download the installer for your operating system. Follow the installation instructions for macOS, Linux, or Windows.
Once installation is complete, open a terminal and run:
go versionYou should see output similar to:
go version go1.25.0 darwin/arm64The exact version and platform will depend on your installation.
This output contains three important pieces of information:
go1.25.0is the installed Go version.darwinidentifies the operating system.arm64identifies the processor architecture.
The Go version matters because different versions introduce language features, standard library changes, and improvements to the compiler.
To inspect your Go installation and configuration, run:
go envThis prints environment variables used by the Go toolchain. Some particularly useful ones are:
| Variable | Meaning |
|---|---|
GOROOT | Location of the Go installation and standard library |
GOPATH | Workspace location used by Go tooling and the module cache |
GOMOD | Path to the active go.mod file |
GOVERSION | Version of the Go toolchain |
GOCACHE | Location of the build cache |
GOOS | Target operating system |
GOARCH | Target processor architecture |
You can inspect an individual variable without printing everything:
go env GOMOD
go env GOPATH
go env GOCACHEA useful distinction: GOROOT describes where Go itself is installed, while GOPATH describes a workspace used by Go tooling.
GOPATH versus modules
Historically, Go projects were expected to live inside a specific directory structure under GOPATH/src. This made project organization and dependency management relatively restrictive. Modern Go uses Go modules, which allow a project to live anywhere on your filesystem. A module declares its identity and dependencies in a go.mod file. Go can then resolve imports using module paths instead of relying on the project's physical location. You will still encounter GOPATH because Go uses it for locations such as the module download cache, but you do not need to put your project inside it.
Creating your first Go module
Our project will be called zomato-prep. It is a backend engineering course project in which you will progressively build a food-delivery backend.
We will keep the Go backend inside a dedicated backend/ directory.
Start by creating the project directory:
mkdir -p zomato-prep/backend
cd zomato-prep/backendInitialize a Go module:
go mod init github.com/yashdagar/zomato-prep/backendYou should see:
go: creating new go.mod: module github.com/yashdagar/zomato-prep/backendThis command creates a go.mod file.
Understanding the module path
A module is a collection of related Go packages that share a common module path and dependency definition.
The module path identifies your project. In our case, it is:
github.com/yashdagar/zomato-prep/backendThis path will become the prefix for imports of packages belonging to this project.
For example, if you create a package in:
backend/internal/ratelimit/
Its import path will be:
github.com/yashdagar/zomato-prep/backend/internal/ratelimitNotice that the import path is not a filesystem path beginning with ./. It is constructed by combining the module path with the directory relative to the module root.
This distinction is fundamental to understanding how Go projects are organized.
Reading go.mod
Immediately after initialization, your go.mod will look similar to this:
module github.com/yashdagar/zomato-prep/backend
go 1.25.0Let's understand every line.
The module declaration:
module github.com/yashdagar/zomato-prep/backendThis declares the module's identity. Every package inside the module can be imported using this path as its prefix.
The Go version:
go 1.25.0This declares the Go language version and module compatibility requirements for the project. It also influences certain module and toolchain behaviors.
The Go version declared here is not necessarily the exact compiler version installed on your machine. The installed toolchain can be newer, subject to Go's compatibility and toolchain-selection rules.
The toolchain directive:
A module can also contain a line like:
toolchain go1.25.1This is an optional toolchain directive. It suggests a particular Go toolchain version when Go needs to select a toolchain for the module.
It does not replace the go directive. The go directive declares the module's Go version requirements, while toolchain suggests a specific toolchain version for working with the module.
You may see this line added or updated when using newer Go toolchain versions.
Understanding go.sum
You might notice that go mod init does not immediately create a go.sum file.
That is normal.
The go.sum file is generated when dependencies are downloaded and their checksums are recorded.
For example, after adding a dependency, it might contain entries resembling:
github.com/go-chi/chi/v5 v5.2.1 h1:exampleModuleChecksum
github.com/go-chi/chi/v5 v5.2.1/go.mod h1:exampleGoModChecksumThese entries are illustrative, not actual checksums.
Each entry records a cryptographic checksum associated with a particular dependency version or its module metadata.
Why does this matter?
Suppose two developers download the same dependency. They should receive the same module contents. Go verifies downloaded dependencies against recorded checksums to detect unexpected changes or corrupted downloads.
The go.sum file is therefore important for reproducible and trustworthy dependency resolution.
Commit both go.mod and go.sum to version control. Do not treat go.sum as a disposable local cache file. It helps ensure that other developers and CI systems verify the same dependency contents.
Understanding Go packages
A package is the basic unit of code organization in Go.
A package groups related functions, types, variables, and constants together. Other packages can import it and use the identifiers it exposes.
Let's create a tiny package for our upcoming rate limiter.
Create this directory:
mkdir -p internal/ratelimitInside it, create limiter.go:
package ratelimit
type Limiter struct {
limit int
}
func New(limit int) *Limiter {
return &Limiter{
limit: limit,
}
}
func (l *Limiter) Limit() int {
return l.limit
}The first line is:
package ratelimitThis declares the package name.
Every .go source file in the same directory that belongs to this package must declare the same package name, except for specially named external test packages.
This is an important organizational rule: one directory represents one Go package.
You cannot put unrelated package declarations into different files in the same directory and expect Go to treat them as separate packages.
If you need two packages, create two directories.
Package name versus directory name
Exported and unexported identifiers
Look at the Limiter type and the limit field:
type Limiter struct {
limit int
}Why does Limiter start with a capital letter while limit starts with a lowercase letter?
Go uses capitalization to control visibility between packages.
An identifier beginning with an uppercase letter is exported. Other packages can access it.
An identifier beginning with a lowercase letter is unexported. It can only be accessed from within its declaring package.
For example:
type Limiter struct {
limit int
}
func New(limit int) *Limiter {
return &Limiter{
limit: limit,
}
}Another package can create a Limiter using ratelimit.New(), but it cannot directly modify or read the limit field.
This is useful because packages can expose a small public API while keeping implementation details private.
It also gives you control over how other parts of your application interact with your code.
For example, the rate limiter might eventually maintain internal counters, timestamps, and synchronization primitives. Other packages should not need to manipulate those implementation details directly.
Organizing a Go backend
A backend service should have a predictable directory structure.
As our project grows, we will organize it like this:
zomato-prep/backend/go.modgo.sumMakefiledocker-compose.yml.golangci.ymlcmd/api/main.go
internal/ratelimit/limiter.go
httpx/
There are two important directories here.
cmd/: Application entry points
The cmd/ directory contains executable applications.
Our API server will live in:
cmd/api/main.goThe api directory represents the API server binary.
A Go executable starts from a package named main, which must define a function named main.
Create the following file:
package main
import (
"fmt"
"github.com/yashdagar/zomato-prep/backend/internal/ratelimit"
)
func main() {
limiter := ratelimit.New(100)
fmt.Println("Configured rate limit:", limiter.Limit())
}The package main declaration tells Go that this package builds an executable program rather than an ordinary importable library.
The func main() function is the program's entry point. When you execute the compiled binary, Go starts running this function.
Notice how we import our own package:
"github.com/yashdagar/zomato-prep/backend/internal/ratelimit"This is the module path followed by the directory relative to the module root.
We do not need to publish our project on GitHub before importing its own packages. Go resolves this import against the current module.
internal/: Private application packages
The internal/ directory has a special meaning in Go.
It allows you to restrict which packages can import your code.
For example, our rate limiter lives inside:
backend/internal/ratelimit/Because it is inside an internal directory, only packages within the permitted parent directory tree can import it.
In our project, packages inside the backend module can import it, but an unrelated external module cannot.
This restriction is enforced by the Go compiler.
Suppose another module tries to import:
import "github.com/yashdagar/zomato-prep/backend/internal/ratelimit"It will receive an error similar to:
use of internal package github.com/yashdagar/zomato-prep/backend/internal/ratelimit not allowedThis is not merely a naming convention. It is an enforced language-toolchain rule.
Why is this useful?
As a backend grows, not every implementation detail should become a public library.
For example:
internal/ratelimitcontains our rate-limiting implementation.internal/httpxcan contain HTTP response helpers and middleware utilities.cmd/apicontains the executable that wires these components together.
Keeping implementation packages inside internal/ prevents accidental reuse by unrelated projects and makes the intended boundaries clearer.
The internal/ directory is not mandatory. It is a deliberate way to enforce application-level encapsulation.
How the module, directories, and packages fit together
The following diagram shows how Go constructs import paths from your module declaration and directory structure.


Importing third-party dependencies
So far, we have imported only packages that belong to our own project.
Real backend applications also depend on external libraries.
For example, we will use chi as our HTTP router.
You can add it using:
go get github.com/go-chi/chi/v5Go downloads the dependency, resolves its version, and updates the module files.
Your go.mod will now contain something similar to:
module github.com/yashdagar/zomato-prep/backend
go 1.25.0
require github.com/go-chi/chi/v5 v5.2.1The exact version may differ depending on when you run the command.
Understanding semantic versions
Notice the dependency version:
v5.2.1Go dependencies commonly use semantic versioning.
A semantic version has three main components:
MAJOR.MINOR.PATCHFor v5.2.1:
5is the major version.2is the minor version.1is the patch version.
Generally:
- A major version change can introduce breaking API changes.
- A minor version adds functionality while maintaining compatibility.
- A patch version contains backward-compatible fixes.
Go has an additional convention for major versions: version 2 and above are generally represented in module paths with a major-version suffix.
For example:
import "github.com/go-chi/chi/v5"The /v5 suffix is part of the module path. It allows multiple incompatible major versions to coexist without confusing the dependency resolver.
Where dependencies are stored
Go downloads third-party modules into its module cache.
You can inspect the cache location with:
go env GOMODCACHEA typical location on macOS or Linux is:
$GOPATH/pkg/modYou do not normally need to interact with this directory manually.
When your source code imports an external package, Go resolves the corresponding module, downloads it if necessary, and uses the cached source during compilation.
Your application does not need to copy third-party source code into its own repository.
Importing and using chi
Once installed, you can import the router in your application:
package main
import (
"fmt"
"net/http"
"github.com/go-chi/chi/v5"
"github.com/yashdagar/zomato-prep/backend/internal/ratelimit"
)
func main() {
limiter := ratelimit.New(100)
router := chi.NewRouter()
router.Get("/health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Rate limit: %d", limiter.Limit())
})
http.ListenAndServe(":8080", router)
}This example combines three different kinds of imports:
fmtandnet/httpbelong to the Go standard library.github.com/go-chi/chi/v5is an external dependency.github.com/yashdagar/zomato-prep/backend/internal/ratelimitbelongs to our own module.
All three are imported using the same Go import mechanism.
The difference is how Go resolves each package.
The Go commands you will use every day
The go command provides several subcommands for managing, building, and inspecting your project.
Understanding these commands early will make debugging much easier.
go build
go build ./...Compiles all packages in the current module and its subdirectories, subject to Go's package pattern and build constraints.
The ./... pattern means the current directory and all its subdirectories.
For a package containing an executable, Go also produces a binary.
You can build just the API server:
go build -o bin/api ./cmd/apiThis creates an executable at bin/api.
A successful build confirms that the compiler can compile the selected packages and resolve their required imports.
It does not guarantee that the application behaves correctly at runtime.
go run
go run ./cmd/apiCompiles and executes the specified Go program.
This is particularly useful during development because you can run the server without manually creating and managing a binary.
For example:
go run .runs the main package in the current directory, provided the current directory contains an executable package.
go test
go test ./...Runs tests for all packages in the module.
Go identifies test files using the _test.go suffix.
For example:
internal/ratelimit/limiter.golimiter_test.go
A test function typically looks like:
func TestNewLimiter(t *testing.T) {
limiter := New(100)
if got := limiter.Limit(); got != 100 {
t.Fatalf("Limit() = %d, want 100", got)
}
}Test functions begin with Test, accept a *testing.T parameter, and live in a test file.
We will explore testing in detail later. For now, remember that go test ./... is the standard command for running your project's Go tests.
go vet
go vet ./...Runs static analysis checks that identify suspicious code patterns.
Static analysis means examining source code without actually executing the application.
For example, go vet can detect certain incorrect formatting calls, suspicious synchronization patterns, and mistakes involving unreachable code or incorrect API usage.
Consider:
fmt.Printf("%d", "hello")The format expects an integer, but the supplied argument is a string.
A suitable go vet check can identify this mismatch.
go vet does not prove that your application is bug-free. It catches classes of mistakes that the compiler alone may not detect.
gofmt
Go has an official code formatter called gofmt.
Run:
gofmt -w .The -w flag tells the formatter to write formatting changes back to files.
Go formatting is intentionally standardized. Developers do not need to debate indentation, brace placement, or spacing conventions.
You can also format an individual file:
gofmt -w internal/ratelimit/limiter.goTo inspect formatting differences without modifying files:
gofmt -d internal/ratelimit/limiter.goFormatting is not optional style decoration in most Go projects. Consistent formatting makes code easier to read and review.
go mod tidy
As your project evolves, imports and dependencies change.
You might remove a dependency from your source code but still have it listed in go.mod. You might also add an import without having the corresponding dependency declared.
Run:
go mod tidyQuick reference
| Command | Purpose |
|---|---|
go version | Prints the installed Go version |
go env | Displays Go environment configuration |
go build ./... | Compiles all packages |
go run ./cmd/api | Compiles and executes the API server |
go test ./... | Runs package tests |
go vet ./... | Checks for suspicious code |
gofmt -w . | Formats Go source files |
go mod init | Initializes a new module |
go get | Adds or updates dependencies |
go mod tidy | Synchronizes module requirements and checksums |
What happens when you build a Go project?
When you execute:
go build ./...Go does considerably more than simply turn individual .go files into machine code.
At a high level, the process involves several stages.
- Package discovery: Go identifies the packages included by
./.... - Import resolution: It examines import declarations and determines where each imported package comes from.
- Dependency resolution: It uses the module definition and available module cache to locate required external dependencies. Missing dependencies may need to be downloaded.
- Compilation: The compiler processes the source files, checks types, and generates compiled package artifacts.
- Linking: For executable packages, the linker combines the required compiled components into a runnable binary.
Go also maintains a build cache. When source files and their relevant dependencies have not changed, the toolchain can reuse previously compiled results instead of repeating all the work.
This is one reason subsequent builds are often faster than the first build.


Understanding this process helps you distinguish different categories of errors.
For example:
- An unresolved import is a dependency or package resolution problem.
- An undefined identifier is generally a source-code or visibility problem.
- A type mismatch is a compilation problem.
- A missing environment variable may only appear when the program runs.
Not every error reported by go build has the same underlying cause.
Putting the project together
At this point, you should understand the structure we will use throughout the course:
zomato-prep/backend/go.modgo.sumMakefiledocker-compose.yml.golangci.ymlcmd/api/main.go
internal/ratelimit/limiter.golimiter_test.go
httpx/
The responsibilities are deliberately separated:
go.modidentifies the module and declares its dependencies and Go version requirements.go.sumrecords dependency checksums.cmd/apicontains the API server executable.internal/ratelimitcontains the rate-limiting implementation.internal/httpxwill contain reusable HTTP-related implementation details.
As the project grows, you will add more packages without turning main.go into a massive file containing every feature.
The entry point should primarily assemble the application. Individual packages should own their respective responsibilities.
This separation makes code easier to test, maintain, and extend.
Common mistakes to avoid
Before moving on, understand these common mistakes:
1. Initializing the module in the wrong directory.
The go.mod file should live at the root of the Go module. In this project, that is backend/, not zomato-prep/.
2. Using filesystem paths as imports.
Do not import your rate limiter using:
import "./internal/ratelimit"Use its complete module import path instead.
3. Forgetting capitalization rules.
If another package needs to access a type or function, its identifier must be exported.
For example, New is accessible outside its package, while new is not.
4. Treating internal as an ordinary directory.
The internal/ directory has compiler-enforced import restrictions. It is not simply a naming convention.
5. Forgetting go.sum.
Commit go.sum alongside go.mod. It contains checksums that help verify dependency integrity.
6. Assuming a successful build means the application works.
Compilation catches many errors, but runtime behavior, integration problems, and incorrect business logic require additional testing.
Knowledge assessment
Which statement correctly describes the relationship between a Go module and a Go package?
Practical applications
You will apply these concepts immediately in Exercise 1.3: Create the repo, Makefile, lint config and docker-compose.
That exercise establishes the initial project structure and development environment for the backend you will build throughout the course.
You will use the module path to organize your imports, cmd/ to define the API server entry point, and internal/ to keep implementation packages private.
The Go commands introduced here will also become part of your Makefile, so you can consistently build, test, format, and inspect your project without remembering a collection of unrelated commands.
Everything that follows in this course builds on this foundation.
References
Everything above is explained on this page; these are where it comes from (Go 1.2x).