Framework Guide - Lokstra as Business Application Framework

Use Lokstra like NestJS or Spring Boot - Full enterprise framework with DI, services, and zero-code deployment topology changes

πŸ’‘ New to framework comparison? See detailed comparisons:

Welcome to Track 2 of Lokstra! Here you’ll learn to use Lokstra as a complete business application framework with:

  • βœ… Lazy Dependency Injection - Type-safe with Go generics
  • βœ… Service Architecture - Clean separation of concerns
  • βœ… Auto-Generated Routers - REST APIs from service definitions
  • βœ… Configuration-Driven Deployment - Monolith ↔ Microservices without code changes
  • βœ… Environment Management - Dev, staging, production configs

Framework Comparison

Feature Lokstra Framework NestJS Spring Boot
Language Go TypeScript Java
DI Pattern Lazy + Generics Decorators + Reflection Annotations + Reflection
Performance Compiled, fast startup Runtime, slower startup JVM, medium startup
Auto Router βœ… From service methods βœ… From decorators βœ… From annotations
Deployment Flexibility βœ… Zero-code topology change ❌ Requires code changes ❌ Requires code changes
Type Safety βœ… Compile-time βœ… TypeScript βœ… Java

Detailed Comparisons:


Quick Framework Example

1. Define Service (user_service.go):

type UserService struct {
    db *Database
}

func (s *UserService) GetAll(p *GetAllParams) ([]User, error) {
    return s.db.Query("SELECT * FROM users")
}

func (s *UserService) GetByID(p *GetByIDParams) (*User, error) {
    return s.db.QueryOne("SELECT * FROM users WHERE id = ?", p.ID)
}

func (s *UserService) Create(p *CreateParams) (*User, error) {
    user := &User{Name: p.Name, Email: p.Email}
    return s.db.Insert(user)
}

func UserServiceFactory(deps map[string]any, config map[string]any) any {
    return &UserService{
        db: deps["database"].(*Database),
    }
}

2. Register Service Factory (one-time setup):

lokstra_registry.RegisterServiceType(
    "user-service-factory",
    UserServiceFactory,
    nil,
    deploy.WithResource("user", "users"),
    deploy.WithConvention("rest"),
)

3. Configure Deployment (config.yaml):

service-definitions:
  user-service:
    type: user-service-factory
    depends-on: [database]
  
  database:
    type: database-factory

deployments:
  production:
    servers:
      api:
        addr: ":8080"
        published-services: [user-service]  # Auto-generates REST router!

4. Run Application:

func main() {
    RegisterServiceAndMiddlewareTypes()

    lokstra_registry.RunServerFromConfig()
}

Generated Routes:

GET    /users       β†’ UserService.GetAll()
GET    /users/{id}  β†’ UserService.GetByID()
POST   /users       β†’ UserService.Create()
PUT    /users/{id}  β†’ UserService.Update() (if defined)
DELETE /users/{id}  β†’ UserService.Delete() (if defined)

Learning Path

🎯 1. Service Management

Learn the heart of Lokstra Framework - lazy dependency injection and service architecture.

What you’ll learn:

  • βœ… Type-safe lazy loading with service.LazyLoad[T]
  • βœ… Service registration and factory patterns
  • βœ… Dependency resolution and caching
  • βœ… Testing strategies with mocked dependencies

Key concepts:

// Service-level lazy loading - services created on first access
var userService = service.LazyLoad[*UserService]("user-service")
var database = service.LazyLoad[*Database]("database")

func handler() {
    // Thread-safe, dependencies eagerly loaded when service created
    users := userService.MustGet().GetAll()
}

πŸ“‹ 2. Configuration Management

Master YAML-driven configuration and environment management.

What you’ll learn:

  • βœ… Service definitions and dependencies
  • βœ… Multi-environment deployments
  • βœ… Environment variable overrides
  • βœ… Deployment topology strategies

Key concepts:

service-definitions:
  user-service:
    type: user-service-factory
    depends-on: [database, cache]

deployments:
  development:
    servers:
      dev: {addr: ":3000", published-services: [user-service]}
  
  production:
    servers:
      api: {addr: ":8080", published-services: [user-service]}
      worker: {addr: ":8081", published-services: [background-jobs]}

🚦 3. Auto Router Generation

Generate REST APIs automatically from service method signatures.

What you’ll learn:

  • βœ… Convention-based routing from method names
  • βœ… Parameter binding and validation
  • βœ… Route customization and overrides
  • βœ… Middleware integration

Key concepts:

// Method signature determines HTTP route
func (s *UserService) GetAll(p *GetAllParams) ([]User, error)     // GET /users
func (s *UserService) GetByID(p *GetByIDParams) (*User, error)    // GET /users/{id}
func (s *UserService) Create(p *CreateParams) (*User, error)      // POST /users

// Register with auto-router
lokstra_registry.RegisterServiceType("user-service-factory", NewUserService, nil,
    deploy.WithResource("user", "users"))

πŸ”§ 4. Middleware & Plugins

Add cross-cutting concerns like authentication, logging, and validation.

What you’ll learn:

  • βœ… Framework middleware integration
  • βœ… Service-level middleware
  • βœ… Request/Response transformation
  • βœ… Error handling patterns

πŸš€ 5. Application & Server Management

Deploy and manage your application across different environments.

What you’ll learn:

  • βœ… Multi-server deployments
  • βœ… Monolith vs microservices patterns
  • βœ… Health checks and monitoring
  • βœ… Graceful shutdown handling

Framework Benefits

vs Manual Service Management

  • βœ… No initialization order issues - lazy loading handles dependencies
  • βœ… Type-safe dependency injection - compile-time guarantees
  • βœ… Declarative configuration - YAML instead of complex bootstrap code
  • βœ… Easy testing - mock services via registry

vs Other Go DI Frameworks

  • βœ… Zero reflection overhead - uses generics, not any
  • βœ… Lazy by default - memory efficient, fast startup
  • βœ… Auto-generated routers - no controller boilerplate
  • βœ… Configuration flexibility - works with or without YAML

vs Traditional Frameworks (NestJS/Spring)

  • βœ… Better performance - compiled Go vs runtime interpretation
  • βœ… Simpler deployment - single binary vs complex packaging
  • βœ… Flexible topology - monolith ↔ microservices without code changes
  • βœ… Type safety - compile-time errors vs runtime discovery

When to Use Framework Track

Choose Framework Track when you’re building:

  • βœ… Enterprise applications with multiple services
  • βœ… Applications that may scale from monolith to microservices
  • βœ… Team projects needing consistent patterns
  • βœ… API-heavy applications with many endpoints
  • βœ… Applications with complex dependencies between components

If you just need simple routing, consider Router Track instead.


Next Steps

  1. Start with Service Management - Core framework concepts
  2. Learn Configuration - YAML-driven setup
  3. Explore Auto Routers - Generate REST APIs
  4. Add Middleware - Cross-cutting concerns
  5. Deploy Applications - Production patterns

Ready to build enterprise applications with Lokstra? Let’s start with services! πŸš€