Ginger is a safe project framework for Go. It understands your codebase, keeps your
structure organized, and evolves your application without overwriting your work.
Ginger é um framework seguro para projetos Go. Ele entende sua codebase, mantém
sua estrutura organizada e evolui sua aplicação sem sobrescrever seu trabalho.
⚡ Quick Start
# 1. Install
go install github.com/fvmoraes/ginger/cmd/ginger@latest
# 2. Create a project
ginger new foobar --service
cd foobar && go mod tidy && ginger run
# 3. Or initialize an existing project
cd my-existing-project
ginger init # detects structure, creates ginger.yaml
ginger inspect # analyze project
Your API is now running at http://localhost:8080
# Safe generation — plan before apply
ginger add swagger --plan # see what would be created
ginger add postgres --plan
ginger generate crud foobar --plan
ginger generate test foobar # Generate tests for handler/service/adapter
ginger generate smoke-test # Generate app smoke test
ginger add postgres # Add PostgreSQL
ginger add redis # Add Redis
ginger build # Compile → bin/foobar
📖 Full guide: Getting Started (5 min) | Quick Reference
Positioning / Posicionamento
Ginger is not just another web framework. It is a project framework + safe generator + structure toolkit.
|
Ginger |
Gin/Echo/Fiber |
Cobra |
| HTTP framework |
✓ |
✓ |
✗ |
| CLI framework |
✓ |
✗ |
✓ |
| Project structure |
✓ |
✗ |
✗ |
| Works with existing code |
✓ |
✗ |
✗ |
| Safe generation (plan → apply) |
✓ |
✗ |
✗ |
| Managed regions |
✓ |
✗ |
✗ |
| Auto-detect structure |
✓ |
✗ |
✗ |
Safe evolution flow
All project-aware commands resolve the root from ginger.yaml, go.mod, or
.git, including when invoked from a nested directory. Plan mode never writes:
ginger init
ginger inspect
ginger add swagger --plan
ginger generate tests --scan --plan
ginger doctor
See examples/existing-api for a non-Ginger
net/http project used to validate custom paths, route discovery, managed
patches, and preservation of existing tests.
English
Português
🇺🇸 English
What is Ginger?
Ginger is a safe project framework for Go. It handles project structure, scaffolding, and generation so you can focus on business logic instead of repetitive setup. It does not hide Go — it organizes it.
Core Principles
- Minimal dependencies — only what is strictly necessary
- Fast compilation — no magic, no reflection-heavy DI
- Idiomatic Go — standard interfaces, standard patterns
- Simple CLI — scaffold, generate, run, build
- Clear project structure — every team member knows where things live
- Developer productivity — less setup, more shipping
Project Structure
Every project created with ginger new starts minimal and grows on demand.
Template types
| Flag |
Entry point |
Best for |
| (none) |
cmd/<name>/ |
Generic Go programs, scripts |
--service |
cmd/<name>/ |
HTTP APIs and microservices |
--worker |
cmd/<name>-worker/ |
Background jobs and message consumers |
--cli |
cmd/<name>/ |
User-facing CLI tools (Cobra-based) |
Service project (--service)
foobar/ # ginger new foobar --service
├── cmd/foobar/main.go
├── internal/
│ ├── api/
│ │ ├── router.go # Centralized route setup (/api/v1 group)
│ │ ├── handlers/health.go
│ │ └── middlewares/ # request_id.go and more
│ ├── ports/ports.go # Hexagonal Store interface
│ ├── adapters/memory_store.go # In-memory adapter for dev/test
│ ├── models/ # Domain models
│ └── config/config.go
├── configs/app.yaml
├── migrations/
├── tests/integration/health_test.go
├── devops/docker/ devops/kubernetes/ devops/helm/ devops/pipelines/
├── Makefile .env.example .editorconfig
└── .gitignore
Worker project (--worker)
foobar/ # ginger new foobar --worker
├── cmd/foobar-worker/main.go
├── internal/
│ ├── worker/worker.go # Run loop with backoff
│ │ handler.go # Handler interface + DefaultHandler
│ ├── ports/ports.go # MessageConsumer, MessagePublisher, JobStore
│ ├── adapters/memory_consumer.go
│ └── services/processor.go
├── tests/integration/worker_test.go
├── devops/docker/ devops/kubernetes/ devops/helm/ devops/pipelines/
├── Makefile .env.example .editorconfig
└── .gitignore
CLI project (--cli)
foobar/ # ginger new foobar --cli
├── cmd/foobar/main.go # Calls commands.Execute()
├── internal/
│ ├── commands/root.go # Root Cobra command (--verbose, --output, --config)
│ │ version.go # version subcommand with ldflags support
│ ├── ports/ports.go # FileReader, ConfigLoader interfaces
│ ├── adapters/filesystem.go # Filesystem adapter
│ └── config/config.go # YAML config loader
├── pkg/output/formatter.go # json/table/text output
├── .goreleaser.yaml # Cross-platform release config
├── Makefile .editorconfig
└── .gitignore
Extra directories such as platform/, docs/, additional layers, and more devops/ assets appear only when you generate or add them.
Getting Started
Install the CLI
The Ginger core requires Go 1.22+. Optional capabilities may declare a
higher requirement; currently OpenTelemetry requires Go 1.25+.
Option 1: Go install (recommended)
go install github.com/fvmoraes/ginger/cmd/ginger@latest
# If `ginger` is not found, export your Go bin to PATH
export PATH="$(go env GOPATH)/bin:$PATH"
Option 2: One-line install script
# installs the latest release by default
curl -fsSL https://raw.githubusercontent.com/fvmoraes/ginger/main/install.sh | bash
Option 3: Download binary
Download from releases page, make executable, and move to your PATH.
Option 4: Build from source
git clone https://github.com/fvmoraes/ginger
cd ginger
go build -o /usr/local/bin/ginger ./cmd/ginger
Create a new project
ginger new foobar --service # Service → cmd/foobar
ginger new foobar -s # same as --service
ginger new foobar --worker # Worker → cmd/foobar-worker
ginger new foobar -w # same as --worker
ginger new foobar --cli # CLI → cmd/foobar
ginger new foobar -c # same as --cli
ginger new foobar # Generic → cmd/foobar
cd foobar
go mod tidy
ginger run
Your API is now running at http://localhost:8080.
Quick test:
curl http://localhost:8080/health
Next steps: See Getting Started Guide for a complete tutorial.
CLI Reference
ginger new <name> Scaffold a generic project → cmd/<name>
ginger new <name> --service | -s Service project → cmd/<name>
ginger new <name> --worker | -w Worker project → cmd/<name>-worker
ginger new <name> --cli | -c CLI project → cmd/<name>
ginger init [--force] Initialize ginger.yaml in an existing project
ginger inspect [--json] Analyze current project structure
ginger run Run the app in dev mode
ginger build [output] Build the binary
ginger generate crud <name> Generate model+handler+service+port+adapter
ginger generate command <name> Generate a Cobra subcommand for --cli projects
ginger generate handler <name> Generate a worker handler for --worker projects
ginger generate service <name> Generate a business service for --cli/--worker projects
ginger generate test <name> Generate handler+service+repository tests
ginger generate tests --scan Scan and generate tests for existing code
ginger generate smoke-test Generate app smoke test under tests/integration
ginger generate swagger [name] Generate docs/openapi.json starter or CRUD example
ginger add <integration> Add an integration to the project
ginger doctor Run project health diagnostics
ginger docs [--plan] Generate documentation based on project structure
ginger version Print ginger x.y.z
ginger help Show help
Safe generation flags (available on `add`, `generate`, `docs`):
--plan Preview what would be done without applying
--force Overwrite existing files
Integrations (ginger add)
| Category |
Command |
Package |
| Databases |
ginger add postgres |
github.com/lib/pq |
|
ginger add mysql |
github.com/go-sql-driver/mysql |
|
ginger add sqlite |
github.com/mattn/go-sqlite3 |
|
ginger add sqlserver |
github.com/microsoft/go-mssqldb |
| ORMs |
ginger add gorm |
gorm.io/gorm |
|
ginger add sqlx |
github.com/jmoiron/sqlx |
|
ginger add bun |
github.com/uptrace/bun |
| NoSQL |
ginger add couchbase |
github.com/couchbase/gocb/v2 |
|
ginger add mongodb |
go.mongodb.org/mongo-driver/v2/mongo |
| Analytical |
ginger add clickhouse |
github.com/ClickHouse/clickhouse-go/v2 |
| Cache |
ginger add redis |
github.com/redis/go-redis/v9 |
| Messaging |
ginger add kafka |
github.com/segmentio/kafka-go |
|
ginger add rabbitmq |
github.com/rabbitmq/amqp091-go |
|
ginger add nats |
github.com/nats-io/nats.go |
|
ginger add pubsub |
cloud.google.com/go/pubsub/v2 |
| Protocols |
ginger add grpc |
google.golang.org/grpc |
|
ginger add mcp |
stdlib only |
| Real-time |
ginger add sse |
stdlib only |
|
ginger add websocket |
stdlib only |
| Observ. |
ginger add otel |
go.opentelemetry.io/otel |
|
ginger add prometheus |
github.com/prometheus/client_golang |
| Docs |
ginger add swagger |
stdlib + Swagger UI CDN |
Code generation example
ginger generate crud foobar
ginger generate swagger foobar
This creates a complete CRUD with:
- Model, Handler, Service, Repository
- Ready to wire in your router
For API docs, you can also generate an OpenAPI example file:
ginger add swagger
ginger generate swagger foobar
You can also generate tests separately:
ginger generate test foobar
ginger generate smoke-test
Learn more: Getting Started Guide
Core Packages
pkg/app — Application bootstrap
cfg, _ := config.Load("configs/app.yaml")
app := gingerapp.New(cfg)
app.Router.Use(middleware.CORS())
app.OnStop(func(ctx context.Context) error {
return db.Close()
})
app.Run() // blocks, handles SIGINT/SIGTERM
pkg/router — HTTP routing
Wraps net/http ServeMux with method helpers, route groups, and JSON utilities.
v1 := app.Router.Group("/api/v1")
v1.GET("/users", listUsers)
v1.POST("/users", createUser)
// JSON response
router.JSON(w, http.StatusOK, payload)
// Standardized error response
router.Error(w, apperrors.NotFound("user not found"))
// Decode request body
router.Decode(r, &input)
pkg/errors — Typed errors
apperrors.NotFound("user not found") // 404
apperrors.BadRequest("invalid input") // 400
apperrors.Unauthorized("token expired") // 401
apperrors.Forbidden("access denied") // 403
apperrors.Conflict("email already exists") // 409
apperrors.Internal(err) // 500
All errors serialize to a consistent JSON shape:
{
"code": "NOT_FOUND",
"message": "user not found"
}
pkg/middleware — Built-in middlewares
middleware.Logger(log) // structured request logging
middleware.Recover(log) // panic recovery → 500
middleware.RequestID() // injects X-Request-ID
// Simple allow-all CORS
middleware.CORS()
// Fine-grained CORS config
middleware.CORS(middleware.CORSConfig{
AllowedOrigins: []string{"https://app.example.com"},
AllowedHeaders: []string{"Content-Type", "Authorization"},
AllowCredentials: true,
MaxAge: 86400,
})
// Compose
middleware.Chain(mw1, mw2, mw3)
pkg/health — Health checks
h := health.New()
h.Register(database.NewChecker(db)) // plug in any Checker
// Automatically mounted at GET /health
// Returns 200 if all checks pass, 503 otherwise
{
"healthy": true,
"checks": [{ "name": "database", "healthy": true }],
"duration": "1.2ms"
}
pkg/config — Configuration
Loads from YAML file first, then overrides with environment variables.
cfg, err := config.Load("configs/app.yaml")
// cfg.App.Name, cfg.HTTP.Port, cfg.Database.DSN, etc.
pkg/logger — Structured logging
Built on log/slog. Ginger always emits structured multi-line JSON logs.
log := logger.New("info", "json")
log.Info("user_created", "id", user.ID)
log.Error("db_error", "error", err)
// Context-aware
ctx = logger.WithContext(ctx, log)
logger.FromContext(ctx).Info("handled")
pkg/telemetry — OpenTelemetry
Telemetry is an optional submodule so importing Ginger's core does not pull an
OpenTelemetry SDK or raise the application's Go requirement. Install it only
when needed with go get github.com/fvmoraes/ginger/pkg/telemetry (Go 1.25+).
provider, err := telemetry.Setup(ctx, telemetry.Config{
ServiceName: cfg.App.Name,
ServiceVersion: cfg.App.Version,
Exporter: "stdout", // swap for "otlp" in production
})
defer provider.Shutdown(ctx)
tracer := telemetry.Tracer("foobar")
ctx, span := tracer.Start(ctx, "operation-name")
defer span.End()
pkg/testhelper — Test utilities
rec := testhelper.NewRequest(t, handler, http.MethodGet, "/users").Do()
testhelper.AssertStatus(t, rec, http.StatusOK)
var result []User
testhelper.DecodeJSON(t, rec, &result)
pkg/response — JSON response envelopes
Consistent JSON shapes for all API responses — frontend clients can handle them generically.
// Single resource — { "data": {...} }
response.OK(w, user)
response.Created(w, user)
// Paginated list — { "data": [...], "pagination": { "page": 1, "per_page": 20, "total": 100, "total_pages": 5 } }
response.Paginated(w, users, page, perPage, total)
// 204 No Content
response.NoContent(w)
pkg/sse — Server-Sent Events
One-way server→client streaming over plain HTTP. Ideal for live feeds, notifications, and progress updates.
func streamHandler(w http.ResponseWriter, r *http.Request) {
stream, err := sse.New(w)
if err != nil {
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
for {
select {
case <-r.Context().Done():
return
case event := <-eventCh:
stream.Send(sse.Event{Type: "update", Data: event})
}
}
}
Nginx buffering is disabled automatically (X-Accel-Buffering: no). Clients reconnect using the id field.
pkg/ws — WebSocket
Bidirectional real-time communication. Zero external dependencies — implemented over net/http hijack + RFC 6455 framing.
func chatHandler(w http.ResponseWriter, r *http.Request) {
ws.Handle(w, r, func(conn *ws.Conn) {
for {
var msg ws.Message
if err := conn.Recv(&msg); err != nil {
return // client disconnected
}
conn.Send(ws.Message{Type: "echo", Data: msg.Data})
}
})
}
Use ginger add sse or ginger add websocket to scaffold a ready-to-use handler in your project.
Example App
The example/ directory contains a complete User CRUD API demonstrating the full Ginger stack:
example/
├── cmd/app/main.go # wires everything together
├── internal/
│ ├── models/user.go # User, CreateUserInput, UpdateUserInput
│ └── api/
│ ├── handlers/user_handler.go # HTTP layer
│ ├── services/user_service.go # Business logic
│ └── repositories/user_repository.go # Data access
└── configs/app.yaml
cd example
go mod tidy
go run ./cmd/app
# Create a user
curl -X POST http://localhost:8080/api/v1/users \
-H "Content-Type: application/json" \
-d '{"name":"Alice","email":"alice@example.com"}'
# List users
curl http://localhost:8080/api/v1/users
# Health check
curl http://localhost:8080/health
Configuration
configs/app.yaml:
app:
name: foobar
env: development
version: 0.1.0
http:
host: 0.0.0.0
port: 8080
shutdown_timeout: 30 # seconds
database:
driver: postgres
dsn: postgres://<user>:<password>@localhost:5432/foobar?sslmode=disable
max_open: 25
max_idle: 5
log:
level: info # debug | info | warn | error
format: json # compatibility field; Ginger logs JSON only
All fields can be overridden with environment variables:
| Env var |
Config field |
APP_NAME |
app.name |
APP_ENV |
app.env |
APP_VERSION |
app.version |
HTTP_HOST |
http.host |
HTTP_PORT |
http.port |
DATABASE_DRIVER |
database.driver |
DATABASE_DSN |
database.dsn |
LOG_LEVEL |
log.level |
LOG_FORMAT |
log.format (compatibility only) |
Observability
OpenTelemetry is available as an opt-in capability/submodule. The default exporter writes traces to stdout. Swap it for OTLP to send to Jaeger, Tempo, or any OTel-compatible backend.
provider, _ := telemetry.Setup(ctx, telemetry.Config{
ServiceName: "foobar",
Exporter: "otlp", // configure OTEL_EXPORTER_OTLP_ENDPOINT env var
})
Docker & Kubernetes
A DevOps bundle is generated only for project types that need it. For service, Ginger creates the full bundle and worker gets the Docker-oriented subset:
devops/docker/Dockerfile
devops/docker/docker-compose.yml
devops/kubernetes/deployment.yaml
devops/helm/...
devops/pipelines/ci.yaml
The generated Dockerfile uses a multi-stage build:
docker build -f devops/docker/Dockerfile -t foobar:latest .
docker run -p 8080:8080 foobar:latest
A Kubernetes Deployment + Service template is available at devops/kubernetes/deployment.yaml. It includes readiness and liveness probes pointed at /health, resource limits, and a ClusterIP service.
⚡ Cheat Sheet — Essential Commands
Create and Run
ginger new foobar --service # Create service project → cmd/foobar
ginger new foobar -s # Same as --service
cd foobar && go mod tidy # Install deps
ginger run # Run (dev)
ginger build # Build (prod)
Generate Code
ginger generate crud foobar # Complete CRUD base
ginger generate test foobar # Resource tests
ginger generate smoke-test # App smoke test
ginger generate swagger foobar # OpenAPI example
Add Integrations
ginger add postgres # PostgreSQL
ginger add redis # Redis
ginger add kafka # Kafka
ginger add grpc # gRPC
Test and Validate
go test ./... # Run tests
ginger doctor # Diagnose project
go vet ./... # Check code
Docker
docker build -f devops/docker/Dockerfile -t foobar . # Build image
docker run -p 8080:8080 foobar # Run container
docker compose -f devops/docker/docker-compose.yml up -d # Run with deps
Kubernetes
kubectl apply -f devops/kubernetes/ # Deploy
kubectl get pods # View pods
kubectl logs -f deploy/foobar # View logs
More commands: Quick Reference
📚 Complete Documentation
Ginger comes with comprehensive, in-depth documentation covering every aspect of the framework:
Deep dive into Ginger's architecture, design philosophy, and code patterns:
- Component diagram and request flow
- Layer responsibilities (Handler → Service → Repository)
- Dependency injection patterns
- Error handling strategies
- Naming conventions and project structure
Complete API documentation for every core package with examples:
pkg/app — Application bootstrap and lifecycle
pkg/router — HTTP routing and helpers
pkg/middleware — Built-in middlewares (Logger, CORS, Recover, RequestID)
pkg/errors — Typed errors with HTTP status mapping
pkg/response — JSON envelopes for consistent API responses
pkg/sse — Server-Sent Events for real-time streaming
pkg/ws — WebSocket for bidirectional communication
pkg/config, pkg/logger, pkg/database, pkg/health, pkg/telemetry
How to add databases, cache, messaging, and protocols:
- Databases: PostgreSQL, MySQL, SQLite, SQL Server, ClickHouse
- NoSQL: MongoDB, Couchbase
- Cache: Redis
- Messaging: Kafka, RabbitMQ, NATS, Google Pub/Sub
- Protocols: gRPC, MCP (Model Context Protocol)
- Real-time: SSE, WebSocket
- Observability: OpenTelemetry, Prometheus
Testing strategies, patterns, and best practices:
- Unit tests, integration tests, E2E tests
- Mocking patterns (manual and testify)
- Table-driven tests
- Test helpers and utilities
- Coverage reporting
- CI/CD integration (GitHub Actions, GitLab CI)
Production deployment with Docker, Kubernetes, and Helm:
- Docker multi-stage builds and optimizations
- Docker Compose for local development
- Kubernetes manifests (Deployment, Service, ConfigMap, Secrets)
- Helm charts for multi-environment deployments
- CI/CD pipelines (GitHub Actions, GitLab CI)
- Health checks, monitoring, and troubleshooting
🇧🇷 Português
O que é o Ginger?
Ginger é um framework seguro para projetos Go. Ele cuida da estrutura, scaffolding e geração de código para que você foque na lógica de negócio em vez de setup repetitivo. Ele não esconde o Go — ele o organiza.
Princípios
- Dependências mínimas — apenas o estritamente necessário
- Compilação rápida — sem mágica, sem DI pesada em reflection
- Go idiomático — interfaces padrão, padrões padrão
- CLI simples — scaffold, generate, run, build
- Estrutura de projeto clara — todo membro da equipe sabe onde as coisas ficam
- Produtividade do desenvolvedor — menos setup, mais entrega
Estrutura do Projeto
Todo projeto criado com ginger new começa enxuto e cresce sob demanda. Para --service, o ponto de partida é:
foobar/ # ginger new foobar --service
├── cmd/
│ └── foobar/ # entrypoint principal
│ └── main.go # Ponto de entrada da aplicação
├── internal/
│ ├── api/
│ │ ├── handlers/ # Começa com health.go
│ │ ├── middlewares/
│ │ └── router.go
│ ├── adapters/
│ ├── ports/
│ ├── models/
│ └── config/
├── configs/
│ └── app.yaml # Configuração da aplicação
├── migrations/
├── tests/integration/
├── devops/
│ ├── docker/ # Dockerfile, compose, Prometheus config
│ ├── kubernetes/ # Samples de Deployment
│ ├── helm/ # Helm chart
│ └── pipelines/ # Samples de CI/CD
├── Makefile
├── .env.example
└── .editorconfig
Diretórios como platform/, tests/, docs/, camadas extras em internal/api/... e mais assets em devops/ surgem sob demanda, conforme você usa ginger generate e ginger add.
Começando
Instalar a CLI
O core do Ginger requer Go 1.22+. Capabilities opcionais podem exigir uma
versão maior; atualmente OpenTelemetry requer Go 1.25+.
Opção 1: Go install (recomendado)
go install github.com/fvmoraes/ginger/cmd/ginger@latest
# Se `ginger` não for encontrado, exporte o bin do Go no PATH
export PATH="$(go env GOPATH)/bin:$PATH"
Opção 2: Script de instalação
# instala a latest release por padrão
curl -fsSL https://raw.githubusercontent.com/fvmoraes/ginger/main/install.sh | bash
Opção 3: Download do binário
Baixe da página de releases, torne executável e mova para seu PATH.
Opção 4: Build do código fonte
git clone https://github.com/fvmoraes/ginger
cd ginger
go build -o /usr/local/bin/ginger ./cmd/ginger
Criar um novo projeto
ginger new foobar --service # Service → cmd/foobar
ginger new foobar -s # igual a --service
ginger new foobar --worker # Worker → cmd/foobar-worker
ginger new foobar -w # igual a --worker
ginger new foobar --cli # CLI → cmd/foobar
ginger new foobar -c # igual a --cli
ginger new foobar # Genérico → cmd/foobar
cd foobar
go mod tidy
ginger run
Sua API estará rodando em http://localhost:8080.
Endpoints disponíveis imediatamente:
| Método |
Caminho |
Descrição |
| GET |
/health |
Health check |
| GET |
/api/v1/... |
Grupo base para suas rotas da aplicação |
Referência da CLI
ginger new <nome> Scaffold genérico → cmd/<nome>
ginger new <nome> --service | -s Projeto Service → cmd/<nome>
ginger new <nome> --worker | -w Projeto Worker → cmd/<nome>-worker
ginger new <nome> --cli | -c Projeto CLI → cmd/<nome>
ginger init [--force] Inicializa ginger.yaml em um projeto existente
ginger inspect [--json] Analisa a estrutura do projeto atual
ginger run Executa a aplicação em modo dev
ginger build [saída] Compila o binário
ginger generate crud <nome> Gera model+handler+service+port+adapter
ginger generate command <nome> Gera um subcomando Cobra para projetos --cli
ginger generate handler <nome> Gera um worker handler para projetos --worker
ginger generate service <nome> Gera um serviço de negócio para projetos --cli/--worker
ginger generate test <nome> Gera testes de handler+service+adapter
ginger generate tests --scan Escaneia e gera testes para código existente
ginger generate smoke-test Gera smoke test da aplicação
ginger generate swagger [nome] Gera docs/openapi.json base ou exemplo CRUD
ginger add <integração> Adiciona uma integração ao projeto
ginger doctor Diagnóstico de saúde do projeto
ginger docs [--plan] Gera documentação baseada na estrutura do projeto
ginger version Exibe ginger x.y.z
ginger help Exibe a ajuda
Flags de geração segura (disponíveis em `add`, `generate`, `docs`):
--plan Visualiza o que seria feito sem aplicar
--force Sobrescreve arquivos existentes
Integrações (ginger add)
| Categoria |
Comando |
Pacote |
| Bancos |
ginger add postgres |
github.com/lib/pq |
|
ginger add mysql |
github.com/go-sql-driver/mysql |
|
ginger add sqlite |
github.com/mattn/go-sqlite3 |
|
ginger add sqlserver |
github.com/microsoft/go-mssqldb |
| ORMs |
ginger add gorm |
gorm.io/gorm |
|
ginger add sqlx |
github.com/jmoiron/sqlx |
|
ginger add bun |
github.com/uptrace/bun |
| NoSQL |
ginger add couchbase |
github.com/couchbase/gocb/v2 |
|
ginger add mongodb |
go.mongodb.org/mongo-driver/v2/mongo |
| Analítico |
ginger add clickhouse |
github.com/ClickHouse/clickhouse-go/v2 |
| Cache |
ginger add redis |
github.com/redis/go-redis/v9 |
| Mensageria |
ginger add kafka |
github.com/segmentio/kafka-go |
|
ginger add rabbitmq |
github.com/rabbitmq/amqp091-go |
|
ginger add nats |
github.com/nats-io/nats.go |
|
ginger add pubsub |
cloud.google.com/go/pubsub/v2 |
| Protocolos |
ginger add grpc |
google.golang.org/grpc |
|
ginger add mcp |
stdlib only |
| Tempo real |
ginger add sse |
stdlib only |
|
ginger add websocket |
stdlib only |
| Docs |
ginger add swagger |
stdlib + Swagger UI CDN |
| Observ. |
ginger add otel |
go.opentelemetry.io/otel |
|
ginger add prometheus |
github.com/prometheus/client_golang |
Exemplo de geração de código
ginger generate crud foobar
ginger generate test foobar
ginger generate swagger foobar
Isso cria:
internal/models/foobar.go
internal/api/handlers/foobar_handler.go
internal/services/foobar_service.go
internal/ports/foobar_repository.go
internal/adapters/foobar_memory_repository.go
docs/openapi.json
Cada arquivo já vem com a interface correta, construtor e stubs de métodos — pronto para preencher.
Pacotes Principais
pkg/app — Bootstrap da aplicação
cfg, _ := config.Load("configs/app.yaml")
app := gingerapp.New(cfg)
app.Router.Use(middleware.CORS())
app.OnStop(func(ctx context.Context) error {
return db.Close()
})
app.Run() // bloqueia, trata SIGINT/SIGTERM
pkg/router — Roteamento HTTP
Encapsula o net/http ServeMux com helpers de método, grupos de rotas e utilitários JSON.
v1 := app.Router.Group("/api/v1")
v1.GET("/usuarios", listarUsuarios)
v1.POST("/usuarios", criarUsuario)
// Resposta JSON
router.JSON(w, http.StatusOK, payload)
// Resposta de erro padronizada
router.Error(w, apperrors.NotFound("usuário não encontrado"))
// Decodificar body da requisição
router.Decode(r, &input)
pkg/errors — Erros tipados
apperrors.NotFound("usuário não encontrado") // 404
apperrors.BadRequest("entrada inválida") // 400
apperrors.Unauthorized("token expirado") // 401
apperrors.Forbidden("acesso negado") // 403
apperrors.Conflict("email já cadastrado") // 409
apperrors.Internal(err) // 500
Todos os erros serializam para um formato JSON consistente:
{
"code": "NOT_FOUND",
"message": "usuário não encontrado"
}
pkg/middleware — Middlewares embutidos
middleware.Logger(log) // log estruturado de requisições
middleware.Recover(log) // recuperação de panic → 500
middleware.RequestID() // injeta X-Request-ID
// CORS permissivo (allow-all)
middleware.CORS()
// CORS com configuração detalhada
middleware.CORS(middleware.CORSConfig{
AllowedOrigins: []string{"https://app.exemplo.com"},
AllowedHeaders: []string{"Content-Type", "Authorization"},
AllowCredentials: true,
MaxAge: 86400,
})
// Composição
middleware.Chain(mw1, mw2, mw3)
pkg/health — Health checks
h := health.New()
h.Register(database.NewChecker(db)) // implemente a interface Checker
// Montado automaticamente em GET /health
// Retorna 200 se todos os checks passam, 503 caso contrário
{
"healthy": true,
"checks": [{ "name": "database", "healthy": true }],
"duration": "1.2ms"
}
pkg/config — Configuração
Carrega do arquivo YAML primeiro, depois sobrescreve com variáveis de ambiente.
cfg, err := config.Load("configs/app.yaml")
// cfg.App.Name, cfg.HTTP.Port, cfg.Database.DSN, etc.
pkg/logger — Log estruturado
Construído sobre log/slog. O Ginger sempre emite logs estruturados em JSON multilinha.
log := logger.New("info", "json")
log.Info("usuario_criado", "id", usuario.ID)
log.Error("erro_banco", "error", err)
// Com contexto
ctx = logger.WithContext(ctx, log)
logger.FromContext(ctx).Info("processado")
pkg/telemetry — OpenTelemetry
Telemetry é um submódulo opcional: importar o core do Ginger não traz o SDK do
OpenTelemetry nem aumenta a versão Go da aplicação. Instale apenas quando
necessário com go get github.com/fvmoraes/ginger/pkg/telemetry (Go 1.25+).
provider, err := telemetry.Setup(ctx, telemetry.Config{
ServiceName: cfg.App.Name,
ServiceVersion: cfg.App.Version,
Exporter: "stdout", // troque por "otlp" em produção
})
defer provider.Shutdown(ctx)
tracer := telemetry.Tracer("foobar")
ctx, span := tracer.Start(ctx, "nome-da-operacao")
defer span.End()
pkg/testhelper — Utilitários de teste
rec := testhelper.NewRequest(t, handler, http.MethodGet, "/usuarios").Do()
testhelper.AssertStatus(t, rec, http.StatusOK)
var resultado []Usuario
testhelper.DecodeJSON(t, rec, &resultado)
pkg/response — Envelopes de resposta JSON
Formatos JSON consistentes para todas as respostas da API — clientes frontend podem tratá-los de forma genérica.
// Recurso único — { "data": {...} }
response.OK(w, usuario)
response.Created(w, usuario)
// Lista paginada — { "data": [...], "pagination": { "page": 1, "per_page": 20, "total": 100, "total_pages": 5 } }
response.Paginated(w, usuarios, page, perPage, total)
// 204 No Content
response.NoContent(w)
pkg/sse — Server-Sent Events
Streaming unidirecional servidor→cliente sobre HTTP puro. Ideal para feeds ao vivo, notificações e atualizações de progresso.
func streamHandler(w http.ResponseWriter, r *http.Request) {
stream, err := sse.New(w)
if err != nil {
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
for {
select {
case <-r.Context().Done():
return
case evento := <-eventoCh:
stream.Send(sse.Event{Type: "update", Data: evento})
}
}
}
O buffering do nginx é desabilitado automaticamente (X-Accel-Buffering: no). Clientes reconectam usando o campo id.
pkg/ws — WebSocket
Comunicação bidirecional em tempo real. Zero dependências externas — implementado sobre hijack do net/http + framing RFC 6455.
func chatHandler(w http.ResponseWriter, r *http.Request) {
ws.Handle(w, r, func(conn *ws.Conn) {
for {
var msg ws.Message
if err := conn.Recv(&msg); err != nil {
return // cliente desconectou
}
conn.Send(ws.Message{Type: "echo", Data: msg.Data})
}
})
}
Use ginger add sse ou ginger add websocket para gerar um handler pronto no seu projeto.
App de Exemplo
O diretório example/ contém uma API CRUD completa de usuários demonstrando toda a stack do Ginger:
example/
├── cmd/app/main.go # conecta tudo
├── internal/
│ ├── models/user.go # User, CreateUserInput, UpdateUserInput
│ └── api/
│ ├── handlers/user_handler.go # camada HTTP
│ ├── services/user_service.go # lógica de negócio
│ └── repositories/user_repository.go # acesso a dados
└── configs/app.yaml
cd example
go mod tidy
go run ./cmd/app
# Criar um usuário
curl -X POST http://localhost:8080/api/v1/users \
-H "Content-Type: application/json" \
-d '{"name":"Alice","email":"alice@exemplo.com"}'
# Listar usuários
curl http://localhost:8080/api/v1/users
# Health check
curl http://localhost:8080/health
Configuração
configs/app.yaml:
app:
name: foobar
env: development
version: 0.1.0
http:
host: 0.0.0.0
port: 8080
shutdown_timeout: 30 # segundos
database:
driver: postgres
dsn: postgres://<usuario>:<senha>@localhost:5432/foobar-banco?sslmode=disable
max_open: 25
max_idle: 5
log:
level: info # debug | info | warn | error
format: json # campo de compatibilidade; Ginger usa apenas JSON
Todos os campos podem ser sobrescritos por variáveis de ambiente:
| Variável de ambiente |
Campo de configuração |
APP_NAME |
app.name |
APP_ENV |
app.env |
APP_VERSION |
app.version |
HTTP_HOST |
http.host |
HTTP_PORT |
http.port |
DATABASE_DRIVER |
database.driver |
DATABASE_DSN |
database.dsn |
LOG_LEVEL |
log.level |
LOG_FORMAT |
log.format (compatibilidade apenas) |
Observabilidade
OpenTelemetry está disponível como capability/submódulo opcional. O exportador padrão escreve traces no stdout. Troque por OTLP para enviar ao Jaeger, Tempo ou qualquer backend compatível com OTel.
provider, _ := telemetry.Setup(ctx, telemetry.Config{
ServiceName: "foobar",
Exporter: "otlp", // configure a env OTEL_EXPORTER_OTLP_ENDPOINT
})
Docker e Kubernetes
Um pacote DevOps é gerado apenas para tipos de projeto que precisam dele. Em service e worker, o Ginger cria:
devops/docker/Dockerfile
devops/docker/docker-compose.yml
devops/kubernetes/deployment.yaml
devops/helm/...
devops/pipelines/ci.yaml
O Dockerfile gerado usa build multi-stage:
docker build -f devops/docker/Dockerfile -t foobar:latest .
docker run -p 8080:8080 foobar:latest
Um template de Deployment + Service Kubernetes está disponível em devops/kubernetes/deployment.yaml. Ele inclui probes de readiness e liveness apontando para /health, limites de recursos e um serviço ClusterIP.
⚡ Cheat Sheet — Comandos Essenciais
Criar e Rodar
ginger new foobar --service # Criar projeto service → cmd/foobar
cd foobar && go mod tidy # Instalar deps
ginger run # Rodar (dev)
ginger build # Build (prod)
Gerar Código
ginger generate crud foobar # Estrutura completa do recurso
ginger generate test foobar # Testes do recurso
ginger generate tests --scan # Testes para código existente
ginger generate smoke-test # Smoke test da aplicação
ginger generate swagger foobar # OpenAPI do recurso
Gerenciar Projeto
ginger init [--force] # Inicializar ginger.yaml
ginger inspect # Analisar estrutura
ginger docs --plan # Gerar documentação
Adicionar Integrações
ginger add postgres # PostgreSQL
ginger add redis # Redis
ginger add kafka # Kafka
ginger add grpc # gRPC
Testar e Validar
go test ./... # Rodar testes
ginger doctor # Diagnosticar projeto
go vet ./... # Verificar código
Docker
docker build -f devops/docker/Dockerfile -t foobar . # Build imagem
docker run -p 8080:8080 foobar # Rodar container
docker compose -f devops/docker/docker-compose.yml up -d # Rodar com deps
Kubernetes
kubectl apply -f devops/kubernetes/ # Deploy
kubectl get pods # Ver pods
kubectl logs -f deploy/foobar # Ver logs
Mais comandos: Referência Rápida
📚 Documentação Completa
O Ginger vem com documentação abrangente e profunda cobrindo todos os aspectos do framework:
Mergulho profundo na arquitetura do Ginger, filosofia de design e padrões de código:
- Diagrama de componentes e fluxo de requisição
- Responsabilidades das camadas (Handler → Service → Repository)
- Padrões de injeção de dependência
- Estratégias de tratamento de erros
- Convenções de nomenclatura e estrutura de projeto
Documentação completa da API de cada pacote core com exemplos:
pkg/app — Bootstrap e lifecycle da aplicação
pkg/router — Roteamento HTTP e helpers
pkg/middleware — Middlewares embutidos (Logger, CORS, Recover, RequestID)
pkg/errors — Erros tipados com mapeamento de status HTTP
pkg/response — Envelopes JSON para respostas consistentes
pkg/sse — Server-Sent Events para streaming em tempo real
pkg/ws — WebSocket para comunicação bidirecional
pkg/config, pkg/logger, pkg/database, pkg/health, pkg/telemetry
Como adicionar bancos de dados, cache, mensageria e protocolos:
- Bancos: PostgreSQL, MySQL, SQLite, SQL Server, ClickHouse
- NoSQL: MongoDB, Couchbase
- Cache: Redis
- Mensageria: Kafka, RabbitMQ, NATS, Google Pub/Sub
- Protocolos: gRPC, MCP (Model Context Protocol)
- Tempo real: SSE, WebSocket
- Observabilidade: OpenTelemetry, Prometheus
Estratégias de teste, padrões e melhores práticas:
- Testes unitários, de integração e E2E
- Padrões de mocking (manual e testify)
- Testes table-driven
- Test helpers e utilitários
- Relatórios de coverage
- Integração CI/CD (GitHub Actions, GitLab CI)
Deploy em produção com Docker, Kubernetes e Helm:
- Builds Docker multi-stage e otimizações
- Docker Compose para desenvolvimento local
- Manifests Kubernetes (Deployment, Service, ConfigMap, Secrets)
- Helm charts para deploys multi-ambiente
- Pipelines CI/CD (GitHub Actions, GitLab CI)
- Health checks, monitoramento e troubleshooting
Built with ❤️ and idiomatic Go
Feito com ❤️ e Go idiomático