Go directory naming conventions and project layout: when should you use cmd, internal, and pkg?

June 16, 2025

โ€œgo directory naming convention?โ€ was my question in Cursor. One example had a single main.go. Another had two commands, a service directory, and both internal and pkg. Suppose a command-line tool and a web server both need to parse the same document. Where should the parser live? What changes if someone wants to import it into a third program?

What does a repository with a CLI, a server, and a library look like?

Imagine three users. One runs sqlcheck in a terminal to list the queries in a document. Another uploads the same document to a web server that remembers which files it has seen. The third writes reporting software and wants to call a Go function to get the query names. Here is one way to put all three in a repository. The community Standard Go Project Layout describes what it collects as โ€œa set of common historical and emerging project layout patterns in the Go ecosystem.โ€1

querykit/
โ”œโ”€โ”€ go.mod                        # Module path, minimum Go version, dependency requirements
โ”œโ”€โ”€ go.sum                        # Checksums recorded as needed for downloaded modules
โ”œโ”€โ”€ vendor/                       # Optional local copies of dependency packages
โ”œโ”€โ”€ cmd/
โ”‚   โ”œโ”€โ”€ sqlcheck/main.go          # Command-line interface (CLI): read a file, print the result
โ”‚   โ””โ”€โ”€ sqlserver/main.go         # Open the database, register routes, start the HTTP server
โ”œโ”€โ”€ internal/                     # Import restriction enforced by the go command
โ”‚   โ”œโ”€โ”€ handler/upload.go         # Read the upload and write the HTTP response
โ”‚   โ”œโ”€โ”€ service/import.go         # Decide when to parse, reuse a result, or save it
โ”‚   โ”œโ”€โ”€ service/import_test.go    # Exercise that rule with an in-memory store
โ”‚   โ”œโ”€โ”€ repository/query.go       # Read and write query records in the database
โ”‚   โ”œโ”€โ”€ repository/query_integration_test.go  # Check those operations against a test database
โ”‚   โ”œโ”€โ”€ model/query.go            # Types representing a query and its result
โ”‚   โ”œโ”€โ”€ query/parse.go            # Parser shared by the CLI and the server
โ”‚   โ”œโ”€โ”€ query/testdata/sample.yml # Sample input the parser tests can read
โ”‚   โ””โ”€โ”€ util/
โ”‚       โ”œโ”€โ”€ hash.go               # Compute a digest to recognize duplicate documents
โ”‚       โ”œโ”€โ”€ hash_test.go          # Same-package test can call an unexported helper
โ”‚       โ””โ”€โ”€ hash_api_test.go      # External test package exercises the exported function
โ”œโ”€โ”€ pkg/query/names.go            # Small public API for the reporting program
โ”œโ”€โ”€ api/openapi.yaml              # Upload endpoint, request format, and response fields
โ”œโ”€โ”€ web/                          # Browser assets and server-side templates
โ”œโ”€โ”€ configs/example.yaml          # Example settings for the port and database connection
โ”œโ”€โ”€ migrations/001_queries.sql    # Create the table, then evolve its schema in later migrations
โ”œโ”€โ”€ scripts/                      # Scripts for building, installing, or checking the project
โ”œโ”€โ”€ build/                        # Packaging files and build configuration
โ”œโ”€โ”€ deployments/                  # Configuration for deploying the service
โ”œโ”€โ”€ test/e2e/upload_test.go       # End-to-end test that exercises a running service
โ”œโ”€โ”€ examples/                     # Small programs showing how to call the library
โ””โ”€โ”€ Makefile                      # Named tasks for building, testing, and releasing

The quickest way to read the tree is to ask what happens if you rename something. The Go language specification gives package main and func main() their role in starting a program. The go command gives internal/ its import restriction and recognizes the _test.go filename suffix. Rename internal/query to shared/query and update its import path, and that restriction goes away. Names such as cmd/, service/, and pkg/ communicate a choice to other developers. You can change them along with their import paths.234

Compare the official module layout guide. Its stand-alone server example illustrates cmd/ and internal packages such as auth, metrics, and model. It leaves a placeholder for other files. The choices about database migrations, web assets, and HTTP handlers in the tree above belong to this application. For example, api/openapi.yaml describes what a client can send, while internal/handler/upload.go contains the Go code that receives it. A different project might describe its messages in Protocol Buffers (.proto files) or use JSON Schema to specify the shape of a document.5

How far can one main.go take you?

For a first version that only runs sqlcheck queries.yml, start with go.mod and main.go in one directory. A module is a collection of Go packages versioned together. Its go.mod declares the module path. A package contains source files compiled together. Put package main in main.go, define func main(), and run go build -o sqlcheck . from the module root. The dot selects the package in the current directory.625

If the parser gets long, move it to parse.go in the same directory. Both files can declare package main and call each other's functions. Even the filename main.go is a convention. A run.go containing the same entry point works too. Put a test beside it in parse_test.go and run go test.54

As you add dependencies, Go can record checksums in go.sum. To distribute the dependency source alongside your code, run go mod vendor. This copies the dependency packages needed to build and test packages in the main module into vendor/. In this single-command layout, go build -mod=vendor . builds using those copies. A developer on r/golang grouped vendor, internal, and testdata together and added a qualification worth keeping: โ€œNone of these directories are compulsory in a project.โ€ Each has a defined effect when you use it.789

When do you need a second main package?

The CLI opens a named file, prints its findings, and exits. A web server reads the document from an HTTP request, sends a response, and stays alive for the next upload. Give each executable its own main package and keep the parser in a package both can import.

querykit/
โ”œโ”€โ”€ go.mod
โ”œโ”€โ”€ cmd/
โ”‚   โ”œโ”€โ”€ sqlcheck/main.go
โ”‚   โ””โ”€โ”€ sqlserver/main.go
โ””โ”€โ”€ internal/query/parse.go

Run go build ./cmd/sqlcheck and go build ./cmd/sqlserver from the root. Each command builds one executable. A separately installed migration tool could get a third directory under cmd/. The official guide also shows a repository containing only commands, each in its own top-level directory. Putting them under cmd/ becomes particularly helpful when the repository also has packages people can import. Alex Edwards uses a web application and a CLI tool to illustrate this arrangement.510

A thin entry point takes care of what is specific to its executable. The CLI opens the file and chooses what to print. The server wires up the upload handler. The parser works on the document content, so a change to the document format takes effect in both programs.

If internal/query exports Parse, who can call it?

Suppose the module path in go.mod is example.com/querykit. The parser in internal/query/parse.go declares package query. Both commands import it with the same declaration.

import "example.com/querykit/internal/query"

The import path consists of the module path plus the package's directory relative to the module root. The package name is the identifier declared by package query. By convention it matches the last element of the import path. You use that name at the call site, as in query.Parse(doc), unless you give the import a local alias. Sameer Ajmani's naming advice starts with โ€œGood package names are short and clear.โ€ Use a short lowercase word such as query. Reading the package and function names together also explains why query.Parse works better than query.ParseQuery here. main is a familiar exception to the directory-name convention, as both command directories illustrate.116

There are two checks. First, the go command checks where the importing code lives. The Go 1.24.4 command documentation says, โ€œCode in or below a directory named "internal" is importable only by code in the directory tree rooted at the parent of "internal".โ€ Here the parent is querykit/. Second, the language determines which identifiers the caller can use. The package-level function Parse starts with an uppercase letter and is exported. The package-level function parse is unexported and can be referenced directly only within its own package.3

CallerCan it call query.Parse in this layout?
cmd/sqlcheckYes. Its package is under querykit/.
cmd/sqlserverYes. A second executable can import the very same package.
A separate reporting project at example.org/report, outside that treeA direct import fails with use of internal package ... not allowed. The capitalization of Parse cannot grant access to the package.

That boundary follows the location of this particular internal directory. A parser at cmd/sqlserver/internal/query would be available to the server but out of reach of its sibling CLI. The community template also suggests internal/app/<name>/ for code specific to an application and internal/pkg/ for packages several applications share. A parser at internal/pkg/query is still internal. For two commands the shorter internal/query already does the job.13

Can a unit test call an unexported function in internal/util?

My follow-up in a separate conversation was โ€œunit test for internal utils?โ€ Suppose that uploading a document from Windows and uploading the same text from Linux should give the same result. The files can differ at line endings alone: Windows commonly uses a carriage return and a newline (\r\n), while Linux commonly uses a newline (\n). This small example normalizes that difference before computing a digest, a value we can compare to recognize repeated content.

// internal/util/hash.go
package util

import (
	"crypto/sha256"
	"fmt"
	"strings"
)

func DocumentHash(doc string) string {
	text := normalizeLineEndings(doc)
	return fmt.Sprintf("%x", sha256.Sum256([]byte(text)))
}

func normalizeLineEndings(doc string) string {
	return strings.ReplaceAll(doc, "\r\n", "\n")
}

A same-package test can isolate the normalization step. Give the test file the same package util declaration as the implementation. As the testing documentation puts it, the test file โ€œmay refer to unexported identifiers within the package.โ€ Here it can call normalizeLineEndings directly. This is a white-box test because it exercises an implementation detail.12

// internal/util/hash_test.go
package util

import "testing"

func TestNormalizeLineEndings(t *testing.T) {
	if got := normalizeLineEndings("a\r\nb"); got != "a\nb" {
		t.Errorf("normalizeLineEndings returned %q", got)
	}
}

An external test package asks a different question. Does DocumentHash give callers the same digest for equivalent text and a different digest when the content changes? Declare package util_test in another file in the same directory and explicitly import the package under test. This is a black-box test. You can replace the normalization helper without rewriting it. Its location still satisfies the import rule for internal/util.123

// internal/util/hash_api_test.go
package util_test

import (
	"testing"

	"example.com/querykit/internal/util"
)

func TestDocumentHash(t *testing.T) {
	tests := []struct {
		name     string
		document string
		wantSame bool
	}{
		{"same text", "a\nb", true},
		{"Windows line endings", "a\r\nb", true},
		{"different text", "a\nc", false},
	}
	base := util.DocumentHash("a\nb")
	for _, tc := range tests {
		t.Run(tc.name, func(t *testing.T) {
			same := util.DocumentHash(tc.document) == base
			if same != tc.wantSame {
				t.Errorf("same digest = %t, want %t", same, tc.wantSame)
			}
		})
	}
}

The slice of inputs and expectations makes this a table-driven test. Each call to t.Run gives one case a name. From the module root, go test -v ./internal/util runs both test packages together and prints the subtest names.12

Should integration tests go in a separate tests directory?

Go discovers tests by package. The toolchain recognizes the _test.go suffix and omits those files from ordinary builds. Naming a test file after the implementation is convenient: both hash_test.go and hash_api_test.go qualify. The package declaration determines which identifiers the test can access. Its filename does not decide whether it is a unit or integration test.412

What does the test exercise?A useful locationWhy put it there?
One digest functioninternal/util/hash_test.goThe test is beside the code whose behavior it describes.
One storage package and a real test databaseinternal/repository/query_integration_test.goThe test crosses a database boundary, but the behavior under test still belongs to one package.
Several components, or an upload through the running servertest/integration/ or test/e2e/upload_test.goA separate package can own setup and teardown for the whole scenario. An end-to-end test starts at the user-facing interface and checks the result.

The top-level names test/, tests/, and integration/ are team conventions. In the example module, go test ./... includes these packages by default, even a file named query_integration_test.go. To run only the end-to-end package, use go test ./test/e2e. testdata/ has special meaning to the go command. It skips directories with that name when discovering packages. A test can still open a fixture such as testdata/sample.yml by its relative path.41

What should another project import? Does a library need pkg?

The reporting program needs an application programming interface (API) it can import. One option is to move the parser to query/, change the imports in both commands, and let the reporting tool import example.com/querykit/query. If the report only needs the names, you can keep the parser under internal/ and expose a smaller function. Here is the public package from the opening tree.

// pkg/query/names.go
package query

import parser "example.com/querykit/internal/query"

func Names(doc []byte) ([]string, error) {
	queries, err := parser.Parse(doc)
	if err != nil {
		return nil, err
	}
	names := make([]string, 0, len(queries))
	for _, q := range queries {
		names = append(names, q.Name)
	}
	return names, nil
}

The import declaration gives the internal package the local name parser. The public package lives under querykit/, so it can call parser.Parse. The reporting program imports example.com/querykit/pkg/query and calls query.Names(doc). Its caller only has to deal with a slice of strings and an error. You can change the parser's internal representation without changing that contract.

Why add pkg/ to an import path? Tony Bai makes a practical case for keeping many public packages together when the root would otherwise get crowded. The trade-off shows up in every caller's import declaration. For a single library package, the official guide shows the shortest option of all: put the package at the module root and import example.com/querykit directly. The Juejin project layout example (in Chinese) offers another directory tree for comparison.135

When does a library deserve its own go.mod?

How did the project start?Where can the library live?
You planned to ship a library and a CLI together.Put the public package at the root or in query/, and the command in cmd/sqlcheck/. One go.mod lets them share a release.
You built a stand-alone server, then other projects wanted its parser.The official guide qualifies its advice in the Server project section. When packages become useful to other projects, โ€œit's best to split these off to separate modules.โ€5

A separate module can live in the same Git repository. Give parser/ its own go.mod, move the library implementation there, and have the service and the reporting tool depend on its module path. They can then adopt new library versions independently. Adding a pkg/query/ directory inside the existing module gives you another package on the existing release schedule.6

What belongs in cmd/sqlserver, and what belongs in a service package?

Follow one upload through the opening tree. A server is a running program accepting requests. In a layered application, a service package implements an operation such as importing a document. A CLI can call that operation too.

  1. Start the program. cmd/sqlserver/main.go reads the configuration, opens a database connection, supplies a store to the import service, and registers an HTTP handler for uploads.
  2. Read the request. The handler checks the upload field, passes the document content to the service, and writes the HTTP status and JSON response.
  3. Apply the rule. The service computes the digest. If the store already has a result for that digest, it returns the result. Otherwise it parses the document and asks the store to save it. A small project might choose a name closer to the operation, such as executor.
  4. Save the record. A Query struct holds related values such as a name and a statement. The repository package translates those values into database operations. Changing a query can be local to this package. Adding a stored field may also call for a schema migration.

This gives the duplicate-upload rule a useful unit test. Define a Go interface containing the methods the service calls on its store. Give the test an in-memory implementation that already has the digest and counts calls to its save method. Call the service and check that it returns the existing result and performs zero saves. The test can exercise that rule without an HTTP listener or a database.

OrganizationWhere would I look to change the upload?
By technical responsibilityStart in internal/handler/ for HTTP, internal/service/ for the import rule, or internal/repository/ for SQL. Adding a field may touch all three.
By featureOpen internal/query/. Its handler.go, service.go, and store.go can belong to one package and share unexported identifiers.
By feature, with layers inside itMike Dyne puts HTTP code in internal/api/http/, then groups the administrative feature under pkg/admin/ with its own service/ and repository/. His api directory contains request-handling code. Our top-level api/openapi.yaml describes the interface a client can call.14

How much structure does a simple command-line tool need?

The first version did one thing: it read a local file and printed the query definitions so I could check them. A single main.go at the module root would have been enough. My June 16 version put the entry point in cmd/main.go and the Go types for the input in internal/models/. The module directory was called server/, but running the command just printed the fields and exited.15

Later that day I switched from YAML to Markdown documents with headings and SQL code blocks. On June 17 the tool gained a second job: running those queries against TiDB. That is where database/ and executor/ enter the picture. By then the relevant files looked like this.1617

server/
โ”œโ”€โ”€ go.mod
โ”œโ”€โ”€ Makefile
โ”œโ”€โ”€ cmd/main.go
โ””โ”€โ”€ internal/
    โ”œโ”€โ”€ models/query.go
    โ”œโ”€โ”€ database/db.go
    โ””โ”€โ”€ executor/executor.go

database handled the connection and ran individual SQL statements. executor walked through the variables in each query and filled in their results. Both packages served the same command, so one entry point still covered the whole tool.17

๐Ÿ““ Note

Once the program could read a file, I asked Cursor โ€œhow to packge the program and deployโ€. My follow-ups included โ€œwhy use make file what is make fileโ€ and โ€œcan i use meson.build?โ€ A Makefile works the same way in a Go project as it does in a C or C++ project. Make reads rules, checks a target's prerequisites, and runs its recipe. A C or C++ Makefile often spells out how to compile object files and link them. In this Go project, running go build -o sqlquerymanagement ./cmd from server/ already compiles the imported packages and links the executable. The Go toolchain is sufficient for that build.18

What Make bought me was a repeatable release command. The project's make release built for Linux, Intel and Apple silicon Macs, and 64-bit Windows. The original rule was release: clean. If I wanted a passing test run before packaging, changing it to release: clean test would require both prerequisites to succeed before the release recipe ran. The existing test target already ran go test ./.... TutorialEdge illustrates the same use of prerequisites in its Makefile tutorial.1519

The next surprise came when I took the executable to a Windows 7 machine. Why wouldn't the Go executable run on Windows 7? (in Chinese)

Footnotes

  1. golang-standards. (2025, January 14). Standard Go Project Layout. GitHub. Overview, para. 2 and directory descriptions. โ†ฉ โ†ฉ2 โ†ฉ3

  2. The Go Authors. (2025). The Go programming language specification (Go 1.24.4). The Go Project. Program execution. โ†ฉ โ†ฉ2

  3. The Go Authors. (2025). Go 1.24.4 command documentation. The Go Project. Internal Directories, para. 1. The Go Authors. (n.d.). The Go programming language specification. Exported identifiers. โ†ฉ โ†ฉ2 โ†ฉ3 โ†ฉ4

  4. The Go Authors. (2025). Go 1.24.4 command documentation. The Go Project. Test packages and package lists and patterns. โ†ฉ โ†ฉ2 โ†ฉ3 โ†ฉ4

  5. The Go Authors. (2023, September 20). Organizing a Go module. The Go Project. In the version available in June 2025, see Basic command, Multiple commands, Packages and commands in the same repository, and Server project, final paragraph. โ†ฉ โ†ฉ2 โ†ฉ3 โ†ฉ4 โ†ฉ5 โ†ฉ6

  6. The Go Authors. (n.d.). Go modules reference. The Go Project. Modules, packages, and versions and go.mod files. โ†ฉ โ†ฉ2 โ†ฉ3

  7. The Go Authors. (n.d.). Go modules reference. The Go Project. go.sum files. โ†ฉ

  8. The Go Authors. (n.d.). Go modules reference. The Go Project. Vendoring and go mod vendor. โ†ฉ

  9. gnu_morning_wood. (2023). Comment on Best practices for coding and file structure (โ€œFile structure,โ€ note preceding the directory list). r/golang, Reddit. โ†ฉ

  10. Edwards, A. (2025, January 22). Eleven tips for structuring your Go projects. Alex Edwards. Tip 5, larger projects example. โ†ฉ

  11. Ajmani, S. (2015, February 4). Package names. The Go Blog. Good package names, para. 1. โ†ฉ

  12. The Go Authors. (2025). Package testing (Go 1.24.4). The Go Project. Introduction, paragraph beginning โ€œIf the test file is in the same packageโ€. The Go Authors. (n.d.). Table-driven tests. Go Wiki. โ†ฉ โ†ฉ2 โ†ฉ3 โ†ฉ4

  13. Tony Bai. (2023, October 5). Go้กน็›ฎ็›ฎๅฝ•่ฏฅๆ€Žไนˆ็ป„็ป‡๏ผŸๅฎ˜ๆ–น็ปˆไบŽๅ‡บๆŒ‡ๅ—ไบ†๏ผ [How should a Go project be organized?]. Section 3, discussion of pkg. โ†ฉ

  14. Dyne, M. (2023, February 25). Getting started with Go: Project structure. Evendyne, Medium. Project Structure, directory tree and description of admin. โ†ฉ

  15. CaiBorui [S2thend]. (2025, June 16). Start a new project; scaffolded a Go project [Commit 8c1c3d0]. SqlQueryManagement, GitHub. Command entry point and Makefile. โ†ฉ โ†ฉ2

  16. CaiBorui [S2thend]. (2025, June 16). Add feature process markdown file to query objects [Commit b6ea169]. SqlQueryManagement, GitHub. โ†ฉ

  17. CaiBorui [S2thend]. (2025, June 17). Add SQL query execute using MySQL connector feature [Commit 6e48d58]. SqlQueryManagement, GitHub. Query executor. โ†ฉ โ†ฉ2

  18. Free Software Foundation. (n.d.). GNU Make Manual. GNU Project. Rule syntax. The Go Authors. (2025). Go 1.24.4 command documentation. Compile packages and dependencies. โ†ฉ

  19. Forbes, E. (2026, May 29). Makefiles for Go developers. TutorialEdge. Layering commands with dependencies. This later edition illustrates the Make rule. The June 2025 commit above records the project's original targets. โ†ฉ

ยฉ 2025 borui. All rights reserved. This content may be freely reproduced, displayed, modified, or distributed with proper attribution to borui and a link to the article: borui (2025-06-16). Go directory naming conventions and project layout: when should you use cmd, internal, and pkg?. https://caiborui.com/blog/2025-06-16-en-go-project-layout-cli-server-library

@misc{borui2025-50877d3d,
  author = {borui},
  title = {{Go directory naming conventions and project layout: when should you use cmd, internal, and pkg?}},
  year = {2025},
  publisher = {borui's blog},
  url = {https://caiborui.com/blog/2025-06-16-en-go-project-layout-cli-server-library}
}