What is a domain-oriented Go project structure for a monolith?

A domain-oriented layout puts the whole service in one Go module with a single go.mod at the repository root. Nearly all code lives under internal/, split into packages named after business domains. Each binary gets a thin entrypoint under cmd/. For a service that ships an API server, a background worker and a migration tool, the tree looks like this:

  • go.mod
  • cmd/
    • api/main.go
    • worker/main.go
    • migrate/main.go
  • internal/
    • accounts/
    • billing/
    • inventory/
    • platform/ (database, logging, config)

The internal/ directory carries a rule the Go toolchain enforces. A package under internal/ can be imported only by code rooted at the directory that contains internal/. With internal/ at the module root, every package in the module can use internal/billing. Any other module that tries to import it fails to build. Your domain packages stay private implementation, so you can rename functions or split packages without breaking outside consumers.

Name packages after what they provide. The call billing.Invoice reads naturally and tells a reader where invoice logic lives. Packages called util, common or helpers describe nothing, so unrelated code collects in them. They also tend to end up importing half the codebase, which makes import cycles more likely.

This layout suits teams that run one large deployable service that several engineers or squads change at the same time. Domain packages give each group a clear area of ownership. The single module keeps versioning and builds simple.

// cmd/api/main.go: a thin entrypoint. It wires domain packages together
// and starts the server. Business logic stays in internal/.
package main

import (
	"context"
	"errors"
	"log"
	"net/http"
	"os"
	"os/signal"

	// Importable here because cmd/ shares the module root with internal/.
	// Another module importing these paths fails to build.
	"example.com/shop/internal/accounts"
	"example.com/shop/internal/billing"
	"example.com/shop/internal/platform"
)

func main() {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	// Shared infrastructure (config, DB) comes from platform, not a util package.
	cfg := platform.MustLoadConfig()
	db := platform.MustOpenDB(ctx, cfg.DatabaseURL)

	// Each domain registers its own routes. main only composes them.
	mux := http.NewServeMux()
	accounts.NewHandler(accounts.NewService(db)).Register(mux)
	billing.NewHandler(billing.NewService(db)).Register(mux)

	srv := &http.Server{Addr: cfg.HTTPAddr, Handler: mux}
	go func() { <-ctx.Done(); _ = srv.Shutdown(context.Background()) }()

	if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
		log.Fatal(err)
	}
}

A thin cmd/api entrypoint (Go source) that only loads config and wires the accounts and billing domain packages from internal/ into an HTTP server. The internal package functions shown are placeholders for the project's own code, and cmd/worker and cmd/migrate would follow the same pattern.

Why use one Go module instead of several for a monolith?

A single go.mod at the repository root is the right default. A change that renames a type in billing and updates its callers in orders and the HTTP layer lands in one commit, and it either compiles everywhere or nowhere. There is one dependency graph and one go.sum, so go build ./... and go test ./... cover the whole service, and CI needs one pipeline and one module cache.

Splitting one repository into several modules turns internal calls into versioned dependencies. Each module needs its own tags, prefixed with its subdirectory path. Local development then needs replace directives or a go.work file so that modules can see each other's uncommitted changes. If someone forgets to remove a replace, or tags modules in the wrong order, the build works on one laptop and fails in CI. For code that always ships together, that coordination costs effort and returns nothing.

Concern One module Several modules in one repo
Cross-domain change One atomic commit Tag, bump, and update in order
Dependency versions One shared set Per module, can drift
Local development Works by default Needs replace or go.work
CI One build and test run One per module, plus ordering

The single module has real costs. Go picks one version of each dependency for every package in the module. If one domain needs a newer major release or pins a conflicting version, every binary in the module gets that choice. Upgrades happen all at once.

Code under internal/ cannot be imported from other repositories. To share it, you have to extract it into its own module and version it, and that is ongoing maintenance work.

Multiple modules are justified when code has external consumers with their own release cadence, such as a published client library. They are also justified when one component has a dependency conflict that needs to be isolated from the rest.

How do you organize domain packages and control dependency direction?

Give each business capability its own package under internal/, such as internal/orders or internal/billing. That package owns its types, its rules and its persistence code. A reader looking for how refunds work should find the whole answer in one place. They should not have to piece it together from models/, services/ and repositories/ directories.

Dependencies should point inward. Domain packages never import HTTP or gRPC packages. Transport depends on the domain, and the domain does not depend on transport.

Domains should also avoid importing each other freely. When orders needs to charge a customer, it can declare a small interface such as Charger, with a single Charge method. orders declares only the methods it actually calls. billing.Service satisfies that interface without ever knowing it exists, and main connects the two.

Treat Go's ban on import cycles as feedback on your design. If orders and billing need each other, the boundary between them is probably wrong. Moving the shared types into a common or shared package hides the problem and gives you a new package that everything depends on. Merge the two packages, or extract the concept they both depend on into its own domain.

Don't add interfaces speculatively. Use concrete types until you have a second implementation or a real need for a test seam.

Boundaries chosen early are often wrong. A few larger packages that you split later usually cost less than many tiny ones you have to merge back together.

Clean packages do not guarantee loose coupling. If two domains join across each other's tables or share transactions, they are still tightly coupled, however tidy the import graph looks.

// internal/orders/orders.go
package orders

import "context"

// Charger is declared by the consumer and lists only the method orders calls.
type Charger interface {
	Charge(ctx context.Context, customerID string, amountCents int64) error
}

type Service struct{ charger Charger }

func NewService(c Charger) *Service { return &Service{charger: c} }

func (s *Service) Place(ctx context.Context, customerID string, totalCents int64) error {
	// Order rules and order persistence live here. Billing is reached only through Charger.
	return s.charger.Charge(ctx, customerID, totalCents)
}

// internal/billing/billing.go
package billing

import "context"

// Service never imports orders and does not know Charger exists.
type Service struct{}

func (s *Service) Charge(ctx context.Context, customerID string, amountCents int64) error {
	// Talk to the payment provider and write to billing's own tables only.
	return nil
}

// cmd/shop/main.go: the only place that imports both domains and wires them together.
//
//	svc := orders.NewService(&billing.Service{})

The orders package declares a one-method Charger interface for what it needs. billing.Service satisfies it implicitly without importing orders, and main wires the two together.

How should main.go, cross-cutting concerns, transport and generated code be wired?

cmd/api/main.go should do four things in order: parse configuration, construct dependencies, wire them together, and start servers. If it contains business logic, that logic cannot be reused or tested without starting the process. A cmd/worker/main.go follows the same pattern. It builds the same domain services from the same packages, but it starts a queue consumer instead of an HTTP listener. The two binaries differ only in their entry points.

Cross-cutting concerns belong in small packages such as internal/config, internal/logging, internal/database and internal/telemetry. Each one returns a value, such as a *slog.Logger, a *sql.DB or a config struct, and main passes that value to whatever needs it. Avoid package-level globals and init() side effects. They hide dependencies, make ordering unpredictable, and stop tests from running in parallel with different settings.

Handlers can live with each domain (internal/billing/httpapi) or with each API surface (internal/transport/public, internal/transport/admin). Group them per domain when each domain owns its endpoints. Group them per surface when one API combines several domains under shared authentication and versioning rules. Repositories usually stay inside their domain, because the storage model is part of what that domain owns.

Put generated protobuf or sqlc output in its own directory, for example internal/billing/store/gen, so that regeneration can safely wipe that directory. Handwritten adapters that wrap the generated code go in a sibling package.

Explicit wiring makes main.go long, sometimes hundreds of lines. Dependency-injection frameworks shorten that file, but they move the dependency graph somewhere harder to read. A plain nil pointer in a constructor is easier to debug than a resolution failure reported by a framework.

// cmd/api/main.go: parse config, build dependencies, wire them, start the server.
package main

import (
	"context"; "errors"; "fmt"; "net/http"; "os"; "os/signal"

	"example.com/shop/internal/billing"
	"example.com/shop/internal/billing/httpapi"
	"example.com/shop/internal/billing/store" // handwritten adapter over store/gen
	"example.com/shop/internal/config"
	"example.com/shop/internal/database"
	"example.com/shop/internal/logging"
)

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, "api:", err)
		os.Exit(1)
	}
}

func run() error {
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()

	cfg, err := config.Load(os.Getenv) // 1. config is a value, not a global
	if err != nil { return fmt.Errorf("load config: %w", err) }
	logger := logging.New(cfg.LogLevel) // returns *slog.Logger
	db, err := database.Open(ctx, cfg.DatabaseURL) // returns *sql.DB
	if err != nil { return fmt.Errorf("open database: %w", err) }
	defer db.Close()

	// 2-3. Explicit wiring. cmd/worker repeats these lines exactly.
	svc := billing.NewService(store.New(db), logger)

	// 4. Only this step differs: cmd/worker starts a queue consumer here instead.
	srv := &http.Server{Addr: cfg.HTTPAddr, Handler: httpapi.NewHandler(svc, logger)}
	go func() { <-ctx.Done(); _ = srv.Shutdown(context.Background()) }()
	if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { return err }
	return nil
}

A thin Go cmd/api/main.go that loads config, builds the logger, database and billing service explicitly, and starts an HTTP server; a cmd/worker binary would reuse every line except the final server step.

How should tests be structured in a large Go monolith?

Unit tests belong next to the code they exercise. internal/billing/invoice_test.go sits beside invoice.go, compiles only when that package is tested, and fails with a path that names the owning domain. When CI reports a failure in internal/billing, nobody has to work out which team or which part of the codebase to look at.

Use two package names inside the same directory. Files declared as package billing can test unexported helpers. Files declared as package billing_test see only the exported API, the same view other domains get. Prefer the _test form for behavior tests. If a black-box test is awkward to write, the public surface is probably too wide or too leaky, and that is worth knowing before another domain starts depending on it.

Shared fixtures, such as builders for valid domain objects, fake clocks and in-memory repositories, go in a package like internal/testutil or a per-domain internal/billing/billingtest. Because they live under internal/, nothing outside the module can import them. Import them only from test files so they stay out of production binaries.

Integration tests that need a real database or network should not run on a plain go test ./.... Gate them with a //go:build integration constraint and run them with go test -tags integration ./..., or keep them in a separate top-level directory that CI targets explicitly. The default command then checks only fast, hermetic tests, so engineers run it on every change instead of leaving it for CI.

# Layout (one domain shown):
#   internal/billing/invoice.go                 package billing
#   internal/billing/invoice_internal_test.go   package billing       (white-box: unexported helpers)
#   internal/billing/invoice_test.go            package billing_test  (black-box: exported API only)
#   internal/billing/billingtest/builders.go    shared fixtures, imported only from _test.go files
#   internal/billing/store_integration_test.go  first line: //go:build integration

# Fast local loop: compiles and runs only hermetic tests.
# Files with the integration build constraint are excluded.
go test ./...

# Scope to the domain you changed for even faster feedback.
go test ./internal/billing/...

# CI or pre-merge: include the tagged tests that need a real database.
# The DSN is a placeholder; tests read it from the environment.
BILLING_TEST_DSN='postgres://test:test@localhost:5432/billing_test?sslmode=disable' \
  go test -tags integration ./internal/billing/...

# Confirm which files each mode compiles (helps catch a missing constraint).
go list -f '{{.XTestGoFiles}}' ./internal/billing
go list -tags integration -f '{{.XTestGoFiles}}' ./internal/billing

A per-domain test layout and the go test commands that keep the default run fast while integration tests run only when the integration build tag is set.

What are the alternatives, and when should you avoid this layout?

The domain layout is one of four common choices. Each trades early convenience against long-term cost differently.

Layout Change locality Onboarding Import-cycle risk Refactoring cost
Domain packages under internal/ High: a feature change stays in one package Moderate: you must learn the domain map first Low, if dependency direction is enforced Low to moderate
By technical role (controllers/, models/, services/) Low: one feature touches every layer Easy: familiar from other frameworks High: models and services start importing each other High, because features are spread across layers
Cloned community template Varies with the template Misleading: directories exist before the code needs them Moderate Moderate: empty layers keep growing
Flat single package High at first Easiest None, since there are no package boundaries Rises sharply once the package passes a few thousand lines

Skip the domain layout when the domains are still unclear. In a young service you will often guess the boundaries wrong, and moving code between packages costs more than splitting one package later. A flat main package also suits short-lived tools and one-off migrations. Code that genuinely has to be shared across repositories cannot live under internal/, because Go blocks those imports. Give it its own module with a deliberately small public API.

Over time, the role-based layout's cost per feature keeps rising: every change crosses more layers, and cycles force awkward interface packages. The domain layout costs more up front. After that, the cost per change stays roughly flat because each domain can be changed or extracted without touching the others.

How do you enforce boundaries and migrate an existing monolith incrementally?

Write the rules down, then check them

Record allowed import directions in a short file at the repository root, for example: internal/billing may import internal/platform/... but not internal/orders. A CI script can run go list -f '{{.ImportPath}} {{join .Imports " "}}' ./..., compare each edge against the file, and fail the build on any violation. Pair this with per-domain ownership entries (such as a CODEOWNERS file), so a change to internal/orders/ needs review from the people who own that domain.

Unchecked rules erode within a few sprints, because one urgent fix that crosses a boundary becomes the precedent for the next. Overly strict rules fail differently. When a legitimate dependency is blocked, engineers copy types between domains or move them into a common package that soon holds everything. Treat a rejected import as a signal to review the rule, not only the change.

Migrate in steps that keep the build green

First, move existing packages under internal/ without changing their contents. This step is mechanical and it immediately stops new outside importers. Then extract one domain at a time. For each domain, move its types and logic, update the callers, and merge before you start the next one.

The costs are real. Moves produce large diffs, conflict with in-flight branches, and hide history in git blame unless you list the move commits in an ignore-revs file. The bigger risk is a migration that stalls halfway and leaves two conventions in the codebase indefinitely. Agree on the target layout and the order of domains as a team, announce each move ahead of time, and keep each step small enough to merge in a day.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to go project structure monolith, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.