Subscribe

Golang Tutorial 13: Packages and modules

Packages and modules in Go 1.27: go mod init and tidy, go.sum, exported names, internal/, versions and /v2 paths, replace for local work, go work workspaces and tool dependencies, all run for real with the output I got, plus an exercise.

Golang Tutorial 13: Packages and modules

Up to now every example in this series was one main.go in one folder. Real Go code is split into packages, and packages live in modules. Modules also decide which versions of other people's code you get. In this blog we will look at packages and exported names, go mod init and go mod tidy, what go.sum is for, the internal/ folder, versions and /v2 import paths, replace for local work, workspaces with go work, and tool dependencies.

Level: beginner. You only need the basics from the earlier tutorials, the last one was Tutorial 12 on error handling. I ran everything here for real on Go 1.27.3 and pasted the output I got, including the errors. Some of those errors are the most useful part of the post.

Package vs module

A package is a folder of .go files that all start with the same package line. It's the unit you import.

A module is a tree of packages with a go.mod file at the root. It's the unit you version and download. The module path in go.mod is the prefix of every import path inside it.

We'll build a tiny module called linkcheck with this layout:

linkcheck/
  go.mod
  cmd/linkcheck/main.go          package main, the program
  internal/normalize/normalize.go  only linkcheck can import this
  slug/slug.go                   public package, anyone can import

cmd/<name> for programs and plain folders for libraries is just a common convention. The Go tool doesn't care about cmd. It does care about internal, as we'll see.

go mod init

mkdir linkcheck && cd linkcheck
go mod init example.com/linkcheck
mkdir -p cmd/linkcheck internal/normalize slug
go: creating new go.mod: module example.com/linkcheck
go: to add module requirements and sums:
    go mod tidy

The module path should be where the code will live, like github.com/you/linkcheck. If you never publish it, anything works, and example.com/... is a safe placeholder. The new go.mod is three lines:

module example.com/linkcheck

go 1.27.3

The go line is the minimum Go version for this module, and it also sets the language version. In the pointers tutorial I changed just this line to go 1.21 and the same loop printed different results. It actually matters.

Packages and exported names

Here is the public slug package:

// Package slug makes short, URL-safe codes from text.
package slug

import "strings"

// maxLen is unexported: other packages cannot see it.
const maxLen = 16

// Make turns "Hello, World!" into "hello-world".
func Make(s string) string {
    var b strings.Builder
    dash := false
    for _, r := range strings.ToLower(s) {
        switch {
        case r >= 'a' && r <= 'z', r >= '0' && r <= '9':
            b.WriteRune(r)
            dash = false
        case b.Len() > 0 && !dash:
            b.WriteByte('-')
            dash = true
        }
    }
    out := strings.TrimSuffix(b.String(), "-")
    if len(out) > maxLen {
        out = strings.TrimSuffix(out[:maxLen], "-")
    }
    return out
}

Go has no public or private keywords. A name that starts with a capital letter is exported (visible outside the package), anything else is not. Make is exported, maxLen isn't. When I tried slug.maxLen from another package, the compiler just said:

cmd/tmpx/main.go:9:32: undefined: slug.maxLen

Not the friendliest message, it doesn't tell you the name exists but is unexported. Remember it when you see "undefined" for something you know is there.

The package name is the last part of the import path by convention, example.com/linkcheck/slug is package slug. Keep names short and lower case, and avoid util or common, they end up as a dumping ground.

internal/

// Package normalize cleans up URLs before we store them.
// It lives under internal/, so only code inside example.com/linkcheck can import it.
package normalize

import (
    "net/url"
    "strings"
)

// URL lower-cases the scheme and host and drops a trailing slash.
func URL(raw string) (string, error) {
    u, err := url.Parse(strings.TrimSpace(raw))
    if err != nil {
        return "", err
    }
    u.Scheme = strings.ToLower(u.Scheme)
    u.Host = strings.ToLower(u.Host)
    u.Path = strings.TrimSuffix(u.Path, "/")
    return u.String(), nil
}

A package under a folder named internal can only be imported by code rooted at the parent of internal. Here that's everything under linkcheck/. To check it, I made a second module example.com/outsider that imports example.com/linkcheck/internal/normalize:

package example.com/outsider
    main.go:6:2: use of internal package example.com/linkcheck/internal/normalize not allowed

This is the most useful folder name in Go. Put everything you don't want to promise to other people under internal/, and you're free to change it any time. I prefer to start new code in internal/ and move it out only when somebody really needs it.

Adding a dependency with go mod tidy

The program uses our two packages and one outside package, golang.org/x/mod/semver, which compares version strings.

package main

import (
    "fmt"
    "os"

    "example.com/linkcheck/internal/normalize"
    "example.com/linkcheck/slug"
    "golang.org/x/mod/semver"
)

func main() {
    u, err := normalize.URL(" HTTPS://Example.COM/Docs/ ")
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    fmt.Println(u)
    fmt.Println(slug.Make("Golang Tutorial 13: Packages and modules"))

    versions := []string{"v1.10.0", "v1.9.3", "v2.0.0-rc.1"}
    semver.Sort(versions)
    fmt.Println(versions, semver.Major("v2.0.0-rc.1"))
}

Imports are grouped: standard library first, then a blank line, then everything else. gofmt keeps each group sorted, see indentation and formatting in golang. The first build fails, which is expected:

cmd/linkcheck/main.go:9:2: no required module provides package golang.org/x/mod/semver; to add it:
    go get golang.org/x/mod/semver

You can run that go get, but I nearly always run go mod tidy instead. It reads every import in the module, adds what's missing and removes what isn't used anymore.

go mod tidy
go run ./cmd/linkcheck
go: finding module for package golang.org/x/mod/semver
go: downloading golang.org/x/mod v0.43.0
go: found golang.org/x/mod/semver in golang.org/x/mod v0.43.0
https://example.com/Docs
golang-tutorial
[v1.9.3 v1.10.0 v2.0.0-rc.1] v2

Note that semver.Sort put v1.10.0 after v1.9.3. A plain string sort would get that wrong. And go.mod now has a require line:

module example.com/linkcheck

go 1.27.3

require golang.org/x/mod v0.43.0

What go.sum is for

go mod tidy also wrote a go.sum:

golang.org/x/mod v0.43.0 h1:MFuq5J6s35W9D3IjkwyWc9vHh0nENOrt5K8Iof4ofmg=
golang.org/x/mod v0.43.0/go.mod h1:4ec1JnuyBz5+FIVhg86UsA39YG8BpnrZdJYSNHmGzHY=

These are hashes of the module's files and of its go.mod. The Go tool checks every download against them, and checks new modules against the public checksum database at sum.golang.org. If someone changes a tagged version after the fact, the build fails instead of quietly using different code. Commit go.sum together with go.mod, always. It is not a lock file you can delete and regenerate whenever you like, well you can, but then you lose that protection for the versions you already had.

Versions: go get, go list and /v2

Go modules use semantic versions: vMAJOR.MINOR.PATCH. To move a dependency to a specific version, use go get with @:

go get golang.org/x/mod@v0.42.0
go get golang.org/x/mod@latest
go list -m -versions golang.org/x/mod

The last command prints every published version, which is handy before picking one. The first two printed this:

go: downloading golang.org/x/mod v0.42.0
go: downgraded golang.org/x/mod v0.43.0 => v0.42.0
go: upgraded golang.org/x/mod v0.42.0 => v0.43.0

go list -m all shows every module in the build. On my first run itself it showed golang.org/x/tools v0.52.0 too, which surprised me, since I never imported anything from x/tools. It's there because golang.org/x/mod lists it in its own go.mod. go mod why golang.org/x/mod/semver tells you which of your packages pulls a package in, and it's my first stop when a dependency shows up that I don't recognise.

Go picks versions with "minimal version selection": if two modules need different versions of the same dependency, the build uses the highest of the minimums asked for, and nothing newer. No surprise upgrades because a new release came out last night.

Major versions are the special case. A v2 that breaks callers gets a new module path ending in /v2. I made a textkit module with a Truncate(s, n) string function, and then a textkit-v2 folder whose go.mod says module example.com/textkit/v2, where Truncate also returns a bool. Both can be imported in the same program:

package main

import (
    "example.com/textkit"
    textkitv2 "example.com/textkit/v2"
)

func shortTitle(s string) string { return textkit.Truncate(s, 20) }

func shortTitleV2(s string) (string, bool) { return textkitv2.Truncate(s, 20) }

Both versions' package is called textkit, so one of them needs an alias. This looks odd at first. But it's what lets a big codebase move from v1 to v2 one file at a time.

replace for local work

textkit isn't published anywhere, so example.com/textkit can't be downloaded. Before Go had workspaces, the answer was a replace directive:

go mod edit -replace example.com/textkit=../textkit
go mod tidy
module example.com/linkcheck

go 1.27.3

require (
    example.com/textkit v0.0.0-00010101000000-000000000000
    golang.org/x/mod v0.43.0
)

replace example.com/textkit => ../textkit

That works, and the program printed Golang Tutorial 13:... from textkit.Truncate. See, the problem is that replace lives in go.mod, which you commit. Push it by mistake and CI fails, because ../textkit doesn't exist on the build machine. That fake v0.0.0-00010101000000-000000000000 version is also a giveaway in a code review. I'd use replace for a quick test, or to pin a forked dependency on purpose, not for day to day work on two modules.

Workspaces with go work

A workspace lets several local modules see each other without touching their go.mod files. I removed the replace and the require again and created a go.work in the folder above:

cd linkcheck
go mod edit -dropreplace example.com/textkit -droprequire example.com/textkit
cd ..
go work init ./linkcheck ./textkit
go work use ./textkit-v2
go 1.27.3

use (
    ./linkcheck
    ./textkit
    ./textkit-v2
)

Now go run ./cmd/linkcheck inside linkcheck finds textkit from the workspace. Then I ran go mod tidy in linkcheck, out of habit, and it failed:

go: finding module for package example.com/textkit
go: example.com/linkcheck/cmd/linkcheck imports
    example.com/textkit: cannot find module providing package example.com/textkit: unrecognized import path "example.com/textkit": reading https://example.com/textkit?go-get=1: 404 Not Found

That's by design. go mod tidy works on one module's go.mod and ignores the workspace, so it went looking for example.com/textkit on the internet. Same with GOWORK=off go build ./..., which is roughly what a CI machine without the go.work file sees:

cmd/linkcheck/title.go:3:8: no required module provides package example.com/textkit; to add it:
    go get example.com/textkit

So a workspace is for local development. Before you push, the module you depend on has to be published with a real version and required in go.mod. The usual advice is to not commit go.work, and I'd keep it out of git too. go env GOWORK prints which go.work is active if you ever have a doubt.

Tool dependencies

Since Go 1.24 a module can also track the tools it uses, like linters or code generators, in go.mod. I added govulncheck (more about it in finding vulnerable dependencies in golang using govulncheck):

go get -tool golang.org/x/vuln/cmd/govulncheck@latest
go tool govulncheck ./...

go.mod got a tool line and the tool's own dependencies as indirect requires. Go 1.27's go mod tidy keeps at most two require blocks, one for direct and one for indirect, and that's the shape I got:

module example.com/linkcheck

go 1.27.3

require golang.org/x/mod v0.43.0

require (
    golang.org/x/sync v0.25.0 // indirect
    golang.org/x/sys v0.50.0 // indirect
    golang.org/x/telemetry v0.0.0-20261116191925-e77a43154acb // indirect
    golang.org/x/tools v0.53.0 // indirect
    golang.org/x/vuln v1.10.0 // indirect
)

tool golang.org/x/vuln/cmd/govulncheck

And the scan found something, which I hadn't planned:

Vulnerability #1: GO-2026-6859
    HTTP/1 server crash due to MaxBytesReader header race in net/http
  More info: https://pkg.go.dev/vuln/GO-2026-6859
  Standard library
    Found in: stdlib@go1.27.3
    Fixed in: stdlib@go1.27.4

My Mac's Go is one patch release behind. The code doesn't call the affected function, so govulncheck rates it as not affecting the code, but it's a good reminder that the Go toolchain is a dependency too. Anyone who clones the repo runs the same pinned version with go tool govulncheck, no separate install step, and that's the main reason I like the tool directive.

Exercise

Make a third module, example.com/clicks, next to the others. It has one type, Counter, with a Hit(code string) int method that counts visits per code and is safe to call from many goroutines (use a sync.Mutex, Tutorial 8 has the basics). Add it to the workspace with go work use, write a second program cmd/linkstats in linkcheck that uses it, and then run it again with GOWORK=off. Before you run that last command, guess the error.

Here's mine.

// Package clicks counts visits per short code.
package clicks

import "sync"

// Counter is safe for use from many goroutines.
type Counter struct {
    mu sync.Mutex
    m  map[string]int
}

// New returns an empty Counter.
func New() *Counter { return &Counter{m: map[string]int{}} }

// Hit records one visit and returns the new total for code.
func (c *Counter) Hit(code string) int {
    c.mu.Lock()
    defer c.mu.Unlock()
    c.m[code]++
    return c.m[code]
}
package main

import (
    "fmt"

    "example.com/clicks"
)

func main() {
    c := clicks.New()
    for _, code := range []string{"go", "k9", "go", "go"} {
        fmt.Println(code, c.Hit(code))
    }
}
cd clicks && go mod init example.com/clicks && cd ..
go work use ./clicks
cd linkcheck
go run ./cmd/linkstats
GOWORK=off go run ./cmd/linkstats
go 1
k9 1
go 2
go 3
cmd/linkstats/main.go:6:2: no required module provides package example.com/clicks; to add it:
    go get example.com/clicks

New returns a pointer because Counter holds a mutex, and a mutex must not be copied after first use. go vet checks for that with its copylocks check.

If you'd rather share code across repos without publishing a module at all, there's another approach in keeping a shared golang package in sync across repos with a golden file hash test. And when go vet ./... trips over stray files in a repo in CI, this post on go list failures in GitHub Actions covers the fix.