Project shape
One link service, laid out twice. Both pass the same black-box test. One finishes a request when SIGTERM arrives, tests a rule with no HTTP, and swaps its store in one place. The other does not.
- 1main is the wiring. It reads config, builds each layer with its constructor, and owns startup and shutdown order.
- 2The business layer imports no transport and no storage. It defines the interfaces it needs.
- 3No package reads the environment or holds global state, so every test builds its own world.
- 4Start with one package and split when a second user or a second reason appears. Split by domain, never into models and utils.
package main
import (
"errors"
"fmt"
"log"
)
type store struct{}
func (store) Close() { fmt.Println("store flushed and closed") }
func boot() error { return errors.New("port in use") }
func main() {
log.SetFlags(0)
s := store{}
defer s.Close()1
if err := boot(); err != nil {
log.Fatal(err)2
}
}- 1Looks safe, and a review passes it.
- 2Prints, then calls os.Exit(1). Deferred functions do not run.
port in usestore flushed and closed
port in usefunc main() {
ctx, stop := signal.NotifyContext(
context.Background(), os.Interrupt, syscall.SIGTERM,
)
defer stop()
if err := run(ctx, os.Getenv, os.Stdout)1; err != nil {
fmt.Fprintln(os.Stderr, "linksd:", err)
os.Exit(1)
}
}- 1run returns, so its defers have run before os.Exit.
log.Fatal calls os.Exit, and os.Exit skips every defer. So main calls run, run returns an error, and only main exits.
- These are the handler, service and store of the build kit, moved into packages.
- links defines Store, and the stores import links. The storage arrows point at the business layer. This is dependency inversion, and it needs no framework.
- A layer changes for one reason: a new route, a new rule, or a new database.
Transport and storage both point at the business layer. main is the one package that knows all of them.
Dockerfile 11
cmd/
linksd/
main.go 131
internal/
config/
config.go 46
httpapi/
httpapi.go 98
links/
links.go 81
memstore/
memstore.go 49
pgstore/
pgstore.go 79
storetest/
storetest.go 44
justfile 23globals/
globals.go 29
handlers/
handlers.go 78
main.go 19
models/
models.go 9
utils/
utils.go 22| measure | well | badly | note |
|---|---|---|---|
| Go files, without tests | 7 | 5 | The good layout costs more. |
| Lines, without tests | 528 | 157 | The good layout costs more. |
| Mutable package variables | 0 | 3 | Each one is shared by every test. |
| init functions | 0 | 1 | A test cannot skip code that runs on import. |
| References to the concrete store | 2 | 7 | Good: all in main. Bad: all in handlers. |
| Test functions | 11 | 2 | Rules, routes, stores and imports, each alone. |
| 11 requests from outside the process | Same | Same | Same status and body, also on Postgres. No linter sees this difference. |
| SIGTERM with a request in flight | 201 Created | connection closed | exit 0, and signal: terminated. |
Both layouts give the same 11 responses. The good one has more lines. I accept that cost past a one-hour exercise.
| layout | status |
|---|---|
| go.mod | One per repository |
| cmd/name/main.go | One per program |
| internal/name/ | All other code |
| Exported packages at the root | Only for a library |
| pkg/ | Adds a path, gives nothing |
| src/ | Not approved |
| models/, utils/, common/ | Names say nothing |
| handlers/, services/, repositories/ | Splits one feature |
| signal | action |
|---|---|
| A 45-minute build, one binary | One package, three files |
| A second program needs the code | Move it to internal |
| A rule test must not start HTTP | Split the business layer out |
| A second store appears | Move the interface to its consumer |
| Two packages need each other | Merge them, or move an interface to one side |
| A package has one small function | Move it to its only caller |
| A file passes about 1,000 lines | New file first, new package only with a reason |
Size is a judgment, not a measured limit. A package name is part of each call: links.New reads well, and utils.New says nothing.
I start in one package with three files. I split when a second program needs the code, or a layer needs tests of its own.
package app/shop
shop/main.go:3:8: use of internal package app/pay/internal/tax not allowedpackage app/orders
imports app/users from orders.go
imports app/orders from users.go: import cycle not allowed- Code under a/b/internal can be imported only from the tree rooted at a/b. So pay can change tax with no effect on shop.
- To break a cycle, define the interface on the side that calls and let the other side implement it. Panel F does this with Store.
internal is enforced by the go command, not by convention. A cycle is a compile error, so a package split must have a direction.
// Errors are the language the layers share. Transport maps them to
// status codes, and storage returns them.
var (
ErrInvalid = errors.New("invalid")1
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
)
// Link is one short code and where it leads.
type Link struct2 {
Code string
URL string
Hits int64
}
// Store is what this package needs from storage. The consumer defines
// the interface, so this package imports no storage package.
type Store interface3 {
Create(ctx context.Context, l Link) error
Visit(ctx context.Context, code string) (Link, error)
}
// Service holds the rules. Its dependencies come in through New.
type Service struct {
store Store
newCode func() string
}
// New returns a Service. A missing dependency stops the boot here, and
// not at the first request.
func New(store Store, newCode func() string)4 (*Service, error) {
if store == nil || newCode == nil5 {
return nil, errors.New("links: store and newCode are required")
}
return &Service{store: store, newCode: newCode}, nil
}
// Shorten stores target under code, or under a new code if code is "".
func (s *Service) Shorten(
ctx context.Context, target, code string,
) (Link, error) {
u, err := url.Parse(target)
if err != nil || u.Host == "" {
return Link{}, fmt.Errorf("%w: url needs a host6", ErrInvalid)
}
if u.Scheme != "http" && u.Scheme != "https" {
return Link{}, fmt.Errorf("%w: url needs http or https", ErrInvalid)
}
if code == "" {
code = s.newCode()
}
l := Link{Code: code, URL: target}
if err := s.store.Create(ctx, l); err != nil {
return Link{}, fmt.Errorf("shorten: %w", err)
}
return l, nil
}
// Open counts a visit and returns the link.
func (s *Service) Open(ctx context.Context, code string) (Link, error) {
l, err := s.store.Visit(ctx, code)
if err != nil {
return Link{}, fmt.Errorf("open %q: %w", code, err)
}
return l, nil
}- 1Sentinel errors cross the layers. Only transport turns them into status codes.
- 2No JSON and no SQL tags, so a wire change does not reach this type.
- 3Small and owned by the consumer. A fake in a test needs 2 methods.
- 4Constructor injection. A function counts as a dependency, so a test fixes the code.
- 5A missing wire fails at boot. See the nil-embedded drill for the other outcome.
- 6The rule lives here, once. Any transport gets it for free.
The consumer defines the interface, with the two methods it uses. The constructor takes every dependency, so nothing is hidden.
// Service is what this package needs from the business layer.
type Service interface1 {
Shorten(ctx context.Context, url, code string) (links.Link, error)
Open(ctx context.Context, code string) (links.Link, error)
}
// linkBody is the wire form. It can change without a change to links.
type linkBody struct2 {
Code string `json:"code"`
URL string `json:"url"`
Hits int64 `json:"hits"`
}
type api struct {
svc Service
log *slog.Logger
}
// New returns the routes of the service.
func New(svc Service, log *slog.Logger) http.Handler {
a := &api{svc, log}
mux := http.NewServeMux()3
mux.HandleFunc("GET /healthz", a.health)
mux.HandleFunc("POST /links", a.create)
mux.HandleFunc("GET /links/{code}", a.open)
return mux
}
func (a *api) health(w http.ResponseWriter, _ *http.Request) {
a.write(w, http.StatusOK, map[string]string{"status": "ok"})
}
func (a *api) create(w http.ResponseWriter, r *http.Request) {
var in struct{ URL, Code string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
a.write(w, http.StatusBadRequest, problem("invalid JSON"))
return
}
l, err := a.svc.Shorten(r.Context(), in.URL, in.Code)
a.respond(w, http.StatusCreated, l, err)
}
func (a *api) open(w http.ResponseWriter, r *http.Request) {
l, err := a.svc.Open(r.Context(), r.PathValue("code"))
a.respond(w, http.StatusOK, l, err)
}
func (a *api) respond(
w http.ResponseWriter, ok int, l links.Link, err error,
) {
if err != nil {
a.write(w, a.status(err), problem(err.Error()))
return
}
a.write(w, ok, linkBody{l.Code, l.URL, l.Hits})
}
// status is the one place where an error becomes a status code.
func (a *api) status(err error) int4 {
switch {
case errors.Is(err, links.ErrInvalid):
return http.StatusBadRequest
case errors.Is(err, links.ErrNotFound):
return http.StatusNotFound
case errors.Is(err, links.ErrConflict):
return http.StatusConflict
}
a.log.Error("request failed", "error", err)
return http.StatusInternalServerError
}- 1Again owned by the consumer. A handler test passes a stub and needs no store.
- 2The wire form is a separate type from links.Link.
- 3A local mux. The default mux is global, and the drill shows the panic.
- 4The one place where an error becomes a code. A 500 logs the detail.
Transport parses, calls one method, and maps the error. A rule in a handler is a bug, because the next transport will miss it.
// Store is a links.Store in memory. Each New gives independent state.
type Store struct {
mu sync.Mutex
links map[string]links.Link
}
// New returns an empty Store.
func New() *Store1 {
return &Store{links: map[string]links.Link{}}
}
// Create adds l, or returns links.ErrConflict if the code exists.
func (s *Store) Create(_ context.Context, l links.Link) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.links[l.Code]; ok {
return fmt.Errorf("create %q: %w", l.Code, links.ErrConflict)
}
s.links[l.Code] = l
return nil
}
// Visit adds 1 to the hit count and returns the link.
func (s *Store) Visit(_ context.Context, code string) (links.Link, error) {
s.mu.Lock()
defer s.mu.Unlock()
l, ok := s.links[code]
if !ok {
return links.Link{}, links.ErrNotFound2
}
l.Hits++
s.links[code] = l
return l, nil
}- 1Return the concrete type. Accept interfaces, return structs.
- 2A store speaks the language of the business layer.
// Store is a links.Store on a connection pool.
type Store struct{ pool *pgxpool.Pool }
// Open connects, checks the connection, and creates the table.
func Open(ctx context.Context, url string) (*Store, error) {
pool, err := pgxpool.New(ctx, url)
if err != nil {
return nil, fmt.Errorf("pgstore: connect: %w", err)
}
s := &Store{pool: pool}
if err := s.migrate(ctx); err != nil {
pool.Close()
return nil, fmt.Errorf("pgstore: %w", err)
}
return s, nil
}
// Close waits for active queries and closes the pool.
func (s *Store) Close() { s.pool.Close() }
// Create adds l, or returns links.ErrConflict if the code exists.
func (s *Store) Create(ctx context.Context, l links.Link) error {
tag, err := s.pool.Exec(ctx,
`INSERT INTO links (code, url) VALUES ($1, $2)
ON CONFLICT (code) DO NOTHING1`, l.Code, l.URL)
if err != nil {
return fmt.Errorf("create %q: %w", l.Code, err)
}
if tag.RowsAffected() == 0 {
return fmt.Errorf("create %q: %w", l.Code, links.ErrConflict)
}
return nil
}
// Visit adds 1 to the hit count and returns the link.
func (s *Store) Visit(ctx context.Context, code string) (links.Link, error) {
l := links.Link{Code: code}
err := s.pool.QueryRow(ctx,
`UPDATE links SET hits = hits + 12 WHERE code = $1
RETURNING url, hits`, code).Scan(&l.URL, &l.Hits)
if errors.Is(err, pgx.ErrNoRows)3 {
return links.Link{}, links.ErrNotFound
}
if err != nil {
return links.Link{}, fmt.Errorf("visit %q: %w", code, err)
}
return l, nil
}- 1The unique key gives the same conflict that the map check gives.
- 2One atomic statement. The mutex in memstore does the same job.
- 3A driver error stops here and becomes links.ErrNotFound.
Both stores pass the same contract test, which includes 50 concurrent visits. So the choice of store is a line in main, and no rule changes.
func main() {
ctx, stop := signal.NotifyContext(1
context.Background(), os.Interrupt, syscall.SIGTERM,
)
defer stop()
if err := run(ctx, os.Getenv, os.Stdout); err != nil {
fmt.Fprintln(os.Stderr, "linksd:", err)
os.Exit(1)
}
}
// run is the program. It returns an error, so every defer runs, and a
// test can call it with its own env, output and context.
func run(2
ctx context.Context, getenv func(string) string, out io.Writer,
) error {
log := slog.New(slog.NewJSONHandler(out, nil))
cfg, err := config.Load(getenv)3
if err != nil {
return err
}
store, closeStore, err := openStore(ctx, cfg, log)
if err != nil {
return err
}
defer closeStore()4
svc, err := links.New(store, newCode)5
if err != nil {
return err
}
srv := &http.Server{
Handler: httpapi.New(svc, log),
ReadHeaderTimeout: 5 * time.Second6,
}
ln, err := net.Listen("tcp", cfg.Addr)
if err != nil {
return fmt.Errorf("listen: %w", err)
}
log.Info("listening", "addr", ln.Addr().String())
return serve(ctx, srv, ln, cfg.Grace, log)
}- 1The signal becomes a context. run does not know about signals.
- 2Every side effect arrives as an argument, so a test can pass fakes.
- 3The one read of the environment.
- 4Runs on every return path. log.Fatal would skip it.
- 5This line is all of dependency injection: a constructor and two arguments.
- 6Stops a slow client from holding a connection before the handler starts.
// openStore is the only place that names a storage package. It returns
// the interface and the function that releases it.
func openStore(1
ctx context.Context, cfg config.Config, log *slog.Logger,
) (links.Store, func(), error)2 {
if cfg.DatabaseURL == "" {
log.Info("store ready", "kind", "memory")
return memstore.New(), func() {}, nil3
}
s, err := pgstore.Open(ctx, cfg.DatabaseURL)
if err != nil {
return nil, nil, err
}
log.Info("store ready", "kind", "postgres")
return s, func() {
s.Close()
log.Info("store closed")
}, nil
}- 1The only function that names a storage package.
- 2The caller gets an interface and its cleanup. Each success path returns a non-nil pair.
- 3A real nil is impossible here, so the typed-nil drill cannot happen.
run takes its environment, output and context as arguments, so a test calls the whole program. No framework: constructors called in order.
// Config holds every setting. Only main sees it. Each constructor gets
// the values it needs, so no package reads the environment.
type Config struct1 {
Addr string
DatabaseURL string // empty: keep links in memory
Grace time.Duration
}
// Load reads the settings through getenv, so a test passes a function
// and never changes the process environment. It reports every bad value
// at once, not only the first.
func Load(getenv func(string) string2) (Config, error) {
c := Config{
Addr: getenv("LINKS_ADDR"),
DatabaseURL: getenv("DATABASE_URL"),
Grace: 10 * time.Second,
}
var errs []error
if c.Addr == "" {
errs = append(errs, errors.New("LINKS_ADDR is required"))
}
if v := getenv("LINKS_GRACE"); v != "" {
d, err := time.ParseDuration(v)
if err != nil || d <= 0 {
errs = append(errs, fmt.Errorf("LINKS_GRACE: bad value %q", v))
}
c.Grace = d
}
if err := errors.Join(errs...)3; err != nil {
return Config{}, fmt.Errorf("config: %w", err)
}
return c, nil
}- 1One struct. Constructors receive values from it and never see the struct.
- 2The same type as os.Getenv, so main passes that, and a test passes a map lookup.
- 3An operator sees every bad value in one run. Go 1.20.
The standard library covers most services. Add a flag only for a value that an operator sets by hand.
Config is a plain struct, read once in main. A test passes a function, so it can run in parallel with no Setenv.
// serve runs srv until ctx ends. Then it stops taking connections and
// waits for active requests. run closes the store after this returns.
func serve(
ctx context.Context, srv *http.Server, ln net.Listener,
grace time.Duration, log *slog.Logger,
) error {
serveErr := make(chan error, 1)1
go func() { serveErr <- srv.Serve(ln) }()
select {
case err := <-serveErr:
return fmt.Errorf("serve: %w", err)
case <-ctx.Done():
}
log.Info("stopping", "cause", context.Cause(ctx)2.Error())
stop, cancel := context.WithTimeout(context.WithoutCancel(ctx)3, grace)
defer cancel()
if err := srv.Shutdown(stop)4; err != nil {
return fmt.Errorf("shutdown: %w", err)
}
if err := <-serveErr; !errors.Is(err, http.ErrServerClosed5) {
return fmt.Errorf("serve: %w", err)
}
log.Info("requests drained")
return nil
}- 1One slot, so the goroutine can always exit.
- 2Since Go 1.26, this names the signal.
- 3ctx has already ended. Shutdown needs a live context with its own deadline.
- 4Closes the listener, then waits for active requests. It does not cancel them.
- 5The normal result of Serve after Shutdown. Do not log it as a failure.
Set the grace limit below the time your orchestrator waits before SIGKILL. G12 adds a worker pool to this order.
On SIGTERM I close the listener, drain within a grace limit, and return. The defer then closes the store, last.
// DB is the store. Any package can read or change it.
var DB = map[string]*models.Link{}1
// Mu guards DB, if the caller remembers to take it.
var Mu sync.Mutex
// Port is read when the program loads, before main runs.
var Port string
func init()2 {
Port = os.Getenv("PORT")
if Port == "" {
Port = "8080"
}
}- 1One store per process, so two tests share it.
- 2Runs on import, before any test can set the value.
func main() {
handlers.Register()1
log.Fatal(http.ListenAndServe2("127.0.0.1:"+globals.Port, nil))
}- 1Writes to the process-wide default mux.
- 2No signal handling, no timeouts, no drain.
// CreateLink is transport, business rules and storage in one function.
func CreateLink(w http.ResponseWriter, r *http.Request)1 {
var in struct{ URL, Code string }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
utils.WriteJSON(w, 400, map[string]string{"error": "invalid JSON"})
return
}
u, err := url.Parse(in.URL)
if err != nil || u.Host == "" {
fail(w, 400, "invalid: url needs a host")2
return
}
if u.Scheme != "http" && u.Scheme != "https" {
fail(w, 400, "invalid: url needs http or https")
return
}
code := in.Code
if code == "" {
code = utils.RandCode()
}
globals.Mu.Lock()3
defer globals.Mu.Unlock()
if _, ok := globals.DB[code]; ok {
fail(w, 409, fmt.Sprintf("shorten: create %q: conflict", code))
return
}
l := &models.Link{Code: code, URL: in.URL}
globals.DB[code] = l
utils.WriteJSON(w, 201, l)4
}- 1A rule test must build an HTTP request.
- 2The rule and its status code are one line. A second transport copies them.
- 3A move to Postgres rewrites this function and every other one like it.
- 4The stored struct is the wire format. A new column becomes a new response field.
This code has no bug a linter can see. The cost is in the tests, the shutdown, and the next change.
func TestShortenRules(t *testing.T) {
tests := []struct {
name, url, code string
wantCode string
wantErr error
}{
{"new code", "https://go.dev", "", "fixed", nil},
{"own code", "https://go.dev", "go", "go", nil},
{"taken code", "https://go.dev", "taken", "", links.ErrConflict},
{"no host", "https://", "", "", links.ErrInvalid},
{"bad scheme", "ftp://go.dev", "", "", links.ErrInvalid},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()1
svc := newService(t)2 // its own store: nothing is shared
got, err := svc.Shorten(t.Context(), tt.url, tt.code)
if !errors.Is(err, tt.wantErr) {
t.Fatalf("error %v, want %v", err, tt.wantErr)
}
if got.Code != tt.wantCode {
t.Fatalf("code %q, want %q", got.Code, tt.wantCode)
}
})
}
}- 1Safe, because each subtest builds its own store. The bad layout cannot do this.
- 2A fresh world per test, built with the same constructors as main.
// forbidden says what each layer must never reach, also through other
// packages. A wrong import fails this test in CI, not in a review.
var forbidden = map[string][]string{
"internal/links": {2
"net/http", "encoding/json", "github.com/jackc/pgx/v5",
pkg + "internal/httpapi", pkg + "internal/memstore",
pkg + "internal/pgstore", pkg + "internal/config",
},
"internal/httpapi": {
"github.com/jackc/pgx/v5", pkg + "internal/memstore",
pkg + "internal/pgstore", pkg + "internal/config",
},
"internal/memstore": {"net/http", pkg + "internal/httpapi"},
"internal/pgstore": {"net/http", pkg + "internal/httpapi"},
"internal/config": {"net/http", pkg + "internal/links"},
}
func TestLayers(t *testing.T) {
for dir, banned := range forbidden {
t.Run(dir, func(t *testing.T) {
out, err := exec.Command("go", "list", "-deps"1, "./"+dir).Output()
if err != nil {
t.Fatalf("go list: %v", err)
}
deps := strings.Fields(string(out))
for _, b := range banned {
if slices.Contains(deps, b) {
t.Errorf("%s must not depend on %s", dir, b)
}
}
})
}
}- 1Lists every package a package reaches, also through other packages.
- 2The business layer must never reach net/http or pgx.
A rule test runs in parallel with no server. A second test fails CI if a layer imports what it must not.
Step 1: Boot
- main reads the config, opens the store, and builds each layer.
- The log says: store ready: postgres, then listening.
If it fails
Any error returns from run. The process exits 1 and prints a line a person can read.
| same request, same signal | the client gets | the process ends with |
|---|---|---|
| Laid out well | HTTP/1.1 201 Created | exit 0 |
| Laid out badly | connection closed | signal: terminated |
I can prove the drain: open a request, send SIGTERM, finish the request, and expect a 201 and exit 0.
| tool | it found | it never sees |
|---|---|---|
| gofmt -l . | unformatted.go | Anything but format. |
| go vet ./... | main.go:19:13: read passes lock by value: example.com/flawed.counter contains sync.Mutex main.go:30:22: address format "%s:%d" does not work with IPv6 (passed to net.Dial at L31) main.go:28:14: fmt.Printf format %d has arg "text" of wrong type string | Dead code, deprecated calls. |
| staticcheck ./... | main.go:5:2: io/ioutil has been deprecated since Go 1.19 (SA1019) main.go:25:6: func unused is unused (U1000) main.go:28:13: Printf format %d has arg #1 of wrong type string (SA5009) main.go:34:13: sleeping for 5 nanoseconds is probably a bug; be explicit if it isn't (SA1004) unformatted.go:3:7: func add is unused (U1000) | Vulnerabilities. |
| govulncheck ./... | GO-2022-1059 Your code is affected by 1 vulnerability from 1 module. | Vulnerable code with no call path. Those appear as a separate count. |
go vet also runs a subset of its checks during go test. No tool here reports the layout problems in panel L.
gofmt settles style, vet finds likely bugs, staticcheck finds more, and govulncheck reports only vulnerable code my program can reach.
# Run `just` before each commit. CI runs the same recipe.
default: check
check: fmt vet lint test vuln1
fmt:
test -z "$(gofmt -l .)"
vet:
go vet ./...
lint:
go run honnef.co/go/tools/cmd/staticcheck@latest3 ./...
test:
go test -race -count=12 ./...
vuln:
go run golang.org/x/vuln/cmd/govulncheck@latest ./...
build:
CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" \
-o bin/linksd ./cmd/linksd- 1CI and the laptop run the same line.
- 2count=1 skips the test cache, so the result is fresh.
- 3Short for this sheet. In a real module, pin with a tool directive: go get -tool, Go 1.24.
FROM golang:1.27.3-alpine AS build1
WORKDIR /src
COPY go.mod go.sum ./2
RUN go mod download
COPY . .
ARG PKG=./cmd/linksd
RUN CGO_ENABLED=03 go build -trimpath -ldflags="-s -w" -o /linksd "$PKG"
FROM gcr.io/distroless/static-debian13:nonroot4
COPY --from=build /linksd /linksd
ENTRYPOINT ["/linksd"]5- 1Two stages: the toolchain stays out of the final image.
- 2A separate layer, so a code change does not download modules again.
- 3No libc link. A test confirms: no interpreter, no shared libraries.
- 4CA roots and time zones, no shell, and a user that is not root.
- 5Exec form: the binary is PID 1, so SIGTERM reaches it.
| linux/amd64 build | size |
|---|---|
| go build | 16.2 MB |
| -trimpath -ldflags="-s -w" | 11.1 MB |
Sizes are the binary only, with pgx linked, from Go 1.27.3. Build the image in CI: the binary and its flags are tested here, and the image is not.
The check recipe is the one thing I run before a commit. A static binary is about 11.1 MB and needs no base image with libc.
| since | what changed | what it means here |
|---|---|---|
| 1.18 | go.work workspaces. go version -m shows build settings, and debug/buildinfo reads them. | A test can check the flags inside a binary. |
| 1.20 | errors.Join. The go command disables cgo by default on systems with no C toolchain. | Config errors report together. |
| 1.21 | log/slog. The go line becomes a strict minimum, and the go command fetches toolchains. | Structured logs with no dependency. |
| 1.22 | ServeMux patterns accept methods and wildcards. | Most small services need no router library. |
| 1.23 | The godebug directive in go.mod. vet gains stdversion. | Old behaviour is pinned in one visible line. |
| 1.24 | The tool directive in go.mod, and go get -tool. crypto/rand.Text. T.Context. | No more tools.go file. Linter versions live in go.mod. |
| 1.25 | The ignore directive in go.mod. GOMAXPROCS follows the cgroup CPU limit on Linux. vet gains waitgroup and hostport. | A container limit applies with no extra library. Vet found the IPv6 address bug in panel O. |
| 1.26 | go fix is rebuilt around modernizers. go mod init picks a lower go version. NotifyContext cancels with a cause that names the signal. | go fix ./... moves old code to current idioms. |
| 1.27 | go test runs stdversion by default. New modernizers. go mod tidy merges duplicate require blocks in go 1.27 modules. gofmt changes column alignment in a small number of files. | Run gofmt after the upgrade, in its own commit. |
| when | the moment | what to do or say |
|---|---|---|
| build | The first minute. | One package: store.go, service.go, handler.go, main.go. See the build kit. Do not create folders. |
| build | A rule appears in a handler. | Move it to the service. A rule test then needs no request. |
| build | The store needs a test double. | Keep the interface small, and pass it to the constructor. |
| build | You reach for a package variable. | Put it on the struct. Two tests then cannot collide. |
| talk | "How would you structure this for a team?" | cmd for the binary, internal for the rest, one package per layer or domain. The files move, and the code stays. |
| talk | "How do you move to Postgres?" | Add a store that passes the contract test, and change one function in main. |
| talk | "What happens on a deploy?" | SIGTERM, close the listener, drain within the grace limit, close the store. The load balancer stops sending first. |
| talk | "Do you use a DI framework?" | No. main calls constructors in order, and the compiler checks the wiring. |
I build in one package with three layers in three files. In the talk, I show how those files become packages with no rewrite.
0 of 10 known
Predict the output. b is declared after a.
package main import "fmt" var a = trace("a", b+1) var b = trace("b", 1) func trace(name string, v int) int { fmt.Println("var", name, v) return v } func init() { fmt.Println("init 1") } func init() { fmt.Println("init 2") } func main() { fmt.Println("main", a) }Predict the output. LAB_SHAPE_PORT is not set when the program starts.
package main import ( "fmt" "os" ) var port = os.Getenv("LAB_SHAPE_PORT") func main() { os.Setenv("LAB_SHAPE_PORT", "9000") fmt.Printf("%q\n", port) fmt.Printf("%q\n", os.Getenv("LAB_SHAPE_PORT")) }Predict the output.
package main import ( "errors" "fmt" ) var ErrPort = errors.New("LINKS_ADDR is required") func load() error { var errs []error errs = append(errs, ErrPort) errs = append(errs, errors.New("LINKS_GRACE: bad value")) return fmt.Errorf("config: %w", errors.Join(errs...)) } func main() { err := load() fmt.Println(err) fmt.Println(errors.Is(err, ErrPort)) fmt.Println(errors.Join(nil, nil) == nil) }Predict the output.
package main import "fmt" type Store interface{ Get() string } type Mem struct{ v string } func (m *Mem) Get() string { return m.v } func New(s Store) string { if s == nil { return "refused" } return "accepted" } func main() { var m *Mem fmt.Println(New(nil)) fmt.Println(New(m)) }Predict the output.
package main import "fmt" type Store interface{ Get() string } type Service struct{ Store } func main() { defer func() { fmt.Println("recovered:", recover()) }() s := Service{} fmt.Println("built") fmt.Println(s.Get()) }Predict the output. The same register function runs twice, as it would in two tests.
package main import ( "fmt" "net/http" "strings" ) func register() { http.HandleFunc("GET /healthz", func(http.ResponseWriter, *http.Request) {}) } func main() { defer func() { msg := fmt.Sprint(recover()) fmt.Println(strings.TrimSpace(msg[strings.LastIndex(msg, "\n"):])) }() register() fmt.Println("first test passed") register() fmt.Println("second test passed") }Predict the output.
package main import "fmt" func open(name string) func() { fmt.Println("open", name) return func() { fmt.Println("close", name) } } func run() error { defer open("store")() defer open("pool")() defer open("server")() fmt.Println("serving") return nil } func main() { if err := run(); err != nil { fmt.Println(err) } }Predict the output. The program sends SIGTERM to itself.
package main import ( "context" "fmt" "os/signal" "syscall" ) func main() { ctx, stop := signal.NotifyContext( context.Background(), syscall.SIGTERM, ) defer stop() if err := syscall.Kill(syscall.Getpid(), syscall.SIGTERM); err != nil { fmt.Println(err) } <-ctx.Done() fmt.Println(ctx.Err()) fmt.Println(context.Cause(ctx)) }Predict the output.
package main import ( "fmt" "time" ) func main() { go func() { time.Sleep(50 * time.Millisecond) fmt.Println("flushed") }() fmt.Println("main returns") }Predict the output. main has a deferred recover.
package main import ( "fmt" "time" ) func main() { defer func() { fmt.Println("recovered:", recover()) }() go func() { panic("boom") }() time.Sleep(100 * time.Millisecond) fmt.Println("main done") }
- lines
- 528 well, 157 badly, for the same 11 responses.
- globals
- 0 well, 3 badly.
- binary
- 16.2 MB plain; 11.1 MB with -s -w and -trimpath.
- files to swap a store
- 1 file changes: the main package. The new store is new code.
- layer rule
- 0 imports from links into the rest of the module.
Go 1.27.3, linux/amd64 target. Line counts exclude tests.