README
ยถ
Features โข Installation โข Quick Start โข Adding Resources โข Adding a Database โข Documentation โข Architecture โข Contributing
๐ฏ What is GoForge?
GoForge is a CLI tool that generates production-ready Go HTTP servers using only the standard library: structured logging with log/slog, Go 1.22+ routing, graceful shutdown, tests, linting, CI, and a hardened Dockerfile. Then it keeps helping: goforge add resource adds complete, tested REST resources to your project. Stop copying boilerplate code and start forging quality servers instantly.
Why GoForge?
โ
Production Ready - Graceful shutdown, request IDs, panic recovery, and timeouts
โ
Grows With You - goforge add resource generates CRUD endpoints, storage, business logic, and tests
โ
Zero Dependencies - Generated servers use only the Go standard library
โ
Tested and Linted - Generated projects ship with tests and pass their own golangci-lint config
โ
Verified Output - Every option combination is generated, linted, tested, built, and booted by GoForge's test suite
โ
Ready for CI/CD - Optional GitHub Actions workflow and non-root Docker image
๐ Features
Core Features
- ๐ Health and Readiness -
GET /healthfor liveness andGET /readyzfor readiness (checks dependencies such as the database) - ๐ Graceful Shutdown - Handles SIGINT/SIGTERM and drains in-flight requests
- ๐งญ Modern Routing - Go 1.22+
http.ServeMuxpatterns likeGET /users/{id}, with automatic 405s - ๐ชช Request IDs - Every response carries an
X-Request-ID; incoming IDs are reused for tracing - ๐งฏ Panic Recovery - Panics become 500s and are logged with a stack trace
- โฑ๏ธ Timeouts - Read, write, idle, and read-header timeouts
- โ๏ธ 12-Factor Config - A
configpackage loadsPORT,CORS_ALLOWED_ORIGINS,MAX_BODY_BYTES, andSHUTDOWN_TIMEOUTfrom the environment - ๐ CORS - Opt-in with
CORS_ALLOWED_ORIGINS, including preflight handling - ๐ Body Limits - Request bodies are capped (1 MiB by default) and oversized ones get
413 - ๐งฐ JSON Helpers -
WriteJSON,WriteError, and a strictDecodeJSONthat rejects unknown fields - ๐งช Tests and Tooling - Handler and middleware tests, a Makefile, and a golangci-lint config
Optional Features
- ๐ Structured Logging -
log/slogin text or JSON, with one log line per request - ๐ณ Docker - Multi-stage build, non-root user, health check, and
.dockerignore - ๐ค GitHub Actions CI - Vet, race-enabled tests, lint, and Docker build
- ๐ README - Documentation for the generated project
๐ฆ Installation
Option 1: Go Install
Requires Go 1.26 or newer to install GoForge. Generated projects need Go 1.24 or newer.
go install github.com/Frank5ive/goforge@latest
Option 2: Download a Binary
Prebuilt binaries for Linux, macOS, and Windows (amd64 and arm64) are on the
releases page, with a checksums.txt to verify them.
# Linux/macOS: extract and move onto your PATH
tar -xzf goforge_*_linux_amd64.tar.gz
sudo mv goforge /usr/local/bin/
# Windows: extract the .zip and add goforge.exe to your PATH
Option 3: Build from Source
git clone https://github.com/Frank5ive/goforge.git
cd goforge
go build -o goforge .
Shell Completion
Tab-complete commands and flags in bash, zsh, fish, or PowerShell:
# bash (current session; add to ~/.bashrc to keep it)
source <(goforge completion bash)
# zsh
goforge completion zsh > "${fpath[1]}/_goforge"
# fish
goforge completion fish > ~/.config/fish/completions/goforge.fish
Run goforge completion <shell> --help for details.
โก Quick Start
Generate Your First Server
# Interactive mode: prompts for the module path and features
goforge generate --name=my-api
# Non-interactive mode (scripts and CI)
goforge generate --name=my-api --module=github.com/you/my-api --yes
# Preview the files without writing anything
goforge generate --name=my-api --dry-run --yes
Run Your Server
cd my-api
go run .
Your server is now running at http://localhost:8080 ๐
Test the Health Endpoint
curl http://localhost:8080/health
Response:
{
"status": "healthy",
"timestamp": "2024-11-02T16:43:58Z",
"service": "my-api"
}
๐งฉ Adding Resources
Inside a project created by goforge generate, add a complete REST resource with one command:
goforge add resource product --fields "name:string,price:float,in_stock:bool,image_url:string?"
โ
Added the product resource. Created 7 files:
products/product.go # Product model, Input, Patch, validation rules, Repository interface
products/memory.go # Thread-safe in-memory Repository
products/service.go # Business logic: list, get, create, update, patch, delete
products/handler.go # HTTP handlers and route registration
products/service_test.go
products/handler_test.go
products/requests.http # Example requests to run from your editor
๐ Updated:
server/routes.go # Routes registered automatically
๐ Endpoints:
GET /products?limit=20&offset=0
POST /products
GET /products/{id}
PUT /products/{id}
PATCH /products/{id}
DELETE /products/{id}
Ready to go: the routes are registered in server/routes.go for you, so the endpoints
work as soon as you start (or restart) the server with go run .. No wiring needed. Open
products/requests.http in VS Code (REST Client extension) or a JetBrains IDE to try every
endpoint with one click; it already points at your project's port.
Each resource uses Clean Architectureโstyle layering in a single package: handlers call
the service, the service holds the business rules, and storage sits behind a Repository
interface, so resources move to a database (see Adding a Database)
without touching the service or handlers. Keeping a resource in one package makes it easy to
find and follow.
Fields are name:type pairs. Types: string, int, float, bool, and time
(RFC 3339 in JSON). String fields are required unless marked optional with ?. id,
created_at, and updated_at are added automatically.
Listing is paginated: GET /products?limit=20&offset=40 returns
{"items": [...], "total": 57, "limit": 20, "offset": 40}, oldest first. limit defaults to
20 and is capped at 100.
Updating: PUT replaces every editable field, while PATCH changes only the fields you
send ({"price": 24.5}). Both run the same validation rules.
Responses: 201 with a Location header on create, 204 on delete, 404 for unknown
IDs, 422 with every failed rule listed ({"error":"invalid product: name is required"}),
and 400 for malformed JSON, unknown fields, or invalid limit/offset.
| Flag | Short | Default | Description |
|---|---|---|---|
--fields |
-f |
name:string |
Comma-separated name:type fields |
--plural |
derived | Plural for irregular words, e.g. --plural people for person |
|
--dir |
-d |
. |
Project directory (the one containing go.mod) |
--dry-run |
false |
Show the files that would be created or changed |
๐ Adding a Database
Store your resources in a real database with one command, either when generating
(goforge generate --db <engine>) or later, inside an existing project:
goforge add db postgres # or: mysql, sqlite, mongo
make db-up # start the database in Docker (not needed for SQLite)
go run . # connects and serves your resources from the database
| Engine | Command | Driver | Local database | Good for |
|---|---|---|---|---|
| PostgreSQL | goforge add db postgres |
pgx | postgres:18 in Docker |
Most production APIs |
| MySQL / MariaDB | goforge add db mysql |
go-sql-driver/mysql | mysql:8.4 in Docker |
Teams already on MySQL or MariaDB |
| SQLite | goforge add db sqlite |
modernc.org/sqlite (pure Go) | A file; no server or Docker | Prototypes, small apps, single-server tools |
| MongoDB | goforge add db mongo |
mongo-driver v2 | mongo:8.0 in Docker |
Document-shaped data |
Aliases work too: postgresql, mariadb, sqlite3, mongodb.
What add db does, for every engine:
- Adds a
dbpackage that connects at startup, checks the database is reachable, and closes it on shutdown. For SQL databases it also runs migrations: SQL files indb/migrationsare embedded in the binary and applied in order at startup, each once, behind a lock so two instances never migrate at the same time. - Moves every existing resource to the database. Each gets a repository for the engine and, for SQL databases, a migration that creates its table. Resources you add afterwards use the database automatically.
- Wires it in:
DATABASE_URLjoins theconfigpackage (it defaults to the local development database), and/readyzreturns503when the database is unreachable. - Proves both storage layers behave the same: each resource's
repository_test.goruns one set of tests against the in-memory and the database repositories. SQLite's tests always run, on a temporary file. The others run whenTEST_DATABASE_URLis set;make test-dbruns everything against the database in Docker. - Adds local tooling and CI:
docker-compose.yml(the database, plus the app when the project has a Dockerfile),make db-up,db-down,db-reset, andtest-db, and a database service in the generated GitHub Actions workflow. SQLite needs none of this: itsmake db-resetdeletes the file, and the files are git-ignored. - Adds the driver to
go.mod. The project's minimum Go version rises to what the driver requires (Go 1.25 for PostgreSQL and MongoDB, Go 1.26 for SQLite).
Edits are made only at marker comments and are all planned before anything is written. If
any step fails, including downloading the driver, the project is left exactly as it was. Use
--dry-run to preview the changes.
Already running a database locally? The Docker databases use the standard ports (5432, 3306, 27017). If one is taken, stop the local server or change the port in
docker-compose.ymlandDATABASE_URL.
MongoDB on Linux 6.19 to 7.0.13. MongoDB refuses to start on these kernels while its allocator uses
rseq(SERVER-121912). The generateddocker-compose.ymland CI service setGLIBC_TUNABLES=glibc.pthread.rseq=1, which handsrseqto glibc so MongoDB starts at a small cost in allocator speed. Set the same variable for a MongoDB you run some other way, or use kernel 7.0.14 or later.
๐ Documentation
Command Line Options
goforge generate [flags]
Flags
| Flag | Short | Default | Description |
|---|---|---|---|
--name |
-n |
myapp |
Name of the application (also the project directory) |
--module |
-m |
app name | Go module path, e.g. github.com/acme/my-api |
--port |
-p |
8080 |
Default port (the PORT env var overrides it at runtime) |
--output |
-o |
. |
Directory to create the project in |
--logger |
true |
Include request logging | |
--docker |
true |
Include a Dockerfile | |
--readme |
true |
Include a README.md | |
--yes |
-y |
false |
Skip prompts and use flag values and defaults |
--dry-run |
false |
List the files that would be created without writing anything | |
--git |
false |
Run git init in the new project |
|
--db |
none | Store data in a database: postgres, mysql, sqlite, or mongo (same as goforge add db <engine>) |
Interactive Prompts
When running in a terminal without --yes, GoForge asks for anything not already set by flag:
- Go module path - Leave empty to use the app name
- Features - Toggle request logging, Dockerfile, and README
Prompts need a terminal. In scripts and CI, pass --yes and set options with flags.
If generation fails partway, GoForge removes the partially created project directory.
Examples
Basic Server
goforge generate --name=hello-api --port=3000
Minimal Server Without Docker or Logging
goforge generate --name=worker --logger=false --docker=false --yes
CI/CD Ready
goforge generate --name=ci-api --module=github.com/acme/ci-api --output=./services --yes --git
๐๏ธ Generated Project Structure
my-api/
โโโ main.go # Entry point: startup and graceful shutdown
โโโ config/ # Settings from environment variables
โโโ server/
โ โโโ server.go # HTTP server and middleware chain
โ โโโ routes.go # Route registration (add endpoints here)
โ โโโ middleware.go # Request ID, panic recovery, request logging
โ โโโ server_test.go
โโโ handlers/
โ โโโ health.go # GET /health
โ โโโ respond.go # JSON response helper
โ โโโ health_test.go
โโโ logger/ # slog setup from LOG_LEVEL / LOG_FORMAT (optional)
โโโ Makefile # run, build, test, cover, lint, docker-build, ...
โโโ .golangci.yml # golangci-lint v2 config
โโโ .github/workflows/ci.yml # GitHub Actions CI (optional)
โโโ Dockerfile # Multi-stage, non-root (optional)
โโโ .dockerignore # (optional)
โโโ README.md # (optional)
โโโ .gitignore
โโโ go.mod
๐จ GoForge Architecture
GoForge itself is built following Clean Architecture principles:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ External Interfaces โ
โ (HTTP Handlers, CLI, Database Adapters) โ
โโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Application Business Rules โ
โ (Use Cases) โ
โโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโดโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Enterprise Business Rules โ
โ (Entities, Interfaces) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Key Principles
โ
Dependency Inversion - Core logic doesn't depend on frameworks
โ
Separation of Concerns - Each layer has a single responsibility
โ
Testability - Easy to mock and test components
โ
Flexibility - Swap implementations without affecting business logic
๐ง Advanced Usage
Custom Port Configuration
goforge generate --name=custom-api --port=3000
Generate Multiple Services
# User service
goforge generate --name=user-service --port=8001 --output=./services
# Order service
goforge generate --name=order-service --port=8002 --output=./services
# Payment service
goforge generate --name=payment-service --port=8003 --output=./services
Docker Deployment
# Generate with Dockerfile
goforge generate --name=my-api --port=8080
cd my-api
# Build Docker image
docker build -t my-api:latest .
# Run container
docker run -p 8080:8080 my-api:latest
# Test
curl http://localhost:8080/health
๐งช Testing
GoForge's test suite generates a project for every combination of options using the
real embedded templates, then checks that each one is gofmt-clean, passes go vet,
compiles, serves /health, and shuts down gracefully on SIGTERM.
# Full suite, including the end-to-end generation test
go test ./...
# Skip the end-to-end test for a quick run
go test -short ./...
๐ ๏ธ Development
Project Stack
- Language: Go 1.26+
- CLI Framework: Cobra
- Interactive Prompts: Huh
- Architecture: Clean Architecture
- Testing: Go testing package
- Template Engine: Go text/template
Building GoForge
# Clone repository
git clone https://github.com/Frank5ive/goforge.git
cd goforge
# Install dependencies
go mod download
# Build
go build -o goforge .
# Run tests
go test ./...
# Run with coverage
go test -cover ./...
Project Structure
goforge/
โโโ cmd/ # CLI commands (Cobra)
โโโ internal/
โ โโโ domain/ # Business entities & interfaces
โ โโโ usecase/ # Application logic
โ โโโ infrastructure/ # Template & file operations
โ โโโ di/ # Dependency injection
โโโ templates/ # Go server templates
โโโ main.go # Entry point
See ARCHITECTURE.md for how generation works and how to add templates or options.
๐ค Contributing
We welcome contributions! Here's how you can help:
Ways to Contribute
- ๐ Report Bugs - Open an issue with reproduction steps
- โจ Suggest Features - Share your ideas for improvements
- ๐ Improve Documentation - Fix typos, add examples
- ๐ง Submit PRs - Fix bugs or implement features
Contribution Process
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Guidelines
- Follow Clean Architecture principles
- Write tests for new features
- Update documentation
- Keep commits atomic and descriptive
- Run
go fmtandgo vetbefore committing
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
What This Means
โ
Commercial use allowed
โ
Modification allowed
โ
Distribution allowed
โ
Private use allowed
๐ Acknowledgments
- Inspired by Clean Architecture by Uncle Bob
- Built with Cobra CLI framework
- Uses Huh for interactive prompts
- The Go gopher was designed by Renรฉe French and is licensed under CC BY 4.0. The pixel-art gopher in GoForge's terminal banner is adapted from it.
๐ฎ Support & Contact
- ๐ Issues: GitHub Issues
- ๐ฌ Discussions: GitHub Discussions
โญ Star History
If you find GoForge useful, please consider giving it a star! โญ
It helps others discover the project and motivates continued development.
๐บ๏ธ Roadmap
v0.1 (Current)
- โ Server generation with health checks, graceful shutdown, and middleware
- โ Structured logging, tests, linting, CI, and Docker
- โ Environment-based configuration, CORS, and request body limits
- โ
goforge add resourcefor tested CRUD resources - โ
Databases: PostgreSQL, MySQL/MariaDB, SQLite, and MongoDB (
goforge add db <engine>)
Next
- Authentication middleware (JWT)
- OpenAPI documentation generated from resources
- Homebrew tap
Future
- gRPC server support
- GraphQL server support
- Kubernetes manifests
- Monitoring/metrics (Prometheus)
- Distributed tracing (OpenTelemetry)
Built with โค๏ธ by Frank Gondwe
Documentation
ยถ
There is no documentation for this package.
Directories
ยถ
| Path | Synopsis |
|---|---|
|
Package cmd implements the goforge command-line interface.
|
Package cmd implements the goforge command-line interface. |
|
internal
|
|
|
infrastructure/gomod
Package gomod manages a generated project's Go module dependencies with the go command.
|
Package gomod manages a generated project's Go module dependencies with the go command. |
|
tools
|
|
|
release
command
Command release enforces the release rules for the Release workflow.
|
Command release enforces the release rules for the Release workflow. |