Modules, testing and tooling
Go ships with everything a real project needs in the single go command: dependency management (modules), a test runner with benchmarks and coverage, a formatter, a linter and documentation. This lesson builds a small project with a package, tests and a third-party dependency, the way professional Go projects are organised.
Creating a module
A module is a collection of packages with a go.mod file at its root. The module path is usually where the code lives online:
mkdir pricing && cd pricing
go mod init github.com/asha/pricing
cat go.modgo: creating new go.mod: module github.com/asha/pricing module github.com/asha/pricing go 1.27.4
Every folder inside the module is a package. Let's add one:
// Package discount calculates prices after discounts and tax.
package discount
import (
"errors"
"math"
)
// ErrInvalidPercent is returned for discounts outside 0–100.
var ErrInvalidPercent = errors.New("discount must be between 0 and 100")
// Apply returns price reduced by percent, rounded to 2 decimals.
func Apply(price float64, percent float64) (float64, error) {
if percent < 0 || percent > 100 {
return 0, ErrInvalidPercent
}
return round2(price * (1 - percent/100)), nil
}
// WithTax adds tax (e.g. 0.18 for 18%) to price.
func WithTax(price, rate float64) float64 {
return round2(price * (1 + rate))
}
func round2(x float64) float64 { return math.Round(x*100) / 100 }And a program that uses it. Packages are imported by module path + folder:
package main
import (
"fmt"
"log"
"github.com/asha/pricing/discount"
)
func main() {
p, err := discount.Apply(1999, 15)
if err != nil {
log.Fatal(err)
}
fmt.Printf("after discount: %.2f, with 18%% tax: %.2f\n", p, discount.WithTax(p, 0.18))
}cd pricing
go run ./cmd/quote
go build -o bin/quote ./cmd/quoteafter discount: 1699.15, with 18% tax: 2005.00 quote
A common layout: reusable packages in their own folders (or under internal/, which other modules can't import), and executables under cmd/<name>/.
Tests
Tests live next to the code in files ending in _test.go. A test is a function named TestXxx(t *testing.T):
package discount
import (
"errors"
"testing"
)
func TestApply(t *testing.T) {
got, err := Apply(200, 25)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got != 150 {
t.Errorf("Apply(200, 25) = %v, want 150", got)
}
}
// A table-driven test: the idiomatic way to test many cases.
func TestApplyTable(t *testing.T) {
tests := []struct {
name string
price float64
percent float64
want float64
wantErr error
}{
{"no discount", 100, 0, 100, nil},
{"half price", 99.99, 50, 50, nil},
{"free", 10, 100, 0, nil},
{"negative", 10, -5, 0, ErrInvalidPercent},
{"too big", 10, 150, 0, ErrInvalidPercent},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Apply(tt.price, tt.percent)
if !errors.Is(err, tt.wantErr) {
t.Fatalf("error = %v, want %v", err, tt.wantErr)
}
if got != tt.want {
t.Errorf("Apply(%v, %v) = %v, want %v", tt.price, tt.percent, got, tt.want)
}
})
}
}
func TestWithTax(t *testing.T) {
if got := WithTax(100, 0.18); got != 118 {
t.Errorf("WithTax(100, 0.18) = %v, want 118", got)
}
}cd pricing
go test ./...
go test -v -run TestApplyTable ./discount? github.com/asha/pricing/cmd/quote [no test files]
ok github.com/asha/pricing/discount 0.00Xs
=== RUN TestApplyTable
=== RUN TestApplyTable/no_discount
=== RUN TestApplyTable/half_price
=== RUN TestApplyTable/free
=== RUN TestApplyTable/negative
=== RUN TestApplyTable/too_big
--- PASS: TestApplyTable (0.00s)
--- PASS: TestApplyTable/no_discount (0.00s)
--- PASS: TestApplyTable/half_price (0.00s)
--- PASS: TestApplyTable/free (0.00s)
--- PASS: TestApplyTable/negative (0.00s)
--- PASS: TestApplyTable/too_big (0.00s)
PASS
ok github.com/asha/pricing/discount 0.00Xsgo test ./...runs the tests in every package of the module.t.Errorfreports a failure and continues;t.Fatalfstops this test.t.Runcreates a subtest per table row, each with its own name, so a failure says exactly which case broke. Run one with-run 'TestApplyTable/half'.- Packages without tests show
[no test files].
When a test fails
Let's break round2 and see:
# change math.Round to math.Floor in round2, then:
go test ./discount--- FAIL: TestApplyTable (0.00Xs)
--- FAIL: TestApplyTable/half_price (0.00Xs)
discount_test.go:40: Apply(99.99, 50) = 49.99, want 50
FAIL
FAIL github.com/asha/pricing/discount 0.00Xs
FAILThe output names the subtest, the file and line, and the values. That's why good test messages always say what they got and what they wanted.
Coverage
go test -cover ./discountok github.com/asha/pricing/discount 0.00Xs coverage: 100.0% of statements
go test -coverprofile=c.out ./... && go tool cover -html=c.out opens a page showing exactly which lines your tests never ran.
Testing HTTP handlers
The net/http/httptest package runs handlers without a real network:
package api
import (
"encoding/json"
"net/http"
"strconv"
"github.com/asha/pricing/discount"
)
func Quote(w http.ResponseWriter, r *http.Request) {
price, err1 := strconv.ParseFloat(r.URL.Query().Get("price"), 64)
pct, err2 := strconv.ParseFloat(r.URL.Query().Get("discount"), 64)
if err1 != nil || err2 != nil {
http.Error(w, "price and discount must be numbers", http.StatusBadRequest)
return
}
final, err := discount.Apply(price, pct)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]float64{"price": final})
}package api
import (
"net/http/httptest"
"strings"
"testing"
)
func TestQuote(t *testing.T) {
tests := []struct {
url string
wantCode int
wantBody string
}{
{"/quote?price=200&discount=10", 200, `{"price":180}`},
{"/quote?price=abc&discount=10", 400, "must be numbers"},
{"/quote?price=10&discount=120", 400, "between 0 and 100"},
}
for _, tt := range tests {
rec := httptest.NewRecorder()
Quote(rec, httptest.NewRequest("GET", tt.url, nil))
if rec.Code != tt.wantCode || !strings.Contains(rec.Body.String(), tt.wantBody) {
t.Errorf("%s: got %d %q, want %d containing %q", tt.url, rec.Code, rec.Body.String(), tt.wantCode, tt.wantBody)
}
}
}go test ./apiok github.com/asha/pricing/api 0.00Xs
Benchmarks
Functions named BenchmarkXxx(b *testing.B) measure performance. b.Loop() (Go 1.24+) runs the body as many times as needed for a stable measurement:
package discount
import "testing"
func BenchmarkApply(b *testing.B) {
for b.Loop() {
Apply(1999, 15)
}
}go test -bench=. -benchmem ./discountBenchmarkApply-10 … 2.184 ns/op 0 B/op 0 allocs/op
The columns are nanoseconds per operation, bytes allocated and allocations per operation. Exact numbers depend on the machine; compare before and after a change on the same one (benchstat does this properly).
Dependencies
Add a third-party package with go get. Here, Google's UUID package:
package main
import (
"fmt"
"github.com/google/uuid"
)
func main() {
id := uuid.New()
fmt.Println("order id has", len(id.String()), "characters, version", id.Version())
}cd pricing
go get github.com/google/uuid@v1.6.0
go mod tidy
go run ./cmd/order
cat go.modgo: added github.com/google/uuid v1.6.0 order id has 36 characters, version VERSION_4 require github.com/google/uuid v1.6.0 github.com/google/uuid v1.6.0
go.modrecords your direct dependencies and their exact versions.go.sumholds cryptographic checksums, so a tampered download is rejected. Commit both.go mod tidyadds anything your code imports and removes what it no longer uses. Run it before committing.- Versions follow semantic versioning;
go get pkg@latestupgrades, andgo list -m -u allshows available updates. - Downloads go through the public module proxy and checksum database by default, so builds are reproducible even if the original repository disappears.
The rest of the toolbox
go vet ./... # finds suspicious code: wrong printf verbs, unreachable code, copied locks…
gofmt -l . # lists files that aren't formatted
go doc ./discount Apply # documentation from the commentsgo vet: no problems
0 unformatted files
package discount // import "github.com/asha/pricing/discount"
func Apply(price float64, percent float64) (float64, error)
Apply returns price reduced by percent, rounded to 2 decimals.| Command | Does |
|---|---|
go fmt ./... |
Format every file |
go vet ./... |
Built-in static checks (also run by go test) |
go test -race ./... |
Tests with the race detector |
go doc pkg Name |
Documentation, generated from the comment above each exported name |
go mod tidy |
Clean up go.mod and go.sum |
go install pkg@version |
Install a Go tool into ~/go/bin, e.g. golang.org/x/tools/cmd/goimports@latest |
go build -ldflags="-s -w" |
Smaller binary (strips debug info) |
go tool pprof |
CPU and memory profiling |
Popular extra tools: staticcheck and golangci-lint (dozens of linters in one), govulncheck (finds known vulnerabilities in your dependencies that your code actually calls), and gopls (the language server behind editor features).
A CI pipeline in four lines
Everything above fits in a GitHub Actions job, and it's what most Go projects run on every pull request:
- uses: actions/setup-go@v5
with: { go-version: '1.27' }
- run: test -z "$(gofmt -l .)"
- run: go vet ./...
- run: go test -race -cover ./...Practice
- Create a module with a package
stringsxcontainingReverse(s string) string, and a table-driven test with at least five cases, including an empty string and a non-English word. - Make one test fail on purpose and read the output. Then fix it.
- Write a benchmark comparing building a string with
+=in a loop againststrings.Builder. - Add
github.com/google/uuidto a project, use it, rungo mod tidy, and look at the changes ingo.mod.
1.What file marks the root of a Go module?
2.How does Go find tests?
3.Why use t.Run in a table-driven test?
4.Why commit go.sum?