codebuild
codebuild turns small Go spec files into a complete REST API: domain types, request validation, net/http handlers, database/sql repositories with SQL written for your database, migrations, and the application bootstrap.
//go:build ignore
package specs
type User struct {
_ struct{} `gen:"table=users,softdelete"`
ID uuid.UUID `gen:"pk,auto"`
Name string `gen:"required,notempty,max=120"`
Email string `gen:"required,unique,email,max=254"`
Role string `gen:"enum=admin|operator|viewer,default=viewer"`
OrgID uuid.UUID `gen:"rel=belongs_to:Org"`
CreatedAt time.Time `gen:"auto=create"`
}
From that file codebuild generates GET/POST /users and GET/PUT/DELETE /users/{id} (plus GET /orgs/{orgId}/users once Org declares the has_many side), validation with field errors, RFC 9457 problem responses, paginated and filtered listing, soft delete, a migration, and repository tests.
Principles
- Zero runtime dependency. codebuild is a development tool, like
sqlc or stringer. Generated code imports only the standard library, the database driver and, on Go 1.26, github.com/google/uuid; microservice workspaces add google.golang.org/grpc and google.golang.org/protobuf. Delete codebuild and the project still builds.
- Standard library first.
net/http routing patterns, database/sql, log/slog, encoding/json or encoding/json/v2. No reflection in generated code, no DI container, no framework.
- Deterministic. The same specs, Go version and dialect always produce byte-identical files. Output is sorted and gofmt-formatted, so diffs stay reviewable.
- Version-aware. The
go directive of your go.mod decides which language and library features the generated code uses. A Go 1.26 project never receives Go 1.27 symbols; go vet's stdversion check passes.
- Your code stays yours.
*_gen.go files are regenerated; services, main.go, configuration and applied migrations are never overwritten.
What a generated project contains
- Layers per domain: generated handlers call your
Service, which calls the generated repository explicitly. Services are written once with one method per operation and never regenerated; when a spec change needs a new method, codebuild adds it in a new file instead of editing yours.
- Transactions: repositories accept
*sql.DB or *sql.Tx (WithTx), and database.InTx wraps a unit of work.
- HTTP:
net/http routing patterns, RFC 9457 problem details, validation with field errors, paginated and filtered lists, creates that are safe to retry with an Idempotency-Key header, request IDs propagated to every log line, /livez and /readyz probes, timeouts and graceful shutdown with a drain delay.
- Authentication: mark an account entity with
auth=session, auth=jwt and optionally apikey to get login, registration, PBKDF2 password hashing, revocable sessions or rotating refresh tokens, API keys, routes protected by default, roles and per-user ownership of rows, all with the standard library. See docs/authentication.md.
- Observability: optional Prometheus metrics on
METRICS_ADDR, OpenTelemetry traces exported over OTLP/HTTP when OTEL_EXPORTER_OTLP_ENDPOINT is set, W3C trace context across HTTP and gRPC, trace IDs in every log line, and configurable CORS, still with the standard library only. See docs/observability.md.
- API description:
openapi.json (OpenAPI 3.1) is generated from the same views as the handlers, with every route, body, filter, error and security requirement, committed next to the code and served at GET /openapi.json. Point Swagger UI, Redoc, Scalar or a client generator at it.
- Data: SQL written for one dialect, incremental migrations with an embedded migrator, repository tests against a real database.
- Delivery: a multi-stage
Dockerfile with a distroless non-root image, a GitHub Actions workflow that runs vet, tests with the race detector against a database service container, govulncheck and the image build, and Kubernetes manifests (a generated kustomize base with probes, resources, a hardened security context and a migration Job, plus an overlay that is yours). See docs/production.md.
- Microservices: wrap entities in
<Name>Service structs to get a Go workspace with one gRPC service per struct (its own database or a shared one), generated .proto contracts whose field numbers stay compatible, a REST gateway that authenticates through the account service, mutual TLS plus a signed internal token between services with keys and certificates that rotate without restarts, client-side load balancing, retries and circuit breakers, Docker Compose, Kubernetes manifests and one CI workflow per module. See docs/microservices.md.
Install
go install github.com/WilkerSL/go-codebuild-tool/cmd/codebuild@latest
To pin codebuild per project, add it as a tool dependency and run it with go tool:
go get -tool github.com/WilkerSL/go-codebuild-tool/cmd/codebuild@latest
go tool codebuild version
codebuild needs Go 1.26 or later. Prebuilt binaries for Linux, macOS and Windows are attached to each release with signed checksums, SBOMs and build provenance; SECURITY.md shows how to verify them.
Five-minute quickstart
mkdir shop && cd shop
mkdir specs
Create specs/orgs.go and specs/users.go:
//go:build ignore
package specs
import (
"time"
"github.com/google/uuid"
)
type Org struct {
ID uuid.UUID `gen:"pk,auto"`
Name string `gen:"required,notempty,max=120"`
Users []User `gen:"rel=has_many:User"`
CreatedAt time.Time `gen:"auto=create"`
}
//go:build ignore
package specs
import (
"time"
"github.com/google/uuid"
)
type User struct {
_ struct{} `gen:"softdelete"`
ID uuid.UUID `gen:"pk,auto"`
Name string `gen:"required,notempty,max=120"`
Email string `gen:"required,unique,email,max=254"`
OrgID uuid.UUID `gen:"rel=belongs_to:Org"`
CreatedAt time.Time `gen:"auto=create"`
UpdatedAt time.Time `gen:"auto=update"`
}
Generate the project, fetch dependencies and start PostgreSQL:
codebuild build --starter --module example.com/shop --dialect postgres
go mod tidy
docker run --rm -d --name shop-db -e POSTGRES_USER=app -e POSTGRES_PASSWORD=app -e POSTGRES_DB=app -p 5432:5432 postgres:17
export DATABASE_URL='postgres://app:app@localhost:5432/app?sslmode=disable'
go run ./cmd/migrate up
go run ./cmd/api
Call the API:
curl -s --json '{"name":"Acme"}' localhost:8080/orgs
curl -s --json '{"name":"Ann","email":"ann@example.com","orgId":"<org id>"}' localhost:8080/users
curl -s 'localhost:8080/users?email=ann@example.com'
curl -s --json '{"name":"","email":"nope"}' localhost:8080/users
--json (curl 7.82 or newer) sends Content-Type: application/json, which every generated endpoint requires; with older curl use -H 'Content-Type: application/json' -d '...'. The last request answers 422 with a problem document listing every invalid field. Change a spec and run codebuild build again: generated files are refreshed, your files are left alone and a new migration describes the schema change.
Commands
| Command |
Purpose |
codebuild build --starter --module <path> [--dialect d] |
Create a project in the current directory. |
codebuild build |
Regenerate *_gen.go, create missing files, add a migration when the schema changed. |
codebuild check |
Validate specs, configuration and the Go version without writing. |
codebuild plan [--diff] [--exit-code] |
Dry run listing files to create, regenerate or skip, with a diff summary. |
codebuild mcp |
Start the Model Context Protocol server over stdio. |
codebuild version |
Print the version, supported Go versions and dialects. |
Global flags: --json for machine-readable output, --upgrade-go to authorize raising a go directive below 1.26 without a prompt, --dir to point at another project. build and plan also accept --dialect, --change-dialect and --prune.
Exit codes: 0 success, 1 error, 2 usage, 3 invalid spec, 4 unsupported Go version, 5 toolchain too old, 6 file conflict (ownership, outdated plan or a concurrent build), 7 configuration conflict, 8 pending changes (plan --exit-code).
Dialects
postgres (default), sqlserver, mysql and sqlite. The repositories use plain database/sql with SQL written for the selected database: placeholders, RETURNING or OUTPUT INSERTED, pagination syntax, column types, timestamps, identifier quoting and constraint error detection all differ per dialect. The choice is stored in codebuild.json. See docs/dialects.md.
Go versions
Target go directive |
JSON |
UUID |
| 1.26 |
encoding/json |
github.com/google/uuid |
| 1.27 and later |
encoding/json/v2 |
standard library uuid |
Below 1.26 codebuild stops and asks before raising the go directive. See docs/go-versions.md.
How codebuild compares
|
codebuild |
sqlc |
ent |
Goa |
goctl (go-zero) |
| Source of truth |
Go spec structs |
SQL queries and schema |
Go schema code |
Go design DSL |
.api files and SQL |
| HTTP layer |
yes, net/http |
no |
no |
yes, plus gRPC |
yes |
| Persistence |
yes, generated SQL |
yes, your SQL |
yes, ORM client |
no |
yes |
| Migrations |
generated, incremental |
no (bring your own) |
via Atlas |
no |
no |
| Runtime library in your binary |
none |
none |
entgo.io/ent |
goa.design/goa/v3 |
github.com/zeromicro/go-zero |
| OpenAPI |
yes, 3.1 |
no |
via extension |
yes |
yes |
Choose sqlc when you want to write every query yourself and keep full control of SQL; codebuild writes CRUD and relation SQL for you and is less flexible for complex reporting queries. Choose ent when you need graph traversals, eager loading, hooks and privacy policies and accept a runtime library. Choose Goa when the API contract, OpenAPI and gRPC matter more than persistence. Choose goctl when you are adopting the go-zero framework. Choose codebuild when you want a conventional CRUD service in plain standard-library Go that you can keep evolving by hand.
Working with AI agents
codebuild mcp exposes the spec grammar and the list_domains, validate, plan and generate tools. Every starter project contains an AGENTS.md describing the safe workflow: read the grammar, write a spec, validate, plan, get the user's approval, generate. See docs/mcp.md.
Documentation
- Spec reference: every marker with an example and its common error.
- Go versions: capability matrix and upgrade behavior.
- Dialects: SQL differences side by side.
- Authentication: methods, markers, endpoints, configuration and customization.
- Microservices: services, gateway, contracts, security between services, retries, Compose and Kubernetes.
- Running in production: TLS, secrets, backups, migrations, Kubernetes, limits and load test results.
- Observability and CORS: Prometheus metrics, OpenTelemetry traces and cross-origin settings of generated projects.
- File ownership: what is regenerated and what is never touched.
- MCP: client configuration and recommended flow.
- Architecture: internals for contributors.
- Contributing: ground rules, tests and releases.
- Security policy: supported versions and private vulnerability reports.
License
MIT. See LICENSE.