Lokstra
Modern Go Web Framework with Declarative Service Management
Quick Start β’ Features β’ Examples β’ Documentation β’ GitHub
What is Lokstra?
Lokstra is a versatile Go web framework that works in two ways:
π― Track 1: As a Router (Like Echo, Gin, Chi)
Use Lokstra as a fast, flexible HTTP router with elegant middleware support. Perfect when you just need routing without the complexity of DI frameworks.
r := lokstra.NewRouter("api")
r.GET("/", func() string {
return "Hello, Lokstra!"
})
app := lokstra.NewApp("hello", ":3000", r)
app.Run(30 * time.Second)
ποΈ Track 2: As a Business Application Framework (Like NestJS, Spring Boot)
Leverage the full framework with lazy dependency injection, auto-generated routers, and configuration-driven deployment. Build enterprise applications that scale from monolith to microservices.
// Define services in YAML
service-definitions:
user-service:
type: user-service-factory
depends-on: [database]
// Service-level lazy loading - service created on first access
userService := service.LazyLoad[*UserService]("user-service")
users := userService.MustGet().GetAll()
Choose your path:
- π Need a Router? β Read Router Guide (like Echo/Gin)
- π’ Building Enterprise Apps? β Read Framework Guide (like NestJS/Spring)
- οΏ½ New to Lokstra? β Start with Introduction
Quick Start
Install Lokstra CLI
go install github.com/primadi/lokstra/cmd/lokstra@latest
Create New Project
# Interactive template selection
lokstra new myapp
# Or choose specific template
lokstra new myapp -template 02_app_framework/01_medium_system
Install Framework Library
go get github.com/primadi/lokstra
Hello World (30 seconds)
package main
import "github.com/primadi/lokstra"
func main() {
r := lokstra.NewRouter("api")
r.GET("/", func() string {
return "Hello, Lokstra!"
})
r.GET("/ping", func() string {
return "pong"
})
app := lokstra.NewApp("hello", ":3000", r)
if err := app.Run(30 * time.Second); err != nil {
log.Fatal(err)
}
}
With Services & Configuration (2 minutes)
1. Define configuration (config.yaml):
service-definitions:
user-service:
type: user-service-factory
deployments:
production:
servers:
api:
base-url: https://api.example.com
addr: ":8080"
published-services: [user-service]
2. Register factory (one-time setup):
lokstra_registry.RegisterServiceType("user-service-factory",
func() any { return service.NewUserService() }, nil)
3. Use anywhere (zero overhead after first access):
var userService = service.LazyLoad[*UserService]("user-service")
func handler() {
users := userService.MustGet().GetAll() // Loaded once, cached forever
}
Key Features
π― Service-Level Lazy Loading
Type-safe service loading with zero overhead. Services created only when needed, dependencies eagerly resolved.
// Define once, use everywhere
var db = service.LazyLoad[*Database]("database")
var cache = service.LazyLoad[*Cache]("cache")
// Service loaded on first access, cached forever
users := db.MustGet().GetAll()
Benefits:
- No initialization order issues
- Thread-safe via
sync.Once - Memory efficient
- Fail-fast with clear errors
π Auto-Generated Routers
Generate REST APIs from service definitions automatically.
service-definitions:
user-service:
type: user-service-factory
deployments:
production:
servers:
api:
published-services: [user-service] # Auto-creates REST router!
Generated routes:
GET /users β List all users
GET /users/{id} β Get user by ID
POST /users β Create user
PUT /users/{id} β Update user
DELETE /users/{id} β Delete user
With overrides:
router-definitions:
user-service-router:
path-prefix: /api/v1
path-rewrites:
- pattern: "^/api/v1/(.*)$"
replacement: "/api/v2/$1"
middlewares: [auth, logging]
hidden: [InternalMethod]
ποΈ Flexible Deployment Topologies
One codebase, multiple deployment strategies. Switch from monolith to microservices without code changes.
Monolith:
deployments:
production:
servers:
all-in-one:
base-url: https://api.example.com
published-services: [user-service, order-service, payment-service]
Microservices:
deployments:
production:
servers:
user-api:
base-url: https://user-api.example.com
published-services: [user-service]
order-api:
base-url: https://order-api.example.com
published-services: [order-service]
Same code, different topology!
π£οΈ Path Rewrites & Overrides
Powerful URL transformation without touching code.
router-definitions:
api-router:
path-rewrites:
- pattern: "^/api/v1/(.*)$"
replacement: "/api/v2/$1"
middlewares: [auth, rate-limiter]
Use cases:
- API versioning
- Multi-tenant paths
- A/B testing
- Legacy URL migration
π Type-Safe Request Binding
Automatic validation with struct tags. Lokstra automatically injects and validates parameters.
type CreateUserParams struct {
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"required,email"`
Age int `json:"age" validate:"min=18,max=100"`
}
// Parameters automatically injected and validated!
func createUser(ctx *request.Context, params *CreateUserParams) error {
// params are already validated and ready to use
user := db.CreateUser(params.Name, params.Email, params.Age)
return ctx.Api.Ok(user)
}
No manual binding code needed! Lokstra handles:
- JSON/Form parsing
- Validation via struct tags
- Clear error messages on failure
π Lokstra CLI
Create new projects from templates in seconds!
# Install CLI
go install github.com/primadi/lokstra/cmd/lokstra@latest
# Create project (interactive)
lokstra new myapp
# Create with specific template
lokstra new blog-api -template 02_app_framework/01_medium_system
# Generate code for Enterprise templates
lokstra autogen ./myproject
Available Templates
Router Patterns (Learning & Simple APIs):
01_router/01_router_only- Pure routing basics01_router/02_single_app- Production single app01_router/03_multi_app- Multiple apps server
Framework Patterns (Production Apps):
02_app_framework/01_medium_system- Domain-driven (2-10 entities)02_app_framework/02_enterprise_modular- DDD with bounded contexts02_app_framework/03_enterprise_router_service- Annotation-based enterprise
What CLI Does Automatically
β
Downloads template from GitHub
β
Fixes all import paths
β
Runs go mod init
β
Runs go mod tidy
β
Ready to run immediately!
π Full CLI Documentation β
Examples
π Introduction & Examples
Quick Examples - Get started in minutes:
- Hello World - Minimal 10-line setup
- JSON API - REST API responses
- CRUD API - Complete service example with lazy DI
- Multi-Deployment - Monolith vs microservices
Comparing Approaches:
- Code vs Config - When to use which approach
- Architecture Overview - Framework design principles
π Essential Guides
Step-by-step learning path:
- Quick Start - Get up and running in 5 minutes
- Service Management - Master lazy dependency injection
- Routing & Handlers - Request handling patterns
- Configuration - YAML setup and environment management
Each guide includes:
- Clear explanations
- Working code examples
- Best practices
- Common pitfalls to avoid
π API Reference
Complete technical documentation:
- Registry API
- Configuration
- YAML Schema - Complete reference
- Deployment Patterns - Topology strategies
Advanced Topics:
- Auto-generated routers
- Path rewrites & overrides
- Multi-environment deployments
- Remote service integration
Why Lokstra?
π― Two Ways to Use Lokstra
Use as Router Only (Track 1)
Compare with Echo, Gin, Chi, Fiber:
// Just routing - no DI, no config files
r := lokstra.NewRouter("api")
r.GET("/users", getUsersHandler)
r.Use(cors.Middleware("*")
app := lokstra.NewApp("api", ":8080", r)
if err := app.Run(30 * time.Second); err != nil {
log.Fatal(err)
}
β
Flexible handler signatures (29+ forms!)
β
Clean middleware support
β
Group routing for API versioning
β
No framework lock-in
Use as Full Framework (Track 2)
Compare with NestJS, Spring Boot, Uber Fx:
# config.yaml
service-definitions:
user-service:
type: user-service-factory
depends-on: [database]
deployments:
production:
servers:
api:
published-services: [user-service] # Auto-router!
// Type-safe lazy DI
var userService = service.LazyLoad[*UserService]("user-service")
func handler() {
users := userService.MustGet().GetAll()
}
β
Lazy dependency injection (type-safe)
β
Auto-generated REST routers from services
β
Configuration-driven deployment
β
Monolith β Microservices without code changes
vs Traditional DI Frameworks
- β
Type-safe with generics (no
anycasting) - β Zero reflection overhead in hot path
- β Optional YAML (start with code, scale with config)
- β No code generation required
vs Manual Dependency Management
- β No initialization order issues
- β Declarative service definitions
- β Environment-based configuration
- β Easy testing (mock via registry)
vs Other Go Frameworks
- β Lazy loading by default (memory efficient)
- β Auto-generated routers from services
- β Multi-deployment support (monolith β microservices)
- β Path rewrites via YAML (no code changes)
Community & Support
- π Full Documentation - Complete guide
- π€ AI Agent Guide - For AI assistants (Copilot, Claude, ChatGPT)
- β‘ Quick Reference - Cheatsheet for common patterns
- π‘ Examples - Working code samples
- π GitHub Issues - Bug reports & features
- πΊοΈ Roadmap - Upcoming features
Quick Links
Made with β€οΈ by Primadi