liveBook · Manning

Internal directory

As explained in Learn Go with Pocket-Sized Projects

An internal package is a Go package that can be imported only by code within its permitted parent directory tree.

Put a Go package under an `internal` directory when the application needs to import it but outside code should not. The directory name enforces an import boundary: code outside its permitted parent directory tree cannot import packages inside it. An exported name does not bypass that boundary. section 8.2.1

> tree
.
├── go.mod
├── internal
│   ├── api
│   │   ├── doc.go
│   │   └── http.go
│   └── handlers
│       ├── doc.go
│       ├── newgame
│       │   └── handler.go
│       └── router.go
└── main.go

This service keeps its HTTP API definitions and handlers under `internal/`, while `main.go` at the module root imports the handlers to start the server. section 8.2.1

The same layout works for a command-line tool: keep `main.go` at the root and place its implementation in `internal/solver`. The root program can call the solver’s exported `New`, `Solve`, and `SaveSolution` functions and methods without making the package available to outside importers. section 9.2.3 section 9.2.1

Use the boundary for implementation code, not as a substitute for deciding what each package should expose. Service domain types commonly belong under `internal/`; HTTP response types serve the endpoint handlers, while the rest of the service uses domain types. Unlike `internal/`, `testdata/` is skipped by Go build and test commands. section 8.7

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines the import boundary and demonstrates package layouts, but does not walk through an attempted outside import.
Examples
Shows an HTTP service with `internal/api` and `internal/handlers`, plus a maze tool with `internal/solver`.
What it assumes
Assumes familiarity with Go packages and modules while introducing the special behavior of the `internal` directory.
What you can do after
Build it from scratch by placing application-only packages under `internal/` and importing them from `main.go`.
How it connects
Connects package organization to Go modules, exported names, HTTP handlers, domain types, and command-line tools.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.