sdk-api

module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2026 License: MIT

README

Natuleadan's SDK API

Module: github.com/natuleadan/sdk-api

CI Integration Release Go Reference Go Version License Conventional Commits

A production-ready Go SDK for building event-driven microservices and monoliths. Fork of go-zero (45+ infrastructure packages) with optimizations: Fiber (fasthttp) replaces the HTTP layer, goccy/go-json (~40% fewer allocs), NATS JetStream for messaging, pgx native PostgreSQL, Turso, MySQL, MongoDB, and per-route middleware for minimal overhead.


Install

go install github.com/natuleadan/sdk-api/cmd/sdk-api@latest

Or download a pre-built binary from the releases page.

Quick Start

1. Install the CLI
go install github.com/natuleadan/sdk-api/cmd/sdk-api@latest
2. Scaffold a microservice
sdk-api new products-svc \
  --model Product \
  --fields "name:string,price:float64,stock:int" \
  --port 8080

This creates:

products-svc/
├── main.go                  # Entrypoint: HTTP server + DB + CRUD
├── service.yaml             # YAML config (DB, NATS, ports, middlewares)
└── models/
    └── model.go             # Product struct + hooks
3. Look at the generated files

models/model.go — your data model:

type Product struct {
    ID    int64   `db:"id,primary,auto" json:"id"`
    Name  string  `db:"name,required"   json:"name"`
    Price float64 `db:"price"           json:"price"`
    Stock int     `db:"stock"           json:"stock"`
}

service.yaml — everything is configured here:

name: products-svc
port: 8080
database:
  url: "${DATABASE_URL}"
  table: product
  resource: products

main.go — just hooks and run:

func main() {
    svc, _ := runtime.New[Product]("service.yaml")
    svc.WithHooks(&models.ProductHooks{})
    svc.Run()
}
4. Run it
# Start PostgreSQL (or use Turso for zero-config)
docker run -d --name pg \
  -e POSTGRES_USER=dev \
  -e POSTGRES_PASSWORD=devpass \
  -e POSTGRES_DB=postgres \
  -p 5432:5432 postgres:17-alpine

# Set the database URL and run
DATABASE_URL="postgres://dev:devpass@localhost:5432/postgres?sslmode=disable" \
go run ./products-svc
5. Test the auto-generated API
# Create a product
curl -X POST http://localhost:8080/api/v1/products \
  -H "Content-Type: application/json" \
  -d '{"name":"Widget","price":9.99,"stock":100}'
# → {"id":1,"name":"Widget","price":9.99,"stock":100}

# List all products
curl http://localhost:8080/api/v1/products
# → {"data":[{"id":1,"name":"Widget","price":9.99,"stock":100}],"total":1,"page":1,"size":10}

# Get by ID
curl http://localhost:8080/api/v1/products/1

# Update
curl -X PATCH http://localhost:8080/api/v1/products/1 \
  -H "Content-Type: application/json" \
  -d '{"price":7.99}'

# Delete
curl -X DELETE http://localhost:8080/api/v1/products/1

# Health check (built-in, no DB required)
curl http://localhost:8080/health
# → OK
6. Add business logic with hooks
func (h *ProductHooks) BeforeCreate(ctx context.Context, req Product) (Product, error) {
    if req.Price < 0 {
        return req, errors.New("price cannot be negative")
    }
    return req, nil
}
7. What you get out of the box
Feature Auto-generated?
REST API (full CRUD) ✅ From struct tags
PostgreSQL / Turso / MySQL / MongoDB ✅ Via YAML driver setting
Table auto-creation CREATE TABLE IF NOT EXISTS
OpenAPI 3.0 spec ✅ At /openapi.json
Scalar UI docs ✅ At /docs
Prometheus metrics ✅ At /metrics
Health check ✅ At /health
Graceful shutdown ✅ On SIGTERM/SIGINT

Features

Category Feature Description
HTTP Fiber (fasthttp) Fastest Go HTTP framework
14 middlewares JWT, CORS, Breaker, Shedding, Trace, Logger, Recover, Health, more
Per-route middleware Select which middlewares apply per path via server.routes in YAML
SSE + WebSocket Built-in real-time support
OpenAPI 3.0 + Scalar UI Auto-generated docs at /docs
Database PostgreSQL (pgx) Native pgxpool, 17 CRUD methods
Turso (SQLite) File-based, zero-config
MySQL database/sql + go-sql-driver
MongoDB go-mongo-driver
AutoInit CREATE TABLE IF NOT EXISTS from struct tags
Pool auto-sizing max(1, (PG_MAX_CONNS - RESERVED) / REPLICAS)
Messaging NATS JetStream Producers, consumers (push/pull), KV cache
NATS KV Distributed cache, shared across prefork processes
Redis Alternative cache backend
CLI sdk-api new Scaffold a microservice from model struct
sdk-api docker Generate Dockerfile
sdk-api kube Generate Kubernetes deployment YAML
sdk-api client Generate SDK in 5 languages (TS, Python, Dart, Java, Kotlin)

Performance

Benchmarks run fully inside Docker with wrk -t10 -c1000 -d30s (wrk inside the same container — zero network overhead).

healthz — Minimal HTTP throughput
Mode Arm Bare Metal 10c VPS A (4c dedicated) VPS B (1c shared)
RAW Fiber (/healthz) 680,867 108,184 56,170
SDK full (/healthz) 672,302 110,346 55,529
→ healthcheck short-circuit ~0% overhead ~0% ~0%
SDK full /ping (14 mw) 148,696 32,153 6,571
SDK minimal /ping (recover+health) 689,418 103,697 55,934
→ vs RAW Fiber ~1% overhead ~4% ~0.5%

See docs/benchmarks.md and docs/benchmarks_history.md for full methodology and history.

Per-Route Middleware

By default all 14 middlewares apply globally. Use server.routes to select middlewares per path:

server:
  routes:
    - path: "/healthz"
      middleware: []                       # recover + health only (689k RPS)
    - path: "/api/v1/public"
      middleware: [cors]
    - path: "/api/v1/*"
      middleware: [logger, breaker, cors, jwt]

Without routes: → 14 global middlewares (backwards compatible).

See docs/http-server.md for the full middleware reference.

Multi-DB App

Run multiple databases in the same process:

app, _ := runtime.NewApp("monolith.yaml")
app.AddDB(ctx, "pg-main", "postgres", pgURL)
app.AddDB(ctx, "local", "turso", tursoURL)
app.Run()
products, _ := runtime.AppGetPool[Product](app, "pg-main", "products")

Documentation

File Contents
docs/architecture.md Layers, packages, communication flow
docs/configuration.md Full YAML schema (35+ fields)
docs/database.md PG, Turso, MySQL, MongoDB drivers
docs/messaging.md NATS JetStream: producers, consumers, KV
docs/http-server.md Fiber, 14 middlewares, per-route config
docs/runtime.md Service[T], App monolith, hooks
docs/cli.md sdk-api new, docker, kube, client
docs/benchmarks.md Methodology, targets, results
docs/best-practices.md Gotchas, patterns, anti-patterns
docs/conventional-commits.md Commit rules, versioning, release flow

Examples

Example Description
examples/healthz/ Baseline HTTP throughput (748k RPS raw Fiber)
examples/url-link-base/ Redis cache benchmark (64k RPS)
examples/url-link-nats/ NATS KV cache benchmark (80k RPS)
examples/mysql/ MySQL CRUD benchmark
examples/turso/ Turso/SQLite CRUD benchmark
examples/mongo/ MongoDB CRUD benchmark

Conventional Commits

This project follows Conventional Commits for versioning and changelog generation. See docs/conventional-commits.md for the full reference.

Quick summary:

feat(scope): description        # minor bump (or patch in 0.x)
fix(scope): description         # patch bump
feat(scope)!: description       # major bump

Scope is required. Pull requests will be rejected if any commit lacks a scope.

Project Structure

├── cmd/sdk-api/          # CLI generator
├── db/                  # PostgreSQL, Turso, MySQL drivers
├── server/              # Fiber HTTP + 14 middlewares
├── events/              # NATS JetStream producer/consumer/KV
├── runtime/             # Service[T], App monolith, hooks, OpenAPI
├── internal/            # Dev server, encoding, health, profiling
├── infra/               # 45+ packages from go-zero
├── docs/                # 12 documentation files
├── examples/            # 6 dockerized benchmarks
└── .github/             # CI/CD workflows (ci, integration, release-please, release)

License

MIT — Fork of go-zero with additional optimizations and features.
Module: github.com/natuleadan/sdk-api

Jump to

Keyboard shortcuts

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