Go REST API template
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.
log/slog, database/sql; no frameworkEvery 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.
The problem
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.
Errors, lists, concurrent updates and tokens each follow one documented convention, used by every endpoint.
Optional code is delimited by marker comments. Turning a module off deletes it together with its dependencies.
CI generates projects with different options and builds, vets and tests each one.
How it is organised
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.
internal/users and internal/tasks each hold a model, a service, a repository and a handler. Features do not import each other.
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.
internal/app constructs every component and mounts every route. Adding a feature touches two files there and nothing else.
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
Make it yours
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.
$ 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
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
-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 containermake 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 →
$ 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
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.
# 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
# the API with PostgreSQL; creates admin / change-me-now-123
make compose-up
# the same plus Prometheus, Grafana and Tempo
make obs-up
make docker-build
docker run --rm -p 8080:8080 -p 9090:9090 \
-e APP_ENV=development -e DATABASE_DRIVER=sqlite -e SQLITE_PATH=/tmp/app.db \
-e BOOTSTRAP_ADMIN_ENABLED=true -e BOOTSTRAP_ADMIN_USERNAME=admin \
-e BOOTSTRAP_ADMIN_FIRST_NAME=Ada -e BOOTSTRAP_ADMIN_LAST_NAME=Lovelace \
-e BOOTSTRAP_ADMIN_PASSWORD=change-me-now-123 go-rest-template:dev
$ 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 →
What is in the box
Each item is implemented, tested and documented. The ones marked optional can be removed when you create your project.
RFC 9457 errors with a stable code, the request ID and per-field details. Internal causes are logged, never sent.
Lists return {data, next_cursor} with an opaque cursor, 20 items by default and 100 at most.
Every row has a version. A stale If-Match gets 412 and a concurrent write gets 409.
Each refresh token works once. Presenting it twice revokes every token issued from that login.
With EdDSA the public key is published at /.well-known/jwks.json.
Embedded SQL run by goose, with down migrations and an advisory lock on PostgreSQL.
Metrics and pprof listen on a separate port, away from the public API.
Request count, latency histogram and in-flight gauge, labelled by route template. Optional.
Server spans exported over OTLP/HTTP when OTEL_ENABLED=true. Optional.
Per client IP, with a tighter budget for the authentication endpoints. Counters are per process. Optional.
Probes, restricted security context, and optional ingress, autoscaling, disruption budget and network policy.
release-please cuts versions; binaries ship with an SBOM and the image is signed with cosign.
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.
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.
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.
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.
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.
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.
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