Security in Go from cryptography to the supply chain: using AES-GCM and Argon2id from the crypto packages correctly, signing, verifying, and rotating JWTs with golang-jwt/v5, OAuth2/OIDC flows with golang.org/x/oauth2 and go-oidc including PKCE, secrets management with Vault and SOPS beyond the env-var pitfalls — and the supply chain locked down with govulncheck, GOPRIVATE, and SBOMs.
The task service from module 10 is getting serious: the tests should move to github.com/stretchr/testify, and github.com/golang-migrate/migrate/v4 takes over the database migrations. As soon as the first dependencies land, the questions arrive that spawned entire manifest formats in other languages: who decides which version of a library ends up in the final build? What happens when two packages need different versions of the same module? And what is actually in that go.sum file that appears with a few dozen lines at the first go build?
Go's answer to all of this is deliberately boring — and that's exactly what makes it strong. A module is declared in go.mod, versions are picked by the Minimal Version Selection (MVS) algorithm, integrity is sealed by go.sum, and downloads come from the module proxy proxy.golang.org by default since Go 1.13. No lockfile liturgy, no diamond problem: the same go.mod produces the same build on every machine of the team.
MVS picks the highest required version — never the newest
Minimal Version Selection does not mean "take the oldest", it means: for each dependency, take the highest version that any module in the build graph explicitly requires — and never look at what else happens to be available on the proxy. If A requires x/text v0.14.0 and B requires x/text v0.19.0, Go builds with v0.19.0, regardless of v0.21.0 already existing. The consequence: upgrades happen only when you trigger them, and builds stay reproducible because the selection depends only on the go.mod files — never on a random moment on the network.
The anatomy of a real go.mod from the project:
// go.mod — the heart of the module github.com/acme/taskd
module github.com/acme/taskd
// Since Go 1.21 this line also governs the toolchain: if it does not
// match the installed Go version, Go downloads the matching one
// (see the toolchain directive).
go 1.25
require (
github.com/golang-migrate/migrate/v4 v4.18.1
github.com/stretchr/testify v1.10.0
)
require (
// indirect dependencies: this list is maintained by `go mod tidy`,
// split out per module since Go 1.17 (module graph pruning).
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
)
// Terminal: adding a dependency
// $ go get github.com/stretchr/testify@v1.10.0 && go mod tidy
// → go: added github.com/stretchr/testify v1.10.0
//
// Terminal: what is in the build graph? (filtered)
// $ go list -m all | head -3
// → github.com/acme/taskd
// → github.com/davecgh/go-spew v1.1.1
// → github.com/golang-migrate/migrate/v4 v4.18.1
go get updates versions, go mod tidy keeps require in sync with the packages actually imported — it removes what nobody imports anymore and adds what is imported but not yet listed. The /v4 suffix in migrate is not decoration: modules with a major version above 1 carry the number in their path, so v4 and a (hypothetical) v5 can coexist without fighting each other.
The most common misconception around modules concerns go.sum. The file looks like a lockfile — but it is not. It holds checksums (h1: hashes) for module content and go.mod files, verified on every download against the checksum database sum.golang.org. Which version gets built is decided exclusively by MVS based on the go.mod files.
// go.sum — two lines per dependency: module content and go.mod file
// github.com/stretchr/testify v1.10.0 h1:eiSyrtoKnKsA+...
// github.com/stretchr/testify v1.10.0/go.mod h1:UcvrxSs7...
//
// What go.sum does NOT do: pin versions. To change a version,
// change go.mod (via go get) — never go.sum.
//
// Terminal: what happens with a tampered go.sum?
// $ go build ./... # testify line in go.sum modified
// → verifying github.com/stretchr/testify@v1.10.0: checksum mismatch
// → SECURITY ERROR
// → This download does not match an earlier download recorded in the go.sum log.
//
// Terminal: and why deleting never fixes anything:
// $ rm go.sum && go mod tidy && go build ./...
// → go: downloading github.com/stretchr/testify v1.10.0
// → (a fresh go.sum is generated, the build succeeds)
The proxy itself — GOPROXY=https://proxy.golang.org,direct is the default — makes downloads fast and auditable: once published, module versions are immutable there, and GOPRIVATE=corp.example.com tells Go since Go 1.13 that internal modules should bypass the proxy and the checksum database, fetching straight from the company Git instead.
⚠ Common mistake: treating
go.sumas an npm-style lockfile and editing it by hand — bumping versions, deleting lines to "repair" a misbehaving package. The tweak vanishes at the nextgo mod tidy(the file is regenerated), and half an hour of debugging was spent for nothing. Versions are changed exclusively viago get pkg@v1.2.3orgo get -u pkgingo.mod; ifgo.sumitself is corrupt, delete the whole file and regenerate it withgo mod tidy— never perform surgery on individual lines.
Check: Module A requires golang.org/x/text v0.14.0, module B requires x/text v0.19.0. v0.21.0 already exists on the proxy. Which version does MVS pick for the build?
Answer: v0.19.0 — the highest version explicitly required by any module in the build graph
MVS collects all explicitly required versions and takes the maximum per module — here v0.19.0. What the proxy has on offer plays no role, and a genuine conflict would only arise if two versions of the same major version were incompatible — which, with the major version in the path (e.g. /v4 and /v5), would produce two parallel modules anyway, not an abort.
Takeaways:
go.mod declares the module path, Go version, and requirements; go get changes versions, go mod tidy keeps the file in sync with the code.go.sum is an integrity seal (checksums against sum.golang.org), not a lockfile: editing it is futile; deleting it and running go mod tidy regenerates it.GOPRIVATE keeps internal modules out of the proxy and checksum database./v4) and can coexist with other major versions.The task service works — but everything lives in one package: the store, HTTP handlers, mail delivery, configuration, every type definition. Now the reporting team from another department wants exactly one thing reused: the Store. At the same time someone stumbles into import cycle not allowed during a refactor, and out of desperation a proposal circulates to move everything into a shared models package.
This is exactly where the project decides whether it will be pleasant or painful a year from now. In Go, the package is the only real encapsulation boundary: no per-field private, no friend mechanism — whatever is capitalized is visible to everyone allowed to import the package. Cutting a package means defining a public API. The Interface Segregation principle from the Solid Principles series applies verbatim at package level: small surfaces, few exports, no "here is everything, help yourself".
A package is an API, not a folder
The package name appears at every call site (store.Add, not taskd_internal_store.Add) — it is part of the readability of every import. Rules of thumb: a package gets a singular noun name and a reason to exist expressible in one sentence. If it takes two sentences joined by "and", it is usually two packages. And an export is a promise: everything capitalized must be kept compatible — so export only what outsiders genuinely need.
The classic layout for Go apps has established itself around precisely these boundaries: cmd/ for binary entry points, internal/ for everything that should be protected from foreign imports.
// taskd/ — the layout this module keeps building on
// taskd/
// ├── cmd/
// │ ├── taskd/main.go // binary 1: the HTTP server
// │ └── taskctl/main.go // binary 2: the CLI tool
// ├── internal/
// │ ├── store/store.go // package store
// │ ├── api/handlers.go // package api
// │ └── mailer/mailer.go // package mailer
// ├── go.mod
// └── go.sum
//
// package store — internal/store/store.go
package store
// Task is exported: visible to cmd/ and all internal/ packages.
type Task struct {
ID int
Title string
Done bool
}
// next is unexported: implementation, not part of the API.
var next = 0
func New() *Store { return &Store{tasks: map[int]Task{}} }
What makes internal/ special: the visibility rule is not convention but toolchain. Code under internal/ can only be imported by code in the directory tree above the internal folder — in this case, by the module github.com/acme/taskd itself. A foreign module gets a hard compiler message, not a styleguide nudge:
// Terminal: a FOREIGN module attempts the import
// $ cd ~/git/reporting && go get github.com/acme/taskd && go build ./...
// → package github.com/acme/taskd/internal/store is not in std
// → use of internal package github.com/acme/taskd/internal/store not allowed
//
// Terminal: inside the own module, everything is allowed
// $ cd ~/git/taskd && go build ./...
// → (no output — cmd/taskd may import internal/store)
So the API design answer for the reporting team is: either deliberately export a small, stable package outside internal/ (say pkg/… or a separate module — more in lesson 55), or give the reporting team an interface that it defines.
The second pillar of API design is a Go trait that newcomers from Java and C# often find irritating: interfaces are defined not at the provider but at the consumer — where the functionality is needed. The API needs a notification when a new task is created, and that — nothing more — is what its interface says. The mailer later satisfies it implicitly, without ever knowing about it.
// internal/api/handlers.go
package api
import "github.com/acme/taskd/internal/store"
// Notifier is defined by the consumer: exactly the method the API
// needs — not the full surface of the mailer.
type Notifier interface {
TaskCreated(t store.Task) error
}
// Handler receives the interface injected (lesson 54 digs deeper).
type Handler struct {
store *store.Store
notifier Notifier
}
func NewHandler(s *store.Store, n Notifier) *Handler {
return &Handler{store: s, notifier: n}
}
// internal/mailer/mailer.go
package mailer
// Mailer does not know api — and does not have to:
// TaskCreated automatically satisfies api.Notifier.
type Mailer struct{ smtpAddr string }
func New(smtpAddr string) *Mailer { return &Mailer{smtpAddr: smtpAddr} }
func (m *Mailer) TaskCreated(t store.Task) error {
return m.send(t.Title + " — created")
}
// cmd/taskd/main.go — the bracket that knows both sides
// var _ api.Notifier = (*mailer.Mailer)(nil) // compile-time check
This direction — interface at the consumer, implementation at the provider, connected only in main — is the decisive rehearsal for the architecture of the next lesson. It also breaks the import cycle cleanly: api imports store, mailer imports store, and nobody imports api.
⚠ Common mistake: reacting to an import cycle with the reflex "let's move all types into a shared
modelsorcommonpackage". That breaks the cycle mechanically, but the god package soon imports everything and is imported by everything — a change to any single type touches the whole project, and the original package boundaries exist only on paper. The clean way: break the cycle where it arises — put the types both sides truly share into the one package that describes the domain (herestore), and reroute bidirectional dependencies through a consumer interface.
Check: A repo contains two modules: github.com/acme/taskd (module root with internal/store) and github.com/acme/taskctl as a separate go.mod in a subfolder. What holds?
Answer: No import possible: internal/ code is visible only within the same module — taskctl is its own module and therefore outside
The internal/ rule draws the line at the module, not the repo: internal/ code is importable only from the directory tree above the internal folder — and that tree ends at the own go.mod. A second module in the same repo is a foreign importer to this rule and receives the same compiler message as a package from the open internet.
Takeaways:
cmd/ keeps the main entry points lean, internal/ protects the rest by compiler rule: only code in the same module may import.api.models/common catch-alls couple everything to everything.The board wants tasks in Postgres instead of memory — and casually asks whether the business rule "when a task is completed, the system notifies the team" could be tested without spinning up a database every time. Both are the same question: how tightly is the business logic coupled to its environment? That is exactly what the Hexagonal Architecture (Ports & Adapters) addresses, dissected in depth by the Architectural Styles series: the domain sits at the center and defines ports — interfaces for everything it needs from the outside. The outside world plugs in as adapters implementing a port. The dependency direction always points inward: HTTP knows the domain, the domain knows no HTTP.
Go makes this pattern unusually cheap — thanks to implicit interface satisfaction and consumer interfaces from lesson 52, a port is simply an interface in the domain package. No DI container, no framework conventions, just ordinary Go types.
Port = interface in the domain, adapter = a type beside it
The port describes what the domain needs — in its language, with its types and its errors (like task.ErrNotFound). The adapter translates: it knows the domain and maps sql.ErrNoRows onto task.ErrNotFound. Symmetrically at the driving port: the HTTP adapter calls the service. The domain itself imports neither net/http nor database/sql — and precisely this absence makes it testable in milliseconds.
First the domain with its ports:
// internal/task/domain.go
package task
import (
"context"
"errors"
"time"
)
var ErrNotFound = errors.New("task not found")
// Store is the persistence port — defined by the domain,
// in the language of the domain. It says nothing about SQL or files.
type Store interface {
Save(ctx context.Context, t Task) error
ByID(ctx context.Context, id int) (Task, error)
}
// Notifier is the port to the outside world (email, chat, whatever).
type Notifier interface {
TaskCompleted(t Task) error
}
// Service holds the business rules and knows only ports.
type Service struct {
store Store
notifier Notifier
}
func NewService(store Store, notifier Notifier) *Service {
return &Service{store: store, notifier: notifier}
}
func (s *Service) Complete(ctx context.Context, id int) error {
t, err := s.store.ByID(ctx, id)
if err != nil {
return err
}
t.Done = true
t.CompletedAt = time.Now()
if err := s.store.Save(ctx, t); err != nil {
return err
}
return s.notifier.TaskCompleted(t)
}
And an adapter satisfying that port without the domain ever hearing about it:
// internal/adapters/postgres/store.go
package postgres
import (
"context"
"database/sql"
"errors"
"github.com/acme/taskd/internal/task"
)
// Store implements task.Store implicitly. It imports the domain —
// never the other way around. That IS the inward dependency direction.
type Store struct{ db *sql.DB }
func NewStore(db *sql.DB) *Store { return &Store{db: db} }
func (s *Store) ByID(ctx context.Context, id int) (task.Task, error) {
row := s.db.QueryRowContext(ctx,
"SELECT id, title, done FROM tasks WHERE id = $1", id)
var t task.Task
if err := row.Scan(&t.ID, &t.Title, &t.Done); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return task.Task{}, task.ErrNotFound // translated for the domain
}
return task.Task{}, err
}
return t, nil
}
func (s *Store) Save(ctx context.Context, t task.Task) error {
_, err := s.db.ExecContext(ctx,
"UPDATE tasks SET title = $1, done = $2 WHERE id = $3",
t.Title, t.Done, t.ID)
return err
}
The payoff shows up in tests: the business rule runs against an in-memory adapter satisfying the same port — no database, no network, microseconds:
// internal/task/service_test.go
package task_test
import (
"context"
"testing"
"github.com/acme/taskd/internal/task"
)
type memStore struct{ tasks map[int]task.Task }
func (m *memStore) Save(_ context.Context, t task.Task) error {
m.tasks[t.ID] = t
return nil
}
func (m *memStore) ByID(_ context.Context, id int) (task.Task, error) {
t, ok := m.tasks[id]
if !ok {
return task.Task{}, task.ErrNotFound
}
return t, nil
}
type recordingNotifier struct{ called int }
func (r *recordingNotifier) TaskCompleted(task.Task) error { r.called++; return nil }
func TestCompleteNotifiesTeam(t *testing.T) {
store := &memStore{tasks: map[int]task.Task{1: {ID: 1, Title: "Check on-call"}}}
notify := &recordingNotifier{}
svc := task.NewService(store, notify)
if err := svc.Complete(context.Background(), 1); err != nil {
t.Fatalf("Complete: %v", err)
}
if notify.called != 1 {
t.Fatalf("notifier called %d times, expected 1", notify.called)
}
}
// Terminal: go test ./internal/task/ -run Complete -v
// → === RUN TestCompleteNotifiesTeam
// → --- PASS: TestCompleteNotifiesTeam (0.00s)
// → PASS
An honest frame: ports & adapters pay off where business rules exist that are independent of the storage medium. For pure CRUD endpoints without a rulebook, a thin handler over database/sql is legitimate everyday work — any architecture that forces interfaces there produces typing effort with no yield. Apply the pattern when a second adapter (tests count!) or a second driver is foreseeable.
⚠ Common mistake: defining the interface at the adapter instead of the consumer — putting
type Store interfaceinto thepostgrespackage and letting the domain import it. That flips the dependency direction: the domain hangs off the database package, Postgres types leak into the business logic, and the unit test suddenly needs a DB driver just to construct the service. Interfaces belong to the code that calls them — in the domain, with domain types and domain errors. The adapter imports the domain, never the reverse.
Check: In which package do you define the Store port that task.Service needs for persistence?
Answer: In the task package — the domain describes what it needs; the adapter satisfies it implicitly
The port belongs to the domain because it speaks the domain's language: domain types, domain errors, no trace of sql.Row. That way the adapter imports the domain and not the reverse — the dependency direction of the hexagonal architecture emerges simply from WHERE the interface lives. A central interfaces package would additionally couple everything to everything, exactly like the models package of lesson 52.
Takeaways:
sql.ErrNoRows becomes task.ErrNotFound) — the domain stays free of driver vocabulary.After lesson 53 the service knows only ports. But somebody has to assemble the real object graph: the service needs the Postgres store and the mailer, the store needs the sql.DB, the handler needs the service, the server needs the handler. In Go, the answer to "how do we inject this?" is first delightfully unspectacular: as constructor parameters, assembled in main. This constructor injection is the dominant pattern in the Go ecosystem — and for the vast majority of projects the only one ever needed.
Why: the object graph lives in exactly one place, is ordinary Go code, is checked at compile time, and can be rebuilt line by line with fakes in tests. Frameworks like github.com/google/wire (compile-time code generation) or go.uber.org/fx (runtime DI with lifecycle) buy convenience for large graphs — both with honest trade-offs we'll weigh in a moment.
DI is a pattern, not a framework
The rule: dependencies travel as parameters into the constructor; nobody forwards them internally via global variables. main knows everything, nobody else knows main. This one-way street makes dependencies visible: if you spot a *sql.DB in the constructor of Service, you know immediately that business logic and database are coupled — lesson 53 holds the remedy.
The hand wiring for the task service — readable, testable, not a line of magic:
// cmd/taskd/main.go
package main
import (
"database/sql"
"log"
"net/http"
"time"
"github.com/acme/taskd/internal/adapters/mailer"
"github.com/acme/taskd/internal/adapters/postgres"
"github.com/acme/taskd/internal/api"
"github.com/acme/taskd/internal/task"
)
func main() {
db, err := sql.Open("postgres", mustEnv("DATABASE_URL"))
if err != nil {
log.Fatalf("db: %v", err)
}
defer db.Close()
// The object graph: adapters satisfy ports (lesson 53),
// every constructor takes only what it really needs.
store := postgres.NewStore(db)
notifier := mailer.New(mustEnv("SMTP_ADDR"))
svc := task.NewService(store, notifier)
srv := &http.Server{
Addr: ":8080",
Handler: api.NewHandler(svc),
ReadHeaderTimeout: 5 * time.Second, // slowloris protection (module 10)
}
log.Fatal(srv.ListenAndServe())
}
// Terminal: go run ./cmd/taskd
// → 2026/11/05 21:40:01 taskd listening on :8080
//
// And in tests the same graph is built with fakes —
// line by line, without a container:
// svc := task.NewService(&fakeStore{}, &fakeNotifier{})
// → (the service runs entirely without a database)
The point is not elegance but edges: every arrow in the graph is a line of readable Go code checked by the compiler.
When the graph grows to two dozen components, hand wiring becomes tedious and changes in five places at every refactor. That is what github.com/google/wire was built for: you describe provider sets, and the wire CLI generates the wire_gen.go source — exactly the code you would otherwise have written by hand. Important and version-honest: Google archived the project in August 2025 (last release v0.7.0); it is no longer developed. The generated code is ordinary Go and keeps running indefinitely — but a new project should know that the tool itself will not move.
//go:build wireinject
// +build wireinject
// wire.go — read only by the wire tool, never compiled
package main
import (
"github.com/google/wire"
"github.com/acme/taskd/internal/adapters/mailer"
"github.com/acme/taskd/internal/adapters/postgres"
"github.com/acme/taskd/internal/api"
"github.com/acme/taskd/internal/task"
)
var providers = wire.NewSet(
postgres.NewStore,
mailer.New,
task.NewService,
api.NewHandler,
)
func initHandler() (*api.Handler, error) {
wire.Build(providers)
return nil, nil // placeholder — wire replaces this function entirely
}
// Terminal: wire
// → wire: github.com/acme/taskd/cmd/taskd: wrote /path/to/wire_gen.go
// → (wire_gen.go contains the hand wiring from above, as normal Go code)
The escape hatch "if wire is discontinued, delete wire.go and keep wire_gen.go" is real — many teams have done exactly that.
The contrarian approach is go.uber.org/fx: an actively maintained framework (built on Uber's own dig container) that resolves dependencies at runtime via reflection and splits processes into modular providers, including lifecycle hooks (OnStart, OnStop) for cleanly starting and stopping background work. The price: runtime indirection and errors the container reports only at startup, where hand-written code would have caught them in the compiler.
// cmd/taskd-fx/main.go — the same application as an fx app
package main
import (
"go.uber.org/fx"
"github.com/acme/taskd/internal/adapters/mailer"
"github.com/acme/taskd/internal/adapters/postgres"
"github.com/acme/taskd/internal/api"
)
func main() {
fx.New(
fx.Provide(
mustDB,
postgres.NewStore,
mailer.New,
task.NewService,
api.NewHandler,
),
fx.Invoke(api.Serve),
).Run()
}
// Terminal: go run ./cmd/taskd-fx
// → [Fx] PROVIDE *sql.DB := main.mustDB()
// → [Fx] PROVIDE *postgres.Store := postgres.NewStore()
// → [Fx] INVOKE api.Serve()
// → [Fx] RUNNING
The rule of thumb that keeps both frameworks fairly judged: hand wiring first — it rarely becomes a problem before the project is big. Wire pays off for large, stable graphs whose wiring you want checked in as code (despite the archive, the file stays valid). Fx pays off when modular processes with lifecycle management are the goal anyway — say, on microservice platforms already committed to Uber's toolbox. A DI framework as the default starting point is not an accepted Go style, but a cost-benefit decision.
⚠ Common mistake: faking DI with package-level singletons — a
package storewithvar Default *Storeplusstore.Init(dsn)inmain, after which any package anywhere callsstore.Default. It looks like convenience and is paid for in testability: dependencies have vanished from the signatures (nothing reveals anymore who uses the store), tests need the global init in exactly the right order, and two test cases in one run compete for the same global state. Constructor injection was the better answer all along: dependency as a parameter, state instantiated per test, no hidden edges in the graph.
Check: What does github.com/google/wire concretely produce in a wire run?
Answer: A Go source file (wire_gen.go) with the fully spelled-out constructor wiring, built like any other code
Wire is code generation, not a runtime framework: the wire tool writes wire_gen.go with ordinary Go code — from that point the project runs without wire at all. The reflection container at runtime is Fx (built on its base dig), and that is precisely how the two approaches differ: compile-time error checking and a readable source file versus runtime flexibility and lifecycle management.
Takeaways:
main — ordinary code checked at compile time.github.com/google/wire generates the wiring as a source file (wire_gen.go) but has been archived since August 2025 (v0.7.0) — the generated code stays valid, the tool is not developed further.go.uber.org/fx resolves at runtime via reflection and ships lifecycle hooks — maintained, but with indirection and startup-time errors instead of compile-time guarantees.The team starts the next project, and the first pull-request debate is not about code but folders: do we need pkg/? Are these microservices already? Should we build multi-module from day one? Instead of leaving this to debates of faith, here is a catalogue from small to large — with an honest note on where the steps end.
Level 1 — the single-package tool: a CLI script is package main in one folder. Done. A cmd/ structure for two files is ceremony, not design.
Level 2 — the flat standard (the answer to most questions): one module, cmd/ with one folder per binary, internal/ for the rest, packages cut along the domain (lesson 52), ports and adapters where business rules deserve them (lesson 53). This anatomy carries services into six-digit line counts.
Bounded contexts are package boundaries
The domain question from the Domain-Driven Design series — where does a bounded context end? — translates in Go into a package question: internal/task and internal/reporting are separate contexts when task imports nothing from reporting (and vice versa). The compiler knows no bounded contexts, but it knows imports — so it enforces the separation once you codify it as an import ban backed by a small architecture definition.
Level 3 — the modular monolith in full form:
// taskd/ — one binary, domain-cut packages
// taskd/
// ├── cmd/taskd/main.go // the one entry point
// ├── internal/
// │ ├── task/ // context "tasks": domain + ports
// │ │ ├── domain.go
// │ │ └── service_test.go
// │ ├── reporting/ // context "reports"
// │ │ └── service.go
// │ ├── adapters/
// │ │ ├── postgres/ // satisfy the ports from internal/task
// │ │ └── mailer/
// │ └── api/ // HTTP adapter (module 10)
// ├── go.mod
// └── go.sum
// Terminal: go list ./... — make the package structure visible
// $ go list ./...
// → github.com/acme/taskd/cmd/taskd
// → github.com/acme/taskd/internal/adapters/mailer
// → github.com/acme/taskd/internal/adapters/postgres
// → github.com/acme/taskd/internal/api
// → github.com/acme/taskd/internal/reporting
// → github.com/acme/taskd/internal/task
Level 4 — the multi-module monorepo: when parts of the code get independent release cycles or their own consumers (say, a client library imported by other teams), they get their own go.mod. A workspace connects them locally:
// repo/ — two modules, one go.work (workspaces since Go 1.18)
// repo/
// ├── go.work
// ├── taskd/ // go.mod: module github.com/acme/taskd
// └── taskctl/ // go.mod: module github.com/acme/taskctl
// go.work
go 1.25
use (
./taskd
./taskctl
)
// Terminal: build at the workspace root — taskctl uses taskd locally
// from the checkout, without any replace lines in go.mod
// $ cd repo && go build ./...
// → (no output — both modules build from local sources)
Level 5 — microservices: separate deployments, separate repos or modules, communication over the network. This level is an organizational and operational decision, not an architectural merit: it pays on team boundaries (who deploys what, when, independently), not on line count. The price is real — network failures become the norm, contracts must be versioned, distributed tracing becomes baseline equipment (module 13). And the split direction follows bounded contexts vertically (tasks/reports), never horizontally by layer ("one service just for the database") — otherwise you build a distributed monolith: yesterday's coupling, now over the network.
Where does the widely copied repo structure with pkg/, apis/, deployments/ come from? It goes back to the popular golang-standards/project-layout repo — a community collection, not an official Go recommendation. pkg/ makes sense only when foreign projects are actually meant to import code from that path; empty directories as articles of faith just add navigation noise.
⚠ Common mistake: setting up a new project as a microservice federation right away because "scalability" is in the room — three services, one gateway, one message queue, and all three deployment pipelines hammering the same Postgres instance. The result is the distributed monolith: the coupling of a monolith plus network latency, mandatory distributed tracing and versioning overhead on top, without a single one of the benefits. The sovereign path is level 3: a modular monolith with cleanly cut contexts — when a genuine reason for extraction appears later (own scaling, own team, own release cycle), you lift out exactly that context, and the package boundaries of lessons 52 and 53 are already the service boundaries.
Check: When is a separate go.mod — a distinct module — the right choice inside a monorepo?
Answer: When the code is imported from outside the monorepo and needs an independent release cycle
A separate module is a version and ownership boundary, not a line-count boundary: it pays off when consumers outside import the module and it must be versioned stably (or its dependencies deliberately frozen). Within one module, packages do the structural work — and go.work (since Go 1.18) connects several modules in the monorepo without replace tricks, without decoupling them prematurely.
The foundation now stands: projects that grow with the team instead of tripping over their folder skeleton. Module 12 builds the framework world on top — by then you know why the standard-library route of module 10 stays attractive and where a framework genuinely pays off.
Weekly check: do you own these points?
go.sum is not a lockfile?internal/ as a compiler-enforced boundary?Takeaways:
go.mod declares, MVS picks the highest required version, go.sum seals integrity, the proxy has delivered reproducibly since Go 1.13.internal/ enforces them by compiler, interfaces belong to the consumer, cycles break at the domain.Course navigation: ← Module 10 · All 20 modules · Module 12 →