Package boundaries

cmd starts the process, internal hides the details, and dependencies go in one direction.

A small service does not need six layers. It needs a clear boundary.

cmd/server        процесс: конфиг, лог, сигналы
internal/httpapi  HTTP и статус-коды
internal/store    данные
internal/content  правила предметной области, без сокета и SQL

This platform is built the same way. main does not contain the course rules and does not write SQL. It wires the catalog, the database, and HTTP and starts them. The content package does not import net/http. Otherwise a lesson could not be checked without a server.

The direction of imports matters more than the names. HTTP may know about the store. The store must not know about HTTP: it has nowhere to put an http.Request. If you badly want to pass "who called", pass an id and a context, not the whole request.

internal closes packages off from other modules. While there is one service, this is protection against a future import of "I'll just glance at the function". A public library module is stricter: the external API is small, and the rest is in internal.

Do not start a package models where everything is dumped, and a package utils where the rest is dumped. The package name should finish the phrase at the call site: store.Open, content.New. utils.Do finishes no phrase.

An interface appears at a seam that is painful to test, or that already has two implementations. Not on the first day "for growth". A concrete type is easier to read. When a stub for a test becomes necessary, cut the interface to the handler's actual calls, and it will turn out small.

Practice

  1. What main does

    What work does cmd/server/main.go do in an ordinary service?

    • All the business logic, so there is one file
    • Wiring the dependencies and starting the process
    • Only declaring global variables
    • Generating interfaces for every package
  2. Who imports whom

    The package store wants to log the path of an HTTP request and for that imports net/http, so it can accept *http.Request. What is wrong with that?

    • That is how it should be. Request is more convenient to carry everywhere
    • store must not depend on HTTP. The needed data is passed separately
    • The problem is only the package name
    • The compiler will break this import itself
  3. Package names

    Mark the useful guides for the packages of a service.

    • The package name finishes the phrase at the call site
    • A shared utils package for everything you could not find a place for
    • internal for code that is not the external API of the module
    • One models package for SQL, JSON, and domain rules all at once