Browse by type
This repository provides a template for building a RESTful API using Go with features like JWT Authentication, rate limiting, Swagger documentation, and type-safe database access using sqlc over pgx. The application uses the Gin Gonic web framework and is containerized using Docker.
Prerequisites: Go 1.26+, Docker, and Docker Compose.
git clone https://github.com/araujo88/golang-rest-api-template
cd golang-rest-api-template
# 1. Create your .env and set two distinct secrets (each >= 32 bytes).
cp .env.example .env
go run ./scripts/generate_key.go # run twice; put the values in JWT_SECRET_KEY and API_SECRET_KEY
# 2. Start Postgres, Redis, Mongo, and the API (Gin release mode).
make up
# 3. Verify.
curl http://localhost:8001/livez # -> 200 OK
# Swagger UI: http://localhost:8001/swagger/index.html
On first boot against an empty database, the schema in pkg/database/schema.sql is created automatically, so local bootstrap needs no manual step. This is not a migration system — see Database schema and evolving it for how to change the schema of an existing database. See Getting Started for the full walkthrough.
| Concern | Library |
|---|---|
| HTTP framework | Gin |
| PostgreSQL access | pgx/v5 with sqlc-generated, type-safe queries |
| Cache / rate limiting | go-redis |
| Access-log store | MongoDB Go driver |
| Auth | golang-jwt + bcrypt |
| Observability | OpenTelemetry tracing, Prometheus metrics |
| API docs | swaggo/swag (Swagger / OpenAPI) |
| Tests | testify, uber-go/mock, testcontainers-go (ephemeral Postgres), pytest (E2E) |
role claims (user / admin).RATE_LIMIT_*)./metrics (see METRICS_*).pkg/database/schema.sql, queries in pkg/repository/queries/; regenerate with make sqlc-generate).X-Request-Id.golang-rest-api-template/
├── .github
│ ├── dependabot.yml
│ ├── pull_request_template.md
│ └── workflows
│ └── ci.yml
├── cmd
│ └── server
│ └── main.go
├── docker-compose.yml
├── Dockerfile
├── .dockerignore
├── .env.example
├── .golangci.yml
├── docs
│ ├── CONFIGURATION.md
│ ├── events.md # optional domain event publishing (Kafka)
│ ├── docs.go
│ ├── swagger.json
│ └── swagger.yaml
├── examples
│ └── kafka-consumer # standalone example consumer (not part of the API)
│ └── main.go
├── go.mod
├── go.sum
├── internal
│ └── pgtest # shared testcontainers Postgres helper for tests
│ └── pgtest.go
├── LICENSE
├── Makefile
├── sqlc.yaml # sqlc code-generation config
├── pkg
│ ├── api
│ │ ├── books.go
│ │ ├── books_test.go
│ │ ├── book_routes_auth_test.go
│ │ ├── admin_routes_test.go
│ │ ├── main_test.go
│ │ ├── probes.go
│ │ ├── probes_test.go
│ │ ├── router.go
│ │ ├── router_trusted_proxies_test.go
│ │ ├── user.go
│ │ └── user_test.go
│ ├── auth
│ │ ├── auth.go
│ │ ├── auth_test.go
│ │ ├── roles.go
│ │ └── roles_test.go
│ ├── cache
│ │ ├── cache.go
│ │ ├── cache_mock.go
│ │ ├── cache_test.go
│ │ └── redis_env_test.go
│ ├── database
│ │ ├── db.go
│ │ ├── db_test.go
│ │ ├── doc.go
│ │ ├── mongo.go
│ │ ├── mongo_test.go
│ │ └── schema.sql # DDL applied at startup + sqlc schema input
│ ├── events # optional domain event publishing (disabled by default)
│ │ ├── event.go # Event, Envelope, versioned payloads, Publisher iface
│ │ ├── noop.go # NopPublisher (default; no publishing)
│ │ ├── metrics.go # domain_events_published_total
│ │ ├── driver # EVENTS_DRIVER selection (NewFromEnv)
│ │ └── kafka # Kafka-backed Publisher (KAFKA_* only)
│ ├── middleware
│ │ ├── api_key.go
│ │ ├── api_key_test.go
│ │ ├── jwt_auth.go
│ │ ├── jwt_auth_test.go
│ │ ├── rbac.go
│ │ ├── rbac_test.go
│ │ ├── cors.go
│ │ ├── logger.go
│ │ ├── max_body.go
│ │ ├── max_body_test.go
│ │ ├── metrics.go
│ │ ├── metrics_test.go
│ │ ├── rate_limit.go
│ │ ├── rate_limit_test.go
│ │ ├── request_id.go
│ │ ├── request_id_test.go
│ │ ├── request_timeout.go
│ │ ├── request_timeout_test.go
│ │ ├── security.go
│ │ ├── tracing.go
│ │ ├── tracing_test.go
│ │ └── xss.go
│ ├── models
│ │ ├── book.go
│ │ ├── user.go
│ │ └── user_test.go
│ ├── repository
│ │ ├── book.go # BookPersistence interface (+ user.go, refresh.go)
│ │ ├── book_sqlc.go # sqlc-backed stores over pgx
│ │ ├── dbsqlc # generated code (do not edit by hand)
│ │ ├── errors.go # ErrNotFound / unique-conflict mapping
│ │ └── queries # *.sql query inputs for sqlc
│ ├── service
│ │ ├── book_service.go
│ │ └── user_service.go
│ └── tracing
│ ├── config.go
│ ├── config_test.go
│ ├── doc.go
│ ├── provider.go
│ └── provider_test.go
├── README.md
├── scripts
│ └── generate_key.go
└── tests
├── e2e.py
└── requirements.txt
go.mod; aligns CI and Docker with govulncheck / patched stdlib)pkg/database/schema.sql or pkg/repository/queries/*.sql. The generated code is committed, so it is not required to build, test, or run. make sqlc-generate invokes a pinned version via go run, so a local install is optional.git clone https://github.com/araujo88/golang-rest-api-template
cd golang-rest-api-template
vendor/ directory is committed; go.mod / go.sum are the source of truth)go mod download
To refresh go.sum after changing imports, run go mod tidy. Optional local vendoring (go mod vendor) is gitignored and not required for builds, tests, or Docker (the image runs go mod download in the builder stage).
Copy .env.example to .env and set secrets (at least JWT_SECRET_KEY and API_SECRET_KEY, each 32 bytes or longer; use go run ./scripts/generate_key.go twice). Docker Compose reads this file for ${JWT_SECRET_KEY} and ${API_SECRET_KEY} interpolation.
Build and run the Docker containers
make up
Please refer to the Makefile if you need to build in the local environment. The run-local target also requires a populated .env for those two variables.
The database schema lives in pkg/database/schema.sql. At startup ApplySchema runs it with CREATE TABLE IF NOT EXISTS, which bootstraps an empty database only. It is deliberately not a migration tool: Postgres no-ops those statements once a table exists, so editing schema.sql and redeploying against a database that already has the table will not add new columns, indexes, or constraints. (This is a known trade-off versus GORM's AutoMigrate, which did apply additive changes.)
To change the schema of a database that already has data, you must apply the change yourself — run the ALTER TABLE ... by hand, or adopt a migration tool (golang-migrate, goose, or atlas) and keep schema.sql as the source of truth sqlc reads. Keep schema.sql in sync with the live schema either way, since sqlc generates code against it.
The type-safe query code in pkg/repository/dbsqlc/ is generated by sqlc from schema.sql plus the queries in pkg/repository/queries/ (config in sqlc.yaml). After changing the schema or any query, regenerate and commit the output:
make sqlc-generate
make test # go test ./... -race -cover
Database-backed tests spin up an ephemeral PostgreSQL container via testcontainers-go, so a running Docker daemon is required. When Docker is unavailable, those tests skip (rather than fail); the rest of the suite still runs.
All environment variables and configuration notes live in docs/CONFIGURATION.md.
In short: copy .env.example to .env, set at least JWT_SECRET_KEY and API_SECRET_KEY (each 32 bytes or longer), and load the file into the environment (for example set -a && . ./.env && set +a, or docker compose --env-file .env up). Do not commit .env.
The API is documented using Swagger and can be accessed at:
http://localhost:8001/swagger/index.html
The API can publish book lifecycle events (book.created.v1, book.updated.v1,
book.deleted.v1) to Kafka so downstream services can react to changes. It is
disabled by default (EVENTS_DRIVER=none); the app runs identically without
it. Delivery is synchronous and best-effort — a broker problem never fails a
write, but it does add latency to writes. See docs/events.md
for the contract, semantics, configuration, and a runnable example consumer.
GET /livez: Liveness probe (process up; no dependency checks; no X-API-Key).GET /readyz: Readiness probe (checks Postgres, Redis, Mongo; 503 if a dependency fails; no X-API-Key). Docker image HEALTHCHECK uses /livez so the container stays alive while dependencies recover.GET /metrics: Prometheus scrape endpoint (HTTP request metrics plus Go/process collectors; no X-API-Key; outside rate limiting). Disable with METRICS_ENABLED=off.GET /api/v1/: Health check (no X-API-Key; lightweight app-level ping).GET /api/v1/books: Get all books.GET /api/v1/books/:id: Get a single book by ID.POST /api/v1/books: Create a new book.PUT /api/v1/books/:id: Replace a book's title and author (both fields required in the JSON body).PATCH /api/v1/books/:id: Partially update a book (send only the fields to change; at least one of title or author is required).DELETE /api/v1/books/:id: Delete a book.POST /api/v1/login: Login (returns access JWT + opaque refresh token).POST /api/v1/refresh: Rotate refresh token and issue a new access JWT.POST /api/v1/logout: Revoke refresh token(s); denylist current access JWT jti; empty body also sets per-user revoke_before so other devices' access JWTs are rejected when Redis denylist is enabled.POST /api/v1/register: Register a new user.GET /api/v1/admin/me: Admin-only identity probe (API key + JWT with role=admin).GET /swagger/*: Swagger UI (no X-API-Key).Successful /api/v1 JSON responses use a single envelope: {"data": ...} (implemented in pkg/httpresp). Examples: GET /api/v1/ returns {"data":"ok"}; book list and book CRUD return the resource or collection inside data; POST /api/v1/login returns {"data":{"token":"<jwt>","access_token":"<jwt>","refresh_token":"...","expires_in":300}} (token aliases access_token for older clients); POST /api/v1/register returns {"data":{"message":"Registration successful"}}.
Error responses use {"error":"..."} (pkg/httperr). RFC 7807-style problem details are not used yet.
Under /api/v1, every route except GET /api/v1/ (health) requires the X-API-Key header matching API_SECRET_KEY (service-to-service gate).
Book mutations (POST, PUT, PATCH, and DELETE on /api/v1/books and /api/v1/books/:id) also require a valid user JWT in Authorization: Bearer <token> (obtain tokens from POST /api/v1/login; the access JWT is at data.access_token or legacy data.token). Book reads (GET list and `
browse all types & interfaces →
$ claude mcp add golang-rest-api-template \
-- python -m otcore.mcp_server <graph>