go-rest-template

Go REST API template

Start from a service,
not a skeleton.

A working Go API with an enforced OpenAPI contract, token authentication and two databases, plus a tool that renames it and removes the parts you do not want.

  • Go 1.26+ chi router, log/slog, database/sql; no framework
  • OpenAPI 3.1 embedded in the binary and checked on every request
  • PostgreSQL and SQLite served by one repository implementation
  • MIT licensed
One requestOrder taken from internal/app/routes.go
every request /api/v1 feature package request ID client IP tracing logger recover metrics security headers CORS body limit timeout rate limit contract validation authentication handler service repository database optional module, removable when you create your project GET /api/v1/tasks/7

Every request gets an ID and a logger that carries it, runs inside panic recovery and is bounded in size and time before any application code sees it.

What you getA service that already runs
What you chooseDatabase, modules, deployment
What you keepOnly the code you chose

The problem

The same decisions,
every new service.

Before a new API does anything useful it needs an error format, pagination, authentication, migrations, configuration, logging, tests and a way to ship. A template answers those once. A template you cannot trim leaves code in your repository that you did not choose and have to maintain.

Decided, not implied

Errors, lists, concurrent updates and tokens each follow one documented convention, used by every endpoint.

Removable by design

Optional code is delimited by marker comments. Turning a module off deletes it together with its dependencies.

Checked, not promised

CI generates projects with different options and builds, vets and tests each one.

How it is organised

Features on top,
platform below.

A feature package owns its model, rules, storage and HTTP endpoints. The platform layer holds what features share. One file, the composition root, knows about all of them.

01

Feature packages

internal/users and internal/tasks each hold a model, a service, a repository and a handler. Features do not import each other.

02

The contract decides

api/openapi.yaml is embedded in the binary. Requests that do not match it are rejected, and a test fails when a route and the document disagree.

03

One composition root

internal/app constructs every component and mounts every route. Adding a feature touches two files there and nothing else.

project layout
api/openapi.yaml        # the contract, embedded and enforced
cmd/api                 # the server
cmd/migrate             # up, down, status
internal/
  app/                  # composition root: wiring and routes
  auth/                 # tokens, passwords, authentication middleware
  users/                # a feature: model, service, repository, handler
  tasks/                # the example feature, source of the generator
  config/               # every variable declared once
  platform/             # database, httpx, middleware, contract, tracing
migrations/             # SQL per driver, embedded
tools/init              # turns the template into your project
tools/scaffold          # generates a resource

Packages and dependency rules →

Make it yours

Keep what you need,
delete the rest.

The init tool renames the module and the application, removes the options you turn off, deletes what belongs to the template itself, runs go mod tidy and regenerates the example environment file. It asks questions, or takes flags.

terminal
$ go run ./tools/init -yes \
    -module github.com/acme/billing -db postgres -tracing=false
billing is ready.

  module   github.com/acme/billing
  kept     dev container, example resource, helm chart,
           metrics, postgres, rate limiting
  removed  observability stack, sqlite, tracing
$ make check
internal/app/routes.go
r.Use(middleware.Logger(a.logger))
r.Use(middleware.Recover)
// init:metrics:begin
if a.cfg.Metrics.Enabled {
    r.Use(middleware.Metrics(a.registry))
}
// init:metrics:end
r.Use(middleware.SecurityHeaders)

a.users.Routes(r, a.authn)
a.tasks.Routes(r, a.authn) // init:example
FlagDefaultWhat it controls
-modulerequiredGo module path of the new project
-namelast path elementApplication name: service name, image and chart
-dbbothboth, postgres or sqlite; the other driver and its migrations are deleted
-exampletrueThe tasks resource and the resource generator
-metricstruePrometheus metrics
-tracingtrueOpenTelemetry tracing
-ratelimittrueRate limiting per client IP
-observabilitytruePrometheus, Grafana and Tempo compose profile; needs postgres, metrics and tracing
-helmtrueThe Helm chart; needs postgres
-devcontainertrueThe dev container

make test-init, which CI runs, generates nine projects with different options. Each one must be free of template leftovers, pass gofmt, build, pass go vet and pass its tests; projects that keep the example also generate a resource and test it. Linting the generated projects is opt-in with INIT_LINT=1. Create your project →

terminal
$ make resource name=project
Created the projects resource:
  internal/projects/api_test.go
  internal/projects/handler.go
  internal/projects/repository.go
  internal/projects/service.go
  internal/projects/project.go
  migrations/postgres/00003_projects.sql
  migrations/sqlite/00003_projects.sql

Updated api/openapi.yaml, internal/app/app.go
and internal/app/routes.go.

The generator clones the tasks example under a new name: feature package, one migration per driver, the paths and schemas in the OpenAPI document, and the wiring. The result builds, passes its own end-to-end tests and serves a working CRUD API. From there you change the fields and the rules.

Names are a single lowercase word; pass plural= when adding an s is not right. Add a resource →

Run it

From clone
to first request.

In development the service uses a SQLite file, so Go is the only requirement. The same binary runs against PostgreSQL in Compose, in the container image and in the Helm chart.

terminal
# SQLite file under data/, API on :8080, metrics on :9090
BOOTSTRAP_ADMIN_ENABLED=true BOOTSTRAP_ADMIN_USERNAME=admin \
BOOTSTRAP_ADMIN_FIRST_NAME=Ada BOOTSTRAP_ADMIN_LAST_NAME=Lovelace \
BOOTSTRAP_ADMIN_PASSWORD=change-me-now-123 make run
terminal
$ curl -s localhost:8080/api/v1/auth/login -H 'Content-Type: application/json' \
    -d '{"username":"admin","password":"change-me-now-123"}'
{"access_token":"eyJhbGciOi…","refresh_token":"…","token_type":"Bearer","expires_in":900}
$ curl -si localhost:8080/api/v1/tasks -H "Authorization: Bearer $TOKEN" \
    -H 'Content-Type: application/json' -d '{"title":"Write docs","description":"All of them"}'
HTTP/1.1 201 Created
Etag: "1"
{"id":1,"title":"Write docs","description":"All of them","status":"pending","user_id":1,…}
$ curl -s localhost:8080/api/v1/tasks -H "Authorization: Bearer $TOKEN" \
    -H 'Content-Type: application/json' -d '{"title":"","description":"x"}'
{"type":"about:blank","title":"Bad Request","status":400,"detail":"request validation failed",
 "code":"invalid_argument","request_id":"…","errors":[{"field":"title","message":"minimum string length is 1"}]}

Responses shortened. Full quickstart →

Questions.

Why chi and not a framework?

chi is a router built on net/http: handlers are standard http.HandlerFunc values and middleware is func(http.Handler) http.Handler. Nothing in the feature packages depends on a framework type, so the router is the only part you would have to replace.

Why hand-written SQL instead of an ORM or a generator?

The template supports two databases with one repository per resource. Queries are written once with ? placeholders and rewritten for PostgreSQL at run time, which keeps the SQL visible and the generator simple. If you keep a single database, adding a query generator is a local change inside each repository.

Why two binaries?

cmd/api serves and cmd/migrate changes the schema. Keeping them apart lets you run migrations as a separate step with different credentials. Both are in the container image, and the server can also migrate at startup with DATABASE_AUTO_MIGRATE.

Is SQLite supported in production?

It works, with limits: the pool is one connection because SQLite has a single writer, and the Compose file and the Helm chart assume PostgreSQL. SQLite is meant for development, tests and small single-instance deployments. PostgreSQL is the production default.

How do I pick up later changes of the template?

There is no automatic sync. A generated project is independent: the init tool deletes itself and the markers, and from then on the code is yours. To adopt a later change, read the changelog and port what you want.

What does the init tool do with the license?

It keeps LICENSE, which is the MIT license of the template. Add your own copyright line or replace the file with the license of your project.

Create your
project.

Clone it, answer a few questions and run the tests of what is left.

$git clone https://github.com/antoniopaya22/go-rest-template billing && cd billing && make init