This resume is also available in English.

1. Go foundations1 / 4 · All columns

Columns › 1. Go foundations › Part 1

Go Project Layout and Go Modules

工程結構與 Go Modules

Starting from go mod init, this article explains how modules, packages and directories relate, how to lay out cmd and internal, how Go picks dependency versions, and when a multi-service repository should use one module or a go.work workspace.

  • Go
  • Modules
  • Project Layout
In this article
  1. What this article solves
  2. Step 1: Create a module and understand go.mod
  3. Step 2: A package is a directory
  4. Step 3: Lay out the skeleton with cmd and internal
  5. Step 4: Let the entry point know its own version
  6. Step 5: Add dependencies and understand minimal version selection
  7. Step 6: replace, vendor and tool dependencies
  8. Step 7: Several services in one repository
  9. Common pitfalls
  10. Key takeaways
  11. Next

This is the first article in the "Building Microservices with Go" series. The series has 34 articles in eight parts, following the order service of an online shop throughout. Read them in order; each one picks up where the previous one left off:

  1. Part 1: Go foundations (articles 1–4): project layout, error handling, concurrency and context, to get the language fundamentals solid first.
  2. Part 2: Writing a service (articles 5–8): HTTP middleware, layering and dependency injection, database transactions and testing, to build a clearly structured, testable monolithic service.
  3. Part 3: Splitting into microservices (articles 9–12): when to split, splitting it into api-gateway, order, payment and inventory, and dealing with gRPC, the API gateway and service discovery.
  4. Part 4: Reliability (articles 13–16): timeouts, retries, circuit breakers, idempotency, message queues and distributed transactions.
  5. Part 5: Going live and operations (articles 17–20): observability, graceful shutdown, container and Kubernetes deployment of a single service, and performance tuning.
  6. Part 6: Deployment in practice (articles 21–23): deploying the whole system with Docker Compose and Kubernetes, then looking back at how the system evolves step by step from 100K to 1M to 10M scale.
  7. Part 7: Pitfalls in practice (articles 24–26): common problems with concurrency, payments and handling money.
  8. Part 8: Security and working with AI (articles 27–33): security, and using Claude Code and AI workflows for development, review, deployment, troubleshooting, debugging and security checks, finishing with an MCP server in Go that connects to OpenProject.

The last article is a bonus (article 34) on how to get search engines and AI to find your services and documentation once they are live. The code uses the same repository from start to finish.

What this article solves

What trips up people new to Go is usually not the syntax but "where do the files go": how many packages can one directory hold? Should main live at the root or under cmd/? What exactly is the magic of internal? Why does go.sum keep growing? After adding a dependency, which version actually ends up in the binary?

These questions barely matter for a single small tool, but once the system grows into several services (which is exactly what the rest of this series does), the directory and module boundaries you set at the start directly affect which code other services can import, how many places a dependency upgrade touches, how CI is split and how Docker images are built. The cost of changing the structure grows linearly, or even faster, with the amount of code, so it is worth laying solid foundations in the very first article.

This article builds the skeleton of the online shop example.com/shop from scratch, starting with just the order service, and adds packages, command-line entry points, internal packages and external dependencies step by step, before finishing with the trade-offs of a multi-service repository. By the end you should be able to answer:

  • How modules, packages and directories map onto one another.
  • What problems cmd/, internal/ and pkg/ each solve, and when you don't need them.
  • How Go picks dependency versions with "minimal version selection", and what go.sum protects.
  • With several services in one repository, how a single module differs from multiple modules plus go.work.

Step 1: Create a module and understand go.mod

Go Modules is Go's official unit of dependency management and building. A "module" is a directory tree with a go.mod file at its root, which declares the tree's "module path" and which other modules it depends on. Start with an empty project:

mkdir shop && cd shop
go mod init example.com/shop

The generated go.mod is short:

module example.com/shop

go 1.24

There are two things to understand here.

The module path is the prefix of import paths

The string declared on the module line becomes the prefix of the import path of every package in the module. A package in the internal/order directory will have the import path example.com/shop/internal/order. The path does not have to be reachable on the network, but if other people are to fetch the module with go get, it must correspond to a location the source can be downloaded from, such as github.com/account/repository. A common approach: modules that will be public use their real code-hosting URL; modules used only inside the company or within a single repository can use a domain you control, so you don't have to change every import path if the code moves later.

The go directive is the language version, not a comment

The go 1.24 line is not decoration. Since Go 1.21 it is the "minimum required version": an older toolchain refuses to build (or downloads a newer toolchain automatically, depending on the toolchain setting). More importantly, it determines the language semantics. For example, from Go 1.22 the for loop variable became "a new variable per iteration", and that behaviour only applies when go.mod declares 1.22 or later. The same code in a go 1.21 module and a go 1.22 module may capture different loop variables in closures. So when you bump this line, test it as a language upgrade rather than casually changing a number.

Tip: The toolchain directive (for example toolchain go1.24.3) says "which toolchain is recommended for building", while the go directive says "the minimum language version". When a team wants CI and local machines to match, a common practice is to write both and set GOTOOLCHAIN=local in CI so that nothing is quietly downloaded during the build.

Step 2: A package is a directory

Go's rule is very simple: one directory is one package (the external _test package used for tests is the only exception). All .go files in the same directory must declare the same package name, and they can see all of each other's identifiers directly, without imports. Different directories are different packages; they must be referenced through an import path and only see names that start with a capital letter (exported names).

This leads to a few practical conclusions:

ConceptExplanationPractical impact
Only two levels of visibilityA capital letter exports a name; lower case is package-onlyThere is no protected and no "visible within the module"; you control it by splitting directories
The package name is the caller's prefixCallers write order.New(), not New()Names should be short nouns; avoid repetition such as order.OrderService
No import cyclesIf A imports B, B cannot import APackage dependencies must form a directed acyclic graph, which forces you to think through layering
Directory name need not equal package nameBut by convention they should matchA mismatch makes readers open the file every time to check

A small example for comparison. Suppose the internal/order directory has two files; they belong to the same package and can use each other's lower-case identifiers, while callers only see names starting with a capital letter:

// Snippet: internal/order/order.go
package order

import "errors"

// Status is the order status; it starts with a capital letter, so other packages can use order.Status.
type Status string

const (
	StatusPending   Status = "pending"
	StatusPaid      Status = "paid"
	StatusCancelled Status = "cancelled"
)

// Item is one line item in an order; amounts are always int64 in minor units (cents) to avoid floating-point errors.
type Item struct {
	SKU   string
	Qty   int
	Price int64 // unit price, in minor units
}

// Order is exported, and so are its fields; callers write order.Order.
type Order struct {
	ID     string
	UserID string
	Items  []Item
	Total  int64 // in minor units
	Status Status
}

// New is the constructor; callers write order.New(...), which reads as "new order".
func New(id, userID string) *Order {
	return &Order{ID: id, UserID: userID, Status: StatusPending}
}

// AddItem calls the lower-case validQty; it is defined in another file of the same package and is invisible outside it.
func (o *Order) AddItem(it Item) error {
	if !validQty(it.Qty) {
		return errors.New("order: quantity must be positive")
	}
	o.Items = append(o.Items, it)
	o.Total += it.Price * int64(it.Qty)
	return nil
}

Note the naming: callers write order.New and order.StatusPaid. The package name already provides the context, so the function does not need to be called NewOrder. A type Order with the same name as its package is one of the few acceptable repetitions, because it is the core of that package.

The most common package-naming mistake is using names like utils, common or helpers. They don't describe "what this package provides", so everything gets thrown into them; eventually almost every package imports them, any small change triggers a recompile of the whole project, and they even create pressure towards import cycles. A better approach is to name packages after the capability they provide: money (amount calculations), clock (a replaceable time source), retry (retry strategy). If you really can't think of a name, that usually means the code should stay in the package that uses it.

Another rule to know is the main package. Only a package that is package main and contains func main() can be built into an executable. The main package cannot be imported by other packages, so it should be as thin as possible: read configuration, wire up dependencies, start the server, and hand the real logic to other packages. This principle is expanded on later in “Layered Architecture and Dependency Injection in Go”.

Step 3: Lay out the skeleton with cmd and internal

With the idea that "a package is a directory", you can lay out the service's skeleton. Below is a common, but deliberately lean, structure:

shop/ go.mod: example.com/shop cmd/ one entry per service internal/ this module only api/proto/ inter-service APIs deploy/ compose, k8s order/main.go payment/ inventory/ api-gateway/ order/ handler.go: handlers service.go: business logic repository.go: data access payment/ inventory/ main only wires up, imports internal/order Start with just cmd/order and internal/order; the rest grows as the series goes on

Figure: each subdirectory under cmd is one executable; packages under internal can only be imported by this module.

shop/
├── go.mod                # module example.com/shop
├── go.sum
├── cmd/
│   ├── order/            # entry point of the order service (package main)
│   │   └── main.go
│   ├── payment/          # services split out later each get their own entry point too
│   ├── inventory/
│   └── api-gateway/
├── internal/
│   ├── order/            # the order domain: one package per domain
│   │   ├── handler.go    # HTTP handlers
│   │   ├── service.go    # business logic
│   │   └── repository.go # data access
│   ├── payment/
│   └── inventory/
├── api/proto/            # API definitions between services (used from the gRPC article on)
└── deploy/               # docker compose and k8s configuration

At first you only need cmd/order and internal/order. The other directories grow gradually later in the series; they are listed here so you can see the final shape.

cmd/: one subdirectory per executable

A repository often has more than one executable: one per service, and sometimes database migration tools or one-off data-fix programs. Put each in cmd/<name>/main.go, and go build ./cmd/order builds an executable called order (the executable name comes from the directory name). If the whole module will only ever have one executable, putting main.go straight in the root is perfectly fine; there is no need to force a cmd/ in just to "look professional".

internal/: a boundary guaranteed by the compiler

internal is the only directory name with semantics built into the Go toolchain: a package whose path contains internal can only be imported by packages under "the parent directory of internal". In the structure above, example.com/shop/internal/order can only be used by packages under example.com/shop/...; any other module that tries to import it fails to compile.

This guarantee is particularly valuable in a microservice architecture. What it blocks is "other modules"; within the same module, cmd/payment can technically still import internal/order. Services should communicate only through APIs (HTTP, gRPC, messages), not by importing each other's Go packages directly. Once the order service's data-access code is imported by the inventory service, the two services are coupled at the source-code level, and afterwards nobody dares change it. So internal/ guards the external boundary, while the boundary between services relies on convention and code review (you can also nest one more level with internal/order/internal/..., so the compiler only allows use from under internal/order).

Do you need pkg/?

Many template projects have a pkg/ directory for packages "intended for external use". It has no toolchain semantics at all; it is purely a convention. The practical advice: if you really do have a library to offer to other modules (such as a shared client SDK), put it in a clearly named top-level directory or a separate module; if you don't, you don't need pkg/. Put things in internal/ by default and move them out when there really are external users. That is much safer than the reverse, because "taking back something exported" breaks other people's code, while "making something internal public" does not.

Tip: Don't start by copying some "standard project layout" template and creating a dozen empty directories. The Go community consensus is that structure grows with need: start with go.mod and main.go, add internal/ when there are enough packages to need grouping, and add cmd/ when there is more than one executable.

Step 4: Let the entry point know its own version

In a multi-service environment, a very practical need is knowing which version is actually running in production. When something goes wrong, logs and monitoring must map back to a specific commit. Since Go 1.18 the toolchain automatically embeds the module version, the dependency list and version-control information (commit, time, whether there were uncommitted changes) into the binary, and the program can read them with runtime/debug.ReadBuildInfo, without injecting variables yourself via -ldflags.

Below is a complete entry point that prints its own build information and demonstrates the "main only wires things together" style:

package main

import (
	"flag"
	"fmt"
	"log/slog"
	"os"
	"runtime/debug"
)

// buildInfo extracts the module path, version and commit from the information embedded in the binary.
func buildInfo() (path, version, revision string) {
	info, ok := debug.ReadBuildInfo()
	if !ok {
		return "unknown", "unknown", "unknown"
	}
	path, version, revision = info.Main.Path, info.Main.Version, "unknown"
	for _, s := range info.Settings {
		if s.Key == "vcs.revision" {
			revision = s.Value
		}
	}
	return path, version, revision
}

func main() {
	showVersion := flag.Bool("version", false, "print the version and exit")
	addr := flag.String("addr", ":8080", "HTTP listen address")
	flag.Parse()

	path, version, revision := buildInfo()
	if *showVersion {
		fmt.Printf("%s %s (%s)\n", path, version, revision)
		return
	}

	logger := slog.New(slog.NewJSONHandler(os.Stdout, nil)).With(
		"service", "order",
		"version", version,
		"revision", revision,
	)
	logger.Info("starting", "addr", *addr)
	// The real server wiring is added in "net/http and Middleware in Go".
}

A few details:

  • info.Main.Version is usually (devel) or a pseudo-version derived from git tags when built locally with go build; when installed with go install module@v1.2.3 it is the release version.
  • vcs.revision, vcs.time and vcs.modified only exist when you build inside a version-control directory and haven't turned them off with -buildvcs=false. In a Docker multi-stage build that doesn't copy .git, these values are missing, which is a common reason for "why does production show unknown as the version".
  • Put the version in the shared slog attributes and every log line carries it; “Observability in Go: Logs, Metrics and Tracing” later reuses this approach.

You can also use go version -m ./order to see the dependency list embedded in any Go binary, which is very handy when investigating "which dependency versions does that production binary actually use".

Step 5: Add dependencies and understand minimal version selection

Next, add an external dependency. After importing an external package in your code, run:

go get example.com/some/lib@v1.4.0   # add or upgrade to a specific version
go mod tidy                           # add missing and remove unused dependencies
go list -m all                        # list every module version finally selected
go mod why -m example.com/some/lib    # find out why this module is needed

go.mod gains a require block, and go.sum records a hash of the contents of each module version.

What go.sum protects

go.sum is not a lock file; it is an integrity checksum file. Every time a module is downloaded, the toolchain compares hashes to make sure the source is exactly the same as when it was first added; by default it also checks with the public checksum database (sumdb) that the hash for that version has not been tampered with. So go.sum must be committed to version control. It is normal for it to grow, because it records module versions that may be used in the build graph; don't edit it by hand, let go mod tidy maintain it.

Minimal version selection (MVS)

Many languages' package managers pick the "latest" version within the acceptable range, but Go does the opposite: it picks the minimum version that satisfies all requirements. The algorithm works like this: starting from the main module, walk every require; for each module, take the highest version among all its requirements, and that is the version used. It never upgrades automatically just because upstream released a new version.

Main module A v1.0 B v2.3 needs ≥ v1.2 needs ≥ v1.4 C v1.2 C v1.4 C v1.7 released Selected: C v1.4, the highest requirement Nobody requires v1.7, so it is not auto-upgraded

Figure: the main module needs A and B, A requires C v1.2 and B requires C v1.4, so C v1.4 is selected; even though C v1.7 has been released, it is not chosen.

This design brings two benefits:

  1. Reproducible: as long as go.mod doesn't change, builds at any time on any machine get the same dependency versions, with no separate lock file needed.
  2. Upgrading is an explicit action: dependency versions only change when you run go get to upgrade, and the change shows up clearly in the go.mod diff, which makes it easy to review.

The cost is that you must upgrade proactively to get security fixes. A common practice is to run go list -m -u all periodically in CI to check for available upgrades, and to scan for known vulnerabilities with govulncheck (it only reports vulnerable functions your code actually calls, so it is far less noisy than simply matching versions).

Semantic versioning and /v2

Go requires modules to follow semantic versioning and encodes the "major version" in the import path: v0 and v1 share the same import path, while v2 and later must add /v2, /v3 to the end of the module path. In other words, example.com/lib and example.com/lib/v2 are two different modules as far as Go is concerned, and they can coexist in the same build. This lets large systems migrate major versions in batches rather than upgrading everything at once. When you publish your own library and need to make an incompatible change, change the module path according to this rule.

Step 6: replace, vendor and tool dependencies

Besides require, go.mod has a few other directives that are common in practice.

DirectivePurposeNotes
replaceSwap a module for a local path or another source, for example temporarily using a fork to fix a bugOnly applies in the main module and is ignored when others depend on you; remove it when done
excludeExclude a problematic versionRarely used; upgrading to the fixed version is usually more direct
retractThe module author declares that certain published versions should not be usedWritten in the author's own go.mod; users see a warning when upgrading
toolSince Go 1.24, record development tools (code generators, linters) as dependenciesAdd with go get -tool module-path, run with go tool name

Tool dependencies

Projects used to rely on a tools.go file plus a build tag to pin tools such as code generators in go.mod. Go 1.24 added the tool directive, so that trick is no longer needed:

go get -tool golang.org/x/tools/cmd/stringer
go tool stringer -type=Status ./internal/order

Tool versions are pinned along with go.mod, so team members and CI all use the same version, and you don't get "my local generator version is different, so the generated code keeps producing a diff". When generating code later in “gRPC and Protocol Buffers in Go”, you can manage the generators the same way.

The vendor directory

go mod vendor copies the source of every dependency into a vendor/ directory, which the build then uses directly. It suits situations where the build environment has no network access at all, or where company policy requires all third-party code to go through version-control review. The downsides are a larger repository and huge diffs when upgrading dependencies. Most teams simply cache dependencies with a module proxy (GOPROXY) instead and don't necessarily need vendor.

Tip: For private modules, set GOPRIVATE=example.com/shop/* so the toolchain skips the public proxy and checksum database for those paths and downloads directly from version control, which avoids sending internal module names to external services.

Step 7: Several services in one repository

The second half of the series has several services, order, payment, inventory and api-gateway, all in the same repository (a monorepo), so you have to decide how to split modules. There are two common approaches, and this series uses the first:

Approach 1: single module (this series) Approach 2: modules + go.work shop/go.mod (just one) cmd/order internal/order cmd/inventory internal/inventory cmd/payment internal/payment One set of dependency versions, one go test ./... for everything go.work (local development) order/go.mod own dependency versions inventory/go.mod own dependency versions platform/go.mod versioned independently CI sets GOWORK=off for one service

Figure: on the left, the whole repository has one go.mod; on the right, each service has its own go.mod, tied together with go.work for local development.

Approach 1: one module for the whole repository

One go.mod at the root (example.com/shop), with each service being cmd/<service>/ plus internal/<domain>/, which is the structure from Step 3.

  • Pros: the simplest. All services use the same set of dependency versions, shared code is imported directly without release version numbers, and one go test ./... runs everything.
  • Cons: when any service upgrades a dependency, every service upgrades with it; the dependency graph is the union of all services, so a large library used by one service appears in every service's go.sum (although it isn't compiled into binaries that don't use it).

Approach 2: one module per service, with go.work

Each service directory has its own go.mod, so it can upgrade dependencies and be tagged and released independently. Shared libraries are independent modules too. For local development, tie them together with a workspace, added in Go 1.18:

go work init ./order ./inventory ./platform

The generated go.work makes these modules use the source in the working directory directly when they reference each other locally, without publishing a version first or writing replace.

go 1.24

use (
	./inventory
	./order
	./platform
)

Note that go.work is a "development convenience", not a "release configuration": when CI builds a single service, a common practice is to set GOWORK=off to make sure that the service's own go.mod builds correctly; otherwise you can end up with "it builds locally, but fails when CI builds it on its own". Many teams therefore choose not to commit go.work to version control.

How to choose

SituationRecommendation
Few services, maintained by one team, same deployment cadenceA single module, the least hassle
Services maintained by different teams that need to set their own upgrade cadenceMultiple modules + go.work
You have an SDK or library to offer for external useMake that library its own module and tag versions properly
Not sureStart with a single module and use internal/ to guard the boundaries between services; splitting modules later just means moving go.mod, and import paths usually don't change

Whichever you choose, the principle that services "don't directly import each other's business code" stays the same. The only things that can be shared are genuinely generic, stable platform code (logging setup, tracing initialisation, health checks) and client code generated from API definitions.

Common pitfalls

  • Module path doesn't match the actual location: go.mod says github.com/a/b, but the code lives at github.com/a/c, so anyone running go get gets a "module declares its path as…" error. When renaming, update go.mod and every import together.
  • Treating go 1.xx as a comment you can change freely: it changes language semantics (such as the scope of loop variables). Run the full test suite after upgrading, especially where closures capture loop variables or goroutines are involved.
  • Editing go.sum by hand, or not committing it: the former makes verification fail; the latter strips integrity protection from other people's builds. Let go mod tidy maintain it, and commit it.
  • Forgetting to remove a replace pointing at a local path: it builds on your machine, but CI and your colleagues' machines can't find the path. When you need long-term joint local development, use an uncommitted go.work instead.
  • utils and common packages growing without limit: they become the centre of the dependency graph and defeat layering. Name packages by capability, or keep the code where it is used.
  • Services directly importing each other's packages outside internal: it saves effort in the short term, but in the long run the two services must change together and deploy together, which defeats the point of splitting them.
  • Not including .git in the Docker build: debug.ReadBuildInfo can't get the commit, so the production version can't be traced. You can fill it in at build time with -ldflags "-X main.revision=...", or keep the version-control information during the build stage.
  • Copying a large template from day one: a pile of empty directories only adds reading overhead. Structure should grow with the code, not be created first and then filled.

Key takeaways

  • One go.mod defines one module; the module path is the prefix of every package's import path, and the go directive sets the minimum version and the language semantics.
  • One directory is one package; visibility has only two levels (upper and lower case), and packages cannot import each other in a cycle, so splitting directories is splitting the architecture.
  • cmd/<name>/ holds the thin entry point of each executable, internal/ holds code that isn't exposed, with the boundary guaranteed by the compiler, and pkg/ is just a convention, not a requirement.
  • Use runtime/debug.ReadBuildInfo to read the embedded version and commit, and put them in the shared log attributes so the production version can be traced.
  • Go picks dependency versions with minimal version selection: it takes the highest among all requirements and doesn't chase the latest, so builds are reproducible and upgrades are explicit.
  • go.sum is an integrity check, not a lock file, and must be committed; major versions v2 and above go into the module path.
  • Pin development tools with Go 1.24's tool directive; set GOPRIVATE for private modules.
  • A multi-service repository can use a single module or multiple modules + go.work; when unsure, start with a single module and stick to "services don't directly import each other's business code".

Next

The skeleton is in place, but as soon as the program starts calling a database or other services, you run into "how to report a failure, how to tell what went wrong, and how not to leak internal details". The next article, “Error Handling in Go: Wrapping, Sentinels and Custom Types”, starts from the error interface and builds a consistent approach to error handling for the order service.