goforge

command module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 5 Imported by: 0

README ยถ

CI Release Go Reference Go Version License PRs Welcome

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 /health for liveness and GET /readyz for readiness (checks dependencies such as the database)
  • ๐Ÿ›‘ Graceful Shutdown - Handles SIGINT/SIGTERM and drains in-flight requests
  • ๐Ÿงญ Modern Routing - Go 1.22+ http.ServeMux patterns like GET /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 config package loads PORT, CORS_ALLOWED_ORIGINS, MAX_BODY_BYTES, and SHUTDOWN_TIMEOUT from 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 strict DecodeJSON that rejects unknown fields
  • ๐Ÿงช Tests and Tooling - Handler and middleware tests, a Makefile, and a golangci-lint config

Optional Features

  • ๐Ÿ“ Structured Logging - log/slog in 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 db package that connects at startup, checks the database is reachable, and closes it on shutdown. For SQL databases it also runs migrations: SQL files in db/migrations are 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_URL joins the config package (it defaults to the local development database), and /readyz returns 503 when the database is unreachable.
  • Proves both storage layers behave the same: each resource's repository_test.go runs one set of tests against the in-memory and the database repositories. SQLite's tests always run, on a temporary file. The others run when TEST_DATABASE_URL is set; make test-db runs 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, and test-db, and a database service in the generated GitHub Actions workflow. SQLite needs none of this: its make db-reset deletes 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.yml and DATABASE_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 generated docker-compose.yml and CI service set GLIBC_TUNABLES=glibc.pthread.rseq=1, which hands rseq to 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:

  1. Go module path - Leave empty to use the app name
  2. 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

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Guidelines

  • Follow Clean Architecture principles
  • Write tests for new features
  • Update documentation
  • Keep commits atomic and descriptive
  • Run go fmt and go vet before 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


โญ 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 resource for 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

โฌ† Back to Top

Documentation ยถ

The Go Gopher

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
di
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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL