Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

GO
Go
0/12 completed
Beginner
Hello GoTypes and variablesControl flowFunctions
Intermediate
Arrays, slices and mapsStructs and methodsInterfacesError handling
Advanced
GenericsGoroutines and channels
Pro
Building an HTTP serverModules, testing and tooling
Tracks / Go / Pro

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:

bash
mkdir pricing && cd pricing
go mod init github.com/asha/pricing
cat go.mod
Output
go: 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:

pricing/discount/discount.go
// 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:

pricing/cmd/quote/main.go
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))
}
bash
cd pricing
go run ./cmd/quote
go build -o bin/quote ./cmd/quote
Output
after 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):

pricing/discount/discount_test.go
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)
	}
}
bash
cd pricing
go test ./...
go test -v -run TestApplyTable ./discount
Output
?   	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.00Xs
  • go test ./... runs the tests in every package of the module.
  • t.Errorf reports a failure and continues; t.Fatalf stops this test.
  • t.Run creates 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:

bash
# change math.Round to math.Floor in round2, then:
go test ./discount
Output
--- 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
FAIL

The 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

bash
go test -cover ./discount
Output
ok  	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:

pricing/api/api.go
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})
}
pricing/api/api_test.go
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)
		}
	}
}
bash
go test ./api
Output
ok  	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:

pricing/discount/bench_test.go
package discount

import "testing"

func BenchmarkApply(b *testing.B) {
	for b.Loop() {
		Apply(1999, 15)
	}
}
bash
go test -bench=. -benchmem ./discount
Output
BenchmarkApply-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:

pricing/cmd/order/main.go
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())
}
bash
cd pricing
go get github.com/google/uuid@v1.6.0
go mod tidy
go run ./cmd/order
cat go.mod
Output
go: 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.mod records your direct dependencies and their exact versions. go.sum holds cryptographic checksums, so a tampered download is rejected. Commit both.
  • go mod tidy adds anything your code imports and removes what it no longer uses. Run it before committing.
  • Versions follow semantic versioning; go get pkg@latest upgrades, and go list -m -u all shows 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

bash
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 comments
Output
go 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:

yaml
- uses: actions/setup-go@v5
  with: { go-version: '1.27' }
- run: test -z "$(gofmt -l .)"
- run: go vet ./...
- run: go test -race -cover ./...

Practice

  1. Create a module with a package stringsx containing Reverse(s string) string, and a table-driven test with at least five cases, including an empty string and a non-English word.
  2. Make one test fail on purpose and read the output. Then fix it.
  3. Write a benchmark comparing building a string with += in a loop against strings.Builder.
  4. Add github.com/google/uuid to a project, use it, run go mod tidy, and look at the changes in go.mod.
✎ Check your understanding

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?

← Building an HTTP server