xcore

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: MIT Imports: 44 Imported by: 0

README

xcore

A comprehensive Go application runtime framework that provides built-in HTTP server with plans for gRPC and other protocols in future versions.

Overview

xcore is a production-ready Go framework for building applications. It combines the best Go libraries with integrated lifecycle management, making it easy to build, run, and maintain applications. While HTTP is included as a core built-in feature, the framework is architected as an application runtime that can host multiple protocol handlers (HTTP, gRPC, etc.).

Key Philosophy: HTTP is a built-in capability, not the only capability. The framework is designed to be extensible for future protocol support including gRPC, WebSocket, and more.

Features

Built-in HTTP Server
  • RESTful routing with gorilla/mux
  • Route groups and middleware composition
  • Static file serving with fallbacks
  • Context-based handlers with automatic error handling
WebSocket
  • Real-time bidirectional communication
  • Room-based messaging for broadcasting
  • Connection management with ping/pong
  • JSON message encoding support
Middleware
  • Recovery (panic recovery)
  • Request ID tracking
  • Gzip compression
  • Body parsing with size limits
  • Request timeout
  • Real IP extraction
  • Method override (POST to PUT/PATCH/DELETE)
  • CORS support
  • Rate limiting (global and per-IP)
Authentication & Security
  • JWT authentication (HS256, HS384, HS512, RS256, RS384, RS512)
  • CSRF protection
  • Session management (in-memory, custom stores)
  • Security headers middleware
Data & Storage
  • Database: GORM with PostgreSQL, MySQL, SQLite, SQL Server support
  • Connection pooling with configurable limits
  • Transaction support
  • Cache: Memory, File, and Redis backends
  • Cache tagging for grouped invalidation
Background Processing
  • Cron job scheduler with panic recovery
  • Custom services with auto start/stop
  • Graceful shutdown coordination
Logging & Monitoring
  • Structured logging with zerolog (JSON/console)
  • Request logging middleware
  • Error file logging
  • Metrics collection
  • Health checks with component status
Error Handling
  • Structured error types with codes
  • HTTP status mapping
  • Validation error support
  • Error middleware for automatic handling
Graceful Shutdown
  • Signal handling (SIGINT, SIGTERM)
  • Coordinated shutdown of all components
  • Configurable timeouts for callbacks and servers
  • Database, cache, and service cleanup

Architecture

xcore is designed as an application runtime with the following architecture:

┌─────────────────────────────────────────────────────────────┐
│                         xcore.App                           │
├─────────────────────────────────────────────────────────────┤
│  ┌─────────┐  ┌─────────┐  ┌──────────┐  ┌──────────┐   │
│  │  HTTP   │  │   Web   │  │ Services │  │  Cron    │   │
│  │ Server  │  │ Socket  │  │          │  │ Jobs     │   │
│  └────┬────┘  └────┬────┘  └────┬─────┘  └────┬─────┘   │
│       │           │            │            │          │
│  ┌────┴────┐  ┌────┴────┐  ┌────┴─────┐  ┌────┴─────┐   │
│  │ Router │  │   WS   │  │ Service │  │ Cron    │   │
│  │         │  │ Manager│  │ Manager │  │ Manager │   │
│  └────┬────┘  └────────┘  └─────────┘  └─────────┘   │
│       │                                                  │
│  ┌────┴──────────────────────────────────────────┐    │
│  │            Graceful Shutdown Handler            │    │
│  └────┬──────────────────────────────────────────┘    │
│       │                                                  │
│  ┌────┴──────────────────────────────────────────┐    │
│  │         Integrated Components                  │    │
│  │  Logger │ Database │ Cache │ ConfigLoader    │    │
│  └──────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────┘

Installation

go get github.com/errteam/xcore

Quick Start

package main

import (
    "log"
    "net/http"
    
    "github.com/errteam/xcore"
)

func main() {
    app := xcore.New().
        WithHTTP(&xcore.HTTPConfig{Port: 8080}).
        WithLogger(&xcore.LoggerConfig{Level: "info"}).
        WithDatabase(&xcore.DatabaseConfig{Driver: "sqlite", DBName: "app.db"}).
        WithCache(&xcore.CacheConfig{Driver: "memory"}).
        WithGraceful(&xcore.GracefulConfig{Timeout: 30})
    
    // Register routes
    app.Router().GetHandler("/hello", func(c *xcore.Context) error {
        return c.JSONSuccess(map[string]string{"message": "Hello, World!"})
    })
    
    // Health check
    app.Router().GetHandler("/health", func(c *xcore.Context) error {
        return c.JSONSuccess(app.HealthCheck())
    })
    
    // Run the application
    if err := app.Run(); err != nil {
        log.Fatal(err)
    }
}

Core Concepts

App (Application Runtime)

The App struct is the main entry point for the framework. It orchestrates all components:

app := xcore.New().
    WithHTTP(&xcore.HTTPConfig{Port: 8080}).
    WithLogger(&xcore.LoggerConfig{Level: "debug", Output: "console"}).
    WithDatabase(&xcore.DatabaseConfig{Driver: "postgres", Host: "localhost", Port: 5432, User: "user", Password: "pass", DBName: "app"}).
    WithCache(&xcore.CacheConfig{Driver: "redis", RedisAddr: "localhost:6379"}).
    WithCron(&xcore.CronConfig{Timezone: "UTC", RecoverPan: true}).
    WithWebSocket(&xcore.WebsocketConfig{Enabled: true, PingInterval: 30}).
    WithGraceful(&xcore.GracefulConfig{Timeout: 30})
Accessing Components
app.Logger()      // Structured logger
app.Router()      // HTTP router
app.Database()    // Database connection
app.Cache()       // Cache interface
app.Cron()        // Cron scheduler
app.WebSocket()  // WebSocket manager
app.Graceful()    // Graceful shutdown handler
app.Services()    // Service manager
Router & Context-Based Handlers

The Router provides context-based handlers with automatic error handling:

// GET handler
app.Router().GetHandler("/users", func(c *xcore.Context) error {
    return c.JSONSuccess(users)
})

// POST handler with body binding
app.Router().PostHandler("/users", func(c *xcore.Context) error {
    var req CreateUserRequest
    if err := c.BindJSON(&req); err != nil {
        return err  // Returns 400 Bad Request automatically
    }
    // Process request...
    return c.JSONCreated(newUser, "User created")
})

// Route parameters
app.Router().GetHandler("/users/:id", func(c *xcore.Context) error {
    id := c.Param("id")
    user, err := getUser(id)
    if err != nil {
        return xcore.ErrNotFound("User not found")
    }
    return c.JSONSuccess(user)
})

// Query parameters
app.Router().GetHandler("/search", func(c *xcore.Context) error {
    query := c.QueryParam("q")
    page := c.DefaultQuery("page", "1")
    return c.JSONSuccess(searchResults)
})

// Route groups
app.Router().Group("/api/v1", func(api *xcore.Router) {
    api.UseCORS(corsConfig)
    api.GetHandler("/users", handler)
    api.PostHandler("/users", handler)
    api.GetHandler("/posts", handler)
})
Context

The Context provides convenient methods for handling HTTP requests:

// Request data
id := c.Param("id")              // URL parameter
query := c.QueryParam("search")  // Query string
body := c.Body()                 // Request body bytes
c.BindJSON(&obj)                // Parse JSON body
c.BindForm(&obj)                // Parse form data
c.BindQuery(&obj)               // Parse query string
c.GetHeader("Authorization")   // Get header
c.Cookie("session")             // Get cookie
c.ClientIP()                    // Get client IP
c.RequestID()                   // Get request ID
c.RealIP()                      // Get real IP (from proxy headers)
c.UserID()                      // Get authenticated user ID

// Response methods
c.JSON(status, data)              // JSON response
c.JSONSuccess(data)               // 200 OK with standard format
c.JSONCreated(data, msg)          // 201 Created
c.JSONError(status, msg)          // Error response
c.JSONValidationError(errors)     // 422 Unprocessable Entity
c.JSONPaginated(data, page, perPage, total) // Paginated response
c.String(status, format, args...) // Plain text
c.HTML(status, html)              // HTML response
c.File(filepath)                  // Serve file
c.FileInline(filepath, name)      // Download file
c.Redirect(status, url)           // Redirect
c.Stream(status, contentType, reader) // Streaming response
Middleware

Middleware can be applied at the app level or router level:

// App-level (all routes)
app.Use(xcore.NewRecovery(nil).Middleware)
app.Use(xcore.NewCompression(gzip.DefaultCompression).Middleware)

// Router-level
router := app.Router()
router.UseRecovery()
router.UseRequestID()
router.UseCompression(gzip.DefaultCompression)
router.UseTimeout(30 * time.Second)
router.UseRateLimiter(100, 200)        // Global rate limit
router.UseRateLimiterPerIP(10, 20)    // Per-IP rate limit
router.UseCORS(&xcore.CORSConfig{
    AllowedOrigins: []string{"https://example.com"},
    AllowCredentials: true,
})
router.UseRealIP()
router.UseMethodOverride()
Error Handling

Use the structured XError type for proper error handling:

// Predefined errors
return xcore.ErrNotFound("User not found")
return xcore.ErrUnauthorized("Invalid credentials")
return xcore.ErrValidation("Invalid input")
return xcore.ErrForbidden("Access denied")
return xcore.ErrBadRequest("Invalid request")
return xcore.ErrTooManyRequests("Rate limit exceeded")

// Create custom errors
return xcore.NewError(xcore.ErrCodeBadRequest, "Invalid request")
return xcore.NewErrorWithStatus(xcore.ErrCodeValidation, "Validation failed", 422)

// With validation errors
return xcore.NewError(xcore.ErrCodeValidation, "Validation failed").
    WithErrors([]xcore.ValidationError{
        {Field: "email", Message: "Invalid email format"},
        {Field: "password", Message: "Password too short"},
    })

// Wrap errors with context
return xcore.ErrDatabase(err)
return xcore.ErrCache(err)
return xcore.ErrExternalAPI(err, "payment-service")

// Add metadata
return xcore.ErrNotFound("Resource not found").
    WithMeta("resource_id", id)
Response Helpers

The framework provides standardized response formats:

// Success responses
return c.JSONSuccess(data)
return c.JSONCreated(newUser, "Created successfully")
return c.JSONPaginated(items, page, perPage, total)

// Error responses
return c.JSONError(http.StatusBadRequest, "Invalid request")
return c.JSONValidationError(errors)

// Using Response builders
resp := xcore.NewResponse().
    WithStatus(xcore.StatusSuccess).
    WithCode(http.StatusOK).
    WithData(data).
    WithMessage("Success")
return c.JSON(http.StatusOK, resp)
Services (Background Workers)

Implement custom background services that are started and stopped with the app:

type MyWorker struct {
    done chan struct{}
}

func (w *MyWorker) Name() string { return "my-worker" }

func (w *MyWorker) Start() error {
    w.done = make(chan struct{})
    go w.run()
    return nil
}

func (w *MyWorker) Stop() error {
    close(w.done)
    return nil
}

func (w *MyWorker) run() {
    for {
        select {
        case <-w.done:
            return
        default:
            // Work...
            time.Sleep(time.Second)
        }
    }
}

app := xcore.New().WithService(&MyWorker{})
Database
// Configuration
dbConfig := &xcore.DatabaseConfig{
    Driver:          "postgres",
    Host:           "localhost",
    Port:           5432,
    User:           "user",
    Password:       "password",
    DBName:         "mydb",
    SSLMode:        "disable",
    MaxOpenConns:   25,
    MaxIdleConns:   5,
    ConnMaxLifetime: 300,
    ConnMaxIdleTime: 60,
}

// Usage (GORM)
app.Database().Create(&user)
app.Database().First(&user, id)
app.Database().Where("active = ?", true).Find(&users)
app.Database().Model(&user).Updates(map[string]interface{}{"name": "new name"})

// Transaction
app.Database().Transaction(ctx, func(ctx context.Context) error {
    if err := app.Database().Create(&order).Error; err != nil {
        return err
    }
    return app.Database().Create(&invoice).Error
})

// Health check
health := app.Database().Health(ctx)
fmt.Println(health.Status, health.Latency)
Cache
// Configuration
cacheConfig := &xcore.CacheConfig{
    Driver:          "redis",
    RedisAddr:       "localhost:6379",
    RedisPassword:   "",
    RedisDB:         0,
    RedisPoolSize:   10,
}

// Or memory cache
cacheConfig := &xcore.CacheConfig{
    Driver:          "memory",
    CleanupInterval: 60,
}

// Usage
ctx := context.Background()
app.Cache().Set(ctx, "user:1", userData, time.Hour)
value, err := app.Cache().Get(ctx, "user:1")
app.Cache().Delete(ctx, "user:1")

// Multi operations
app.Cache().MSet(ctx, map[string]interface{}{
    "key1": value1,
    "key2": value2,
})
results := app.Cache().MGet(ctx, "key1", "key2")

// Tags (memory cache)
app.Cache().Tags().SetTags(ctx, "user:1", "user", "active")
app.Cache().Tags().InvalidateByTag(ctx, "user")
WebSocket
// Configuration
wsConfig := &xcore.WebsocketConfig{
    Enabled:         true,
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
    PingInterval:    30,
    PongTimeout:     10,
    MaxMessageSize:  1024 * 1024,
    AllowedOrigins:  []string{"*"}, // or ["https://example.com"]
}

app := xcore.New().WithWebSocket(wsConfig)

// Handler
app.Router().GetHandler("/ws", func(c *xcore.Context) error {
    conn := c.Request.Context().Value("ws_conn").(*xcore.WSConnection)
    
    // Read message
    msg := conn.ReadMessage()
    
    // Write message
    conn.WriteMessage(&xcore.WSMessage{
        Type:    xcore.WSMessageText,
        Payload: []byte("Hello"),
    })
    
    // Broadcast to room
    conn.BroadcastToRoom("room1", &xcore.WSMessage{...})
    
    return nil
})

// In WebSocket handler
hub := app.WebSocket().GetHub()
hub.Broadcast(&xcore.WSMessage{Type: xcore.WSMessageText, Payload: []byte("Hello")})
Cron Jobs
// Configuration
cronConfig := &xcore.CronConfig{
    Timezone:   "UTC",
    MaxJobs:    100,
    RecoverPan: true,
}

// Add cron jobs (cron expression: second minute hour day month weekday)
app.Cron().AddJob("daily-cleanup", "0 0 * * *", func() error {
    // Run daily at midnight
    return cleanupOldRecords()
})

app.Cron().AddJob("hourly-report", "0 */6 * * *", func() error {
    // Run every 6 hours
    return generateReport()
})

app.Cron().AddJob("every-minute", "* * * * *", func() error {
    // Run every minute
    return doSomething()
})

// Manage jobs
entries := app.Cron().Entries()
for _, entry := range entries {
    fmt.Println(entry.Name, entry.Next)
}

app.Cron().Stop() // Graceful stop
JWT Authentication
// Configuration
jwtConfig := xcore.NewJWTConfig("your-secret-key").
    WithAlgorithm("HS256").
    WithExpiration(24 * time.Hour).
    WithCookieName("token").
    WithCookieHTTPOnly(true).
    WithCookieSecure(true).
    WithCookieSameSite(http.SameSiteStrictMode)

// Or RSA
jwtConfig, _ := xcore.NewJWTConfig("").WithRSAPrivateKey(privateKeyPEM)

// Middleware
jwtMiddleware := xcore.NewJWTMiddleware(jwtConfig).
    Exclude("/health", "/metrics", "/login")

app.Use(jwtMiddleware.Middleware)

// Generate token
claims := xcore.NewJWTClaims("user-id", "username", "email@example.com", "admin")
token, err := jwtMiddleware.GenerateToken(claims)

// In handler - get claims
claims := xcore.GetJWTClaims(ctx)
userID := xcore.GetUserIDFromContext(ctx)
userID, username, email := xcore.GetUserFromContext(ctx)

// Set cookie
jwtMiddleware.SetTokenCookie(w, token)

// Clear cookie
jwtMiddleware.ClearTokenCookie(w)
Session Management
// Create session store (in-memory)
store := xcore.NewMemorySessionStore(30 * time.Minute)

// Use in handler
app.Router().PostHandler("/login", func(c *xcore.Context) error {
    // Authenticate...
    
    // Create session
    session, _ := store.Create(c.Context())
    session.Values["user_id"] = userID
    store.Set(c.Context(), session)
    
    // Set cookie
    c.SetCookie(&http.Cookie{
        Name:     "session_id",
        Value:    session.ID,
        HttpOnly: true,
    })
    
    return c.JSONSuccess(map[string]string{"status": "logged in"})
})

Configuration Reference

HTTP Config
&xcore.HTTPConfig{
    Host:         "0.0.0.0",
    Port:         8080,
    ReadTimeout:  30,
    WriteTimeout: 30,
    IdleTimeout:  60,
    StaticPath:   "/static",
    StaticDir:    "./public",
}
Logger Config
&xcore.LoggerConfig{
    Level:       "info",       // debug, info, warn, error
    Output:      "both",        // console, file, both
    Format:      "console",    // console, json
    FilePath:    "./logs/app.log",
    MaxSize:     100,           // MB
    MaxAge:      30,            // days
    MaxBackups:  3,
    Compress:    true,
    Caller:      false,        // include file:line
}
Database Config
&xcore.DatabaseConfig{
    Driver:          "postgres",
    Host:            "localhost",
    Port:            5432,
    User:            "user",
    Password:        "password",
    DBName:          "mydb",
    SSLMode:         "disable",
    MaxOpenConns:    25,
    MaxIdleConns:    5,
    ConnMaxLifetime: 300,
    ConnMaxIdleTime: 60,
    ConnectTimeout:  10,
    LogLevel:       "error",    // silent, error, warn, info
}
Cache Config
// Memory
&xcore.CacheConfig{
    Driver:          "memory",
    CleanupInterval: 60,
}

// File
&xcore.CacheConfig{
    Driver:   "file",
    FilePath: "./cache",
    TTL:      3600,
}

// Redis
&xcore.CacheConfig{
    Driver:        "redis",
    RedisAddr:     "localhost:6379",
    RedisPassword: "",
    RedisDB:       0,
    RedisPoolSize: 10,
    RedisTLS:      false,
}
WebSocket Config
&xcore.WebsocketConfig{
    ReadBufferSize:  1024,
    WriteBufferSize: 1024,
    PingInterval:    30,
    PongTimeout:     10,
    MaxMessageSize:  1024 * 1024,
    Enabled:         true,
    AllowedOrigins:  []string{"*"}, // or ["https://example.com"]
}
Cron Config
&xcore.CronConfig{
    Timezone:   "UTC",
    MaxJobs:    100,
    RecoverPan: true,
}
Graceful Config
&xcore.GracefulConfig{
    Timeout: 30, // seconds
}
CORS Config
&xcore.CORSConfig{
    AllowedOrigins:   []string{"https://example.com"},
    AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
    AllowedHeaders:   []string{"Content-Type", "Authorization"},
    ExposedHeaders:   []string{"X-Request-ID"},
    AllowCredentials: true,
    MaxAge:           86400,
    Enabled:          true,
}

Best Practices

1. Use Context-Based Handlers

Always use HandlerFunc for proper error handling:

// Good
app.Router().GetHandler("/users", func(c *xcore.Context) error {
    return c.JSONSuccess(users)
})

// Avoid - no automatic error handling
app.Router().HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
    // Manual handling required
})
2. Return Errors
// Good - automatic error response
app.Router().GetHandler("/users", func(c *xcore.Context) error {
    user, err := getUser(c.Param("id"))
    if err != nil {
        return xcore.ErrNotFound("User not found")
    }
    return c.JSONSuccess(user)
})
3. Use Structured Errors
// Validation errors with field details
if invalidInput {
    return xcore.NewError(xcore.ErrCodeValidation, "Validation failed").
        WithErrors([]xcore.ValidationError{
            {Field: "email", Message: "Invalid email format"},
            {Field: "age", Message: "Must be 18 or older"},
        })
}
4. Configure Graceful Shutdown
app := xcore.New().
    WithGraceful(&xcore.GracefulConfig{Timeout: 30}).
    WithDatabase(dbConfig).
    WithCache(cacheConfig).
    WithService(&myWorker)
5. Database Connection Pooling
&xcore.DatabaseConfig{
    MaxOpenConns:    25,       // Adjust based on load
    MaxIdleConns:    5,
    ConnMaxLifetime: 300,      // 5 minutes
    ConnMaxIdleTime: 60,       // 1 minute
}
6. Logging
// Structured logging
logger.Info().
    Str("user_id", userID).
    Str("action", "create").
    Msg("operation completed")

// Error logging
logger.Error().Err(err).Str("query", query).Msg("database error")
7. Rate Limiting
// Global rate limit
router.UseRateLimiter(100, 200)

// Per-IP rate limit
router.UseRateLimiterPerIP(10, 20)
8. Health Checks
app.Router().GetHandler("/health", func(c *xcore.Context) error {
    return c.JSONSuccess(map[string]string{"status": "ok"})
})

app.Router().GetHandler("/ready", func(c *xcore.Context) error {
    // Check dependencies
    if err := app.Database().Ping(c.Context()); err != nil {
        return c.JSONError(http.StatusServiceUnavailable, "Database not ready")
    }
    return c.JSONSuccess(map[string]string{"status": "ready"})
})
9. Validation

Use validation tags on structs:

type CreateUserRequest struct {
    Name  string `validate:"required,min=2,max=50"`
    Email string `validate:"required,email"`
    Age   int    `validate:"gte=0,lte=150"`
}

// In handler
func (c *Context) BindJSON(v interface{}) error {
    // Binding and validation happens automatically
}
10. Security Headers
security := xcore.NewSecurityHeaders()
router.UseMiddleware(security.Middleware())

Testing

go test -v ./...
go test -cover ./...
go test -race ./...

Project Structure

myapp/
├── main.go
├── go.mod
├── config.yaml
├── app/
│   ├── handlers/
│   │   ├── user.go
│   │   └── product.go
│   ├── services/
│   │   └── worker.go
│   └── middleware/
│       └── auth.go
├── models/
│   └── user.go
└── migrations/

Version

Current version: 1.0.0

Roadmap

  • gRPC support
  • GraphQL support
  • Rate limiting middleware improvements
  • Distributed cache invalidation
  • Metrics export (Prometheus)

License

MIT License

Dependencies

  • github.com/gorilla/mux - HTTP routing
  • github.com/gorilla/websocket - WebSocket support
  • gorm.io/gorm - Database ORM
  • gorm.io/driver/postgres - PostgreSQL driver
  • gorm.io/driver/mysql - MySQL driver
  • gorm.io/driver/sqlite - SQLite driver
  • github.com/rs/zerolog - Logging
  • github.com/golang-jwt/jwt/v5 - JWT authentication
  • github.com/robfig/cron/v3 - Cron scheduling
  • github.com/spf13/viper - Configuration
  • github.com/go-redis/redis/v8 - Redis client
  • github.com/go-playground/validator/v10 - Validation
  • github.com/google/uuid - UUID generation

Contributing

Contributions are welcome! Please submit issues and pull requests.

Documentation

Overview

Package xcore provides caching functionality for the xcore framework.

This package defines the Cache interface and provides implementations for different cache backends. Supported drivers: memory, file, redis.

The cache interface supports standard operations: Get, Set, Delete, Clear, Exists, Keys, TTL, MGet, MSet. It also supports tagging for cache invalidation.

Package xcore provides file-based cache implementation.

This package implements a file-based cache that stores cached data as JSON files in a specified directory.

Package xcore provides an in-memory cache implementation.

The MemoryCache implements the Cache interface using a concurrent-safe map. It supports TTL (time-to-live) for entries, automatic cleanup of expired entries, and cache tagging for grouped invalidation.

Package xcore provides Redis cache implementation.

This package implements a cache backed by Redis for distributed caching across multiple application instances.

Package xcore provides configuration loading functionality for the xcore framework.

This package provides utilities for loading configuration from various sources:

  • Files (YAML, JSON, TOML, etc.) using viper
  • Environment variables with prefix support
  • Multiple file paths with fallback

The ConfigLoader wraps the viper library to provide a fluent interface for configuration management.

Package xcore provides the Context type for HTTP request handling in the xcore framework.

The Context type wraps the standard http.Request and http.ResponseWriter to provide a more convenient interface for handlers. It includes utilities for:

  • Reading path parameters and query strings
  • Managing the handler chain (Next, Abort)
  • Error handling and logging
  • Context value storage

Package xcore provides HTTP request handling methods for the Context.

This file extends the Context type with methods for reading and parsing request data including headers, query parameters, form data, and body.

Package xcore provides HTTP response methods for the Context.

This file extends the Context type with methods for sending various types of HTTP responses including JSON, HTML, XML, files, and streams.

Package xcore provides CORS (Cross-Origin Resource Sharing) middleware for the xcore framework.

This package provides middleware for handling CORS headers in HTTP responses. It supports configurable allowed origins, methods, headers, and credentials.

The middleware handles OPTIONS preflight requests automatically and returns the appropriate CORS headers based on the configuration.

Package xcore provides cron job scheduling functionality.

This package wraps the robfig/cron library to provide a simple interface for scheduling recurring tasks in the application.

Package xcore provides CSRF (Cross-Site Request Forgery) protection.

This package provides CSRF token generation and validation middleware to protect against CSRF attacks in web applications.

Package xcore provides database functionality using GORM.

This package wraps the GORM ORM to provide database operations with support for PostgreSQL, MySQL, SQLite, and SQL Server. It includes connection pooling, transaction support, and health checks.

Package xcore provides error handling functionality for the xcore framework.

This package defines the XError type for structured error handling across the framework. It includes error codes, HTTP status mapping, validation errors, and error handlers.

Key features:

  • Custom error codes with HTTP status mapping
  • Wrapping of underlying errors
  • Validation error support
  • Metadata attachment
  • Middleware for automatic error handling

Package xcore provides graceful shutdown functionality for the xcore framework.

The graceful package handles coordinated shutdown of HTTP servers, databases, caches, WebSocket connections, cron jobs, and user-defined services. It ensures all resources are properly released and pending requests are completed.

Key features:

  • Signal handling (SIGINT, SIGTERM)
  • Configurable shutdown timeout
  • Callback execution with timeout
  • Server shutdown with context timeout

Package xcore provides health check functionality.

This package provides health check endpoints for monitoring the status of the application and its dependencies.

Package xcore provides JWT (JSON Web Token) authentication for the xcore framework.

This package provides JWT token generation, validation, and middleware for HTTP requests. It supports both HMAC (HS256, HS384, HS512) and RSA (RS256, RS384, RS512) algorithms.

Key features:

  • Token generation with custom claims
  • Token validation with multiple algorithms
  • Context-based claims extraction
  • Cookie-based token storage
  • Path exclusion support

Package xcore provides logging functionality for the xcore framework.

This package wraps the zerolog library to provide structured logging with support for multiple outputs (console, file, both), log levels, and formatting. It also includes request logging middleware for HTTP servers.

Package xcore provides metrics collection functionality.

This package provides basic metrics collection including counters and histograms. It can be extended to integrate with Prometheus or other monitoring systems.

Package xcore provides HTTP middleware components for the xcore framework.

This package includes various middleware implementations for common HTTP functionality:

  • Recovery: Panics are recovered and logged, returning a 503 response
  • RequestID: Adds a unique request ID to each request (X-Request-ID header)
  • Compression: Gzip compression for responses
  • BodyParser: Limits and parses request body size
  • Timeout: Adds request timeout with automatic response
  • RealIP: Extracts the real client IP from proxies
  • MethodOverride: Allows POST requests to override HTTP method

Each middleware is implemented as a struct with a Middleware() method that returns an http.HandlerFunc for use with net/http or gorilla/mux.

Package xcore provides rate limiting functionality for the xcore framework.

This package implements token bucket rate limiting for HTTP requests. It supports both global rate limiting and per-IP rate limiting.

Rate limiting headers (X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset) are automatically added to responses. When rate limit is exceeded, a 429 response is returned.

Package xcore provides request logging utilities.

This package provides middleware for logging HTTP request bodies and response data for debugging and audit purposes.

Package xcore provides response helpers for standardized HTTP responses.

This package defines the Response type and helper functions for creating consistent API responses across the application.

Package xcore provides HTTP routing functionality for the xcore framework.

This package wraps the gorilla/mux router to provide a fluent interface for defining HTTP routes with support for:

  • RESTful route handlers (GET, POST, PUT, PATCH, DELETE, OPTIONS)
  • Context-based handlers with error handling
  • Route grouping
  • Static file serving
  • Middleware composition
  • CORS, rate limiting, and other common patterns

Package xcore provides security headers and helpers.

This package provides security-related utilities including security headers for HTTP responses and helper functions.

Package xcore provides service management for the xcore framework.

This package defines the Service interface and ServiceManager for managing application services. Services are components that can be started and stopped as part of the application lifecycle.

Package xcore provides session management functionality.

This package provides session storage with support for custom stores. It includes memory-based session storage and cookie-based session IDs.

Package xcore provides request validation functionality.

This package wraps the go-playground/validator library to provide struct-based validation for HTTP requests. Tags with the name "validate" are used to specify validation rules.

Package xcore provides WebSocket support using gorilla/websocket.

This package enables real-time bidirectional communication between the server and clients. It supports message broadcasting, room-based messaging, and connection management.

Package xcore provides a Go web application framework for building HTTP services.

This package offers a comprehensive set of utilities including:

  • HTTP routing with gorilla/mux
  • Middleware support (recovery, compression, rate limiting, CORS, etc.)
  • JWT authentication
  • Graceful shutdown handling
  • Database and cache integration
  • Logging with zerolog
  • WebSocket support
  • Scheduled jobs (cron)

Example usage:

app := xcore.New().
    WithHTTP(&xcore.HTTPConfig{Port: 8080}).
    WithLogger(&xcore.LoggerConfig{Level: "debug"}).
    WithDatabase(&xcore.DatabaseConfig{...})

app.Router().GetHandler("/hello", func(c *xcore.Context) error {
    return c.JSON(200, map[string]string{"message": "Hello, World!"})
})

if err := app.Run(); err != nil {
    log.Fatal(err)
}

Index

Constants

View Source
const (
	RequestIDKey contextKey = "request_id" // Stores the unique request ID
	RealIPKey    contextKey = "real_ip"    // Stores the client real IP address
	UserIDKey    contextKey = "user_id"    // Stores the authenticated user ID
)

Context keys for storing request-scoped values.

View Source
const (
	Version = "1.0.0"
)

Variables

View Source
var (
	ErrKeyNotFound = fmt.Errorf("key not found")
	ErrKeyExpired  = fmt.Errorf("key expired")
)

Cache errors.

View Source
var (
	ErrInvalidToken       = NewError(ErrCodeInvalidToken, "Invalid token")
	ErrTokenExpired       = NewError(ErrCodeTokenExpired, "Token expired")
	ErrServiceUnavailable = NewError(ErrCodeServiceUnavailable, "Service temporarily unavailable")
)

Predefined errors for common cases.

Functions

func CORSMiddlewareFunc

func CORSMiddlewareFunc(cfg *CORSConfig) func(http.Handler) http.Handler

func GenerateSessionID

func GenerateSessionID() (string, error)

func GetUserFromContext

func GetUserFromContext(ctx context.Context) (string, string, string)

GetUserFromContext extracts user information (ID, username, email) from JWT claims. Returns empty strings if no claims found.

func GetUserIDFromContext

func GetUserIDFromContext(ctx context.Context) string

GetUserIDFromContext extracts the user ID from JWT claims in the context. Returns empty string if no claims found.

func HealthMiddleware

func HealthMiddleware(app *App) func(http.Handler) http.Handler

func HelmetCSPDefault

func HelmetCSPDefault() string

func HelmetCSPStrict

func HelmetCSPStrict() string

func IsXError

func IsXError(err error) bool

IsXError checks if the error is an XError. Uses errors.As for proper type checking.

func LoadConfigFromFile

func LoadConfigFromFile(path string, cfg interface{}) error

LoadConfigFromFile loads configuration from a single file path. It uses the file extension to determine the configuration format. Automatically enables environment variable mapping.

func LoadConfigFromFiles

func LoadConfigFromFiles(paths []string, cfg interface{}) error

LoadConfigFromFiles loads configuration from multiple file paths. It attempts to load the first valid file found in the list. Returns an error if no valid config file is found or if loading fails.

func LoadEnvConfig

func LoadEnvConfig(prefix string, cfg interface{}) error

LoadEnvConfig loads configuration from environment variables with the given prefix. It automatically maps environment variables to configuration keys. Keys are transformed by replacing "-" with ".".

func NoCache

func NoCache() func(http.Handler) http.Handler

func RecordCacheHit

func RecordCacheHit()

func RecordCacheMiss

func RecordCacheMiss()

func RecordDBQuery

func RecordDBQuery(query string, duration time.Duration)

func RecordWSConnection

func RecordWSConnection()

func RecordWSDisconnection

func RecordWSDisconnection()

func RecordWSMessage

func RecordWSMessage()

func RegisterCustomValidator

func RegisterCustomValidator(tag string, fn CustomValidator) error

func SetDefaultLogger

func SetDefaultLogger(logger *Logger)

SetDefaultLogger sets the global default logger. Used when accessing DefaultLogger() without creating a logger.

func StaticCache

func StaticCache(maxAge int) func(http.Handler) http.Handler

func Validate

func Validate(s interface{}) error

func ValidateContext

func ValidateContext(ctx context.Context, s interface{}) error

func ValidateVar

func ValidateVar(field interface{}, tag string) error

Types

type App

type App struct {
	// contains filtered or unexported fields
}

App is the main application struct that orchestrates all components of the xcore framework. It manages the lifecycle of HTTP servers, databases, caches, cron jobs, WebSocket connections, and user-defined services. App provides a fluent builder pattern for configuration.

The App struct is thread-safe for configuration operations but should not be modified after Run() has been called. All setter methods (With*) return the App pointer to enable chaining.

Example:

app := xcore.New().
    WithConfig(cfg).
    WithHTTP(&xcore.HTTPConfig{Port: 8080}).
    WithLogger(&xcore.LoggerConfig{Level: "info"}).
    WithDatabase(dbConfig).
    WithCache(cacheConfig).
    WithCron(cronConfig)

// Register routes
app.Router().GetHandler("/api/health", func(c *xcore.Context) error {
    return c.JSON(200, map[string]string{"status": "ok"})
})

// Run the application (blocking)
if err := app.Run(); err != nil {
    log.Fatal(err)
}

func New

func New() *App

New creates a new App instance with default configuration. This is the starting point for building an xcore application.

The returned App has default Config and an empty ServiceManager. Additional configuration is applied using the With* methods before calling Run().

Example:

app := xcore.New()
app.WithHTTP(&xcore.HTTPConfig{Port: 8080})

func (*App) Cache

func (a *App) Cache() Cache

Cache returns the cache instance. Returns nil if WithCache() has not been called or if initialization failed.

func (*App) Cron

func (a *App) Cron() *Cron

Cron returns the cron scheduler instance. Returns nil if WithCron() has not been called.

func (*App) Database

func (a *App) Database() *Database

Database returns the database instance. Returns nil if WithDatabase() has not been called or if initialization failed.

func (*App) Graceful

func (a *App) Graceful() *Graceful

Graceful returns the graceful shutdown handler instance. Returns nil if WithGraceful() has not been called.

func (*App) Logger

func (a *App) Logger() *Logger

Logger returns the application's logger instance. Returns nil if WithLogger() has not been called.

func (*App) Router

func (a *App) Router() *Router

Router returns the application's router instance. Creates a new Router with default configuration if not already set. The router is used to register HTTP handlers and routes.

func (*App) Run

func (a *App) Run() error

Run starts the application and blocks until shutdown. It initializes all components, starts the HTTP server (if configured), starts all registered services, and waits for shutdown signals.

Run performs the following steps:

  1. Marks the app as started (prevents multiple calls)
  2. Creates a default logger if none configured
  3. Creates a default graceful shutdown handler if none configured
  4. Registers database, cache, and WebSocket with graceful shutdown
  5. Starts cron jobs (if configured)
  6. Starts the HTTP server in a goroutine
  7. Starts all user-defined services
  8. Registers services shutdown with graceful handler
  9. Runs graceful shutdown and waits for completion

Returns an error if the app has already been started.

func (*App) ServeHTTP

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*App) Services

func (a *App) Services() *ServiceManager

func (*App) Use

func (a *App) Use(mw func(http.Handler) http.Handler) *App

Use registers a global middleware that will be applied to all routes. Middlewares are applied in the order they are registered. The middleware function receives the next handler and returns a wrapped handler.

Common middlewares include recovery, compression, rate limiting, CORS, etc. Example:

app.Use(xcore.NewRecovery(nil).Middleware)
app.Use(xcore.NewCompression(gzip.DefaultCompression).Middleware)

func (*App) WebSocket

func (a *App) WebSocket() *WebSocket

WebSocket returns the WebSocket manager instance. Returns nil if WithWebSocket() has not been called.

func (*App) WithCache

func (a *App) WithCache(cfg *CacheConfig) *App

WithCache initializes the cache using the provided configuration. If cfg is nil, default configuration is applied (Driver: "memory"). Supported drivers: "memory", "file", "redis". On failure, the error is logged but the App continues.

func (*App) WithConfig

func (a *App) WithConfig(cfg *Config) *App

WithConfig sets the application configuration. The config parameter should not be nil; if nil is passed, a default Config is used.

Configuration includes settings for HTTP server, logger, database, cache, cron jobs, WebSocket, and graceful shutdown behavior.

func (*App) WithCron

func (a *App) WithCron(cfg *CronConfig) *App

WithCron initializes the cron job scheduler with the provided configuration. If cfg is nil, default configuration is applied. The cron scheduler is started immediately when Run() is called.

func (*App) WithDatabase

func (a *App) WithDatabase(cfg *DatabaseConfig) *App

WithDatabase initializes the database connection using the provided configuration. If cfg is nil, the method returns without changes. On failure, the error is logged but the App continues (database is set to nil). The database is registered with graceful shutdown handler.

func (*App) WithGraceful

func (a *App) WithGraceful(cfg *GracefulConfig) *App

WithGraceful configures graceful shutdown handling. If cfg is nil, default configuration is applied (Timeout: 30 seconds). Graceful shutdown ensures proper termination of HTTP servers, databases, caches, WebSocket connections, and user services.

func (*App) WithHTTP

func (a *App) WithHTTP(cfg *HTTPConfig) *App

WithHTTP configures the HTTP server settings. If cfg is nil, default values are applied (Port: 8080). This method also initializes the Router if not already set.

func (*App) WithLogger

func (a *App) WithLogger(cfg *LoggerConfig) *App

WithLogger configures the logger with the given configuration. If cfg is nil, default values are applied (Level: "info", Output: "console", Format: "console"). A fallback logger is created if logger initialization fails.

func (*App) WithService

func (a *App) WithService(service Service) *App

WithService adds a user-defined service to the application. Services are started in order during app.Run() and stopped in reverse order during shutdown. The service must implement the Service interface (Start, Stop, Name methods).

func (*App) WithWebSocket

func (a *App) WithWebSocket(cfg *WebsocketConfig) *App

WithWebSocket initializes WebSocket support with the given configuration. If cfg is nil, default configuration is applied.

type Binding

type Binding interface {
	Name() string
	Bind(*http.Request, interface{}) error
}
var (
	JSON   Binding = &JSONBinding{}
	Query  Binding = &QueryBinding{}
	Form   Binding = &FormBinding{}
	Header Binding = &HeaderBinding{}
)

type BodyParser

type BodyParser struct {
	// contains filtered or unexported fields
}

BodyParser is a middleware that validates and limits request body size. It checks the Content-Length header against the maxSize limit. For JSON requests, it also wraps the body reader with http.MaxBytesReader.

func NewBodyParser

func NewBodyParser(maxSize int64) *BodyParser

NewBodyParser creates a new BodyParser middleware with the specified max size. If maxSize <= 0, defaults to 10MB (10 << 20 bytes).

func (*BodyParser) Middleware

func (p *BodyParser) Middleware(next http.Handler) http.Handler

Middleware returns an http.Handler that limits and validates request body size. Only applies to POST, PUT, and PATCH requests with JSON content type.

type CORSConfig

type CORSConfig struct {
	AllowedOrigins   []string `mapstructure:"allowed_origins" yaml:"allowed_origins" json:"allowed_origins"`
	AllowedMethods   []string `mapstructure:"allowed_methods" yaml:"allowed_methods" json:"allowed_methods"`
	AllowedHeaders   []string `mapstructure:"allowed_headers" yaml:"allowed_headers" json:"allowed_headers"`
	ExposedHeaders   []string `mapstructure:"exposed_headers" yaml:"exposed_headers" json:"exposed_headers"`
	AllowCredentials bool     `mapstructure:"allow_credentials" yaml:"allow_credentials" json:"allow_credentials"`
	MaxAge           int      `mapstructure:"max_age" yaml:"max_age" json:"max_age"`
	Enabled          bool     `mapstructure:"enabled" yaml:"enabled" json:"enabled"`
}

CORSConfig defines Cross-Origin Resource Sharing configuration.

type CORSMiddleware

type CORSMiddleware struct {
	// contains filtered or unexported fields
}

CORSMiddleware handles CORS headers for HTTP requests. It validates the Origin header against allowed origins and sets appropriate response headers.

func NewCORSMiddleware

func NewCORSMiddleware(cfg *CORSConfig) *CORSMiddleware

NewCORSMiddleware creates a new CORS middleware with the given configuration. If config is nil, default configuration is used:

  • AllowedOrigins: ["*"]
  • AllowedMethods: [GET, POST, PUT, DELETE, OPTIONS]
  • AllowedHeaders: [Content-Type, Authorization]
  • AllowCredentials: false
  • MaxAge: 0 (no caching)
  • ExposedHeaders: []
  • Enabled: true

Note: When AllowCredentials is true, wildcards ("*") in AllowedOrigins are replaced with an empty string to comply with CORS specification.

func (*CORSMiddleware) Handler

func (m *CORSMiddleware) Handler(next http.Handler) http.Handler

Handler returns an http.Handler that applies CORS rules to requests. If CORS is disabled (config.Enabled = false), passes through to next handler unchanged. For OPTIONS requests (preflight), returns 204 No Content with appropriate headers.

func (*CORSMiddleware) MiddlewareFunc

func (m *CORSMiddleware) MiddlewareFunc() func(http.Handler) http.Handler

MiddlewareFunc returns the middleware as a function type. Convenience method for use with router.Use() or similar.

type CSRF

type CSRF struct {
	// contains filtered or unexported fields
}

func NewCSRF

func NewCSRF(cfg *CSRFConfig) *CSRF

func (*CSRF) Middleware

func (c *CSRF) Middleware(next http.Handler) http.Handler

func (*CSRF) TokenGenerator

func (c *CSRF) TokenGenerator() http.HandlerFunc

type CSRFConfig

type CSRFConfig struct {
	TokenLength    int
	TokenName      string
	CookieName     string
	CookiePath     string
	CookieDomain   string
	CookieHTTPOnly bool
	CookieSecure   bool
	CookieSameSite http.SameSite
	HeaderName     string
	FormKeyName    string
	ExpireDuration time.Duration
	IgnoredMethods []string
	TrustedOrigins []string
}

CSRFConfig defines configuration for CSRF protection.

func NewCSRFConfig

func NewCSRFConfig() *CSRFConfig

type Cache

type Cache interface {
	Get(ctx context.Context, key string) (interface{}, error)
	Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
	Delete(ctx context.Context, key string) error
	Clear(ctx context.Context) error
	Exists(ctx context.Context, key string) (bool, error)
	Keys(ctx context.Context, pattern string) ([]string, error)
	TTL(ctx context.Context, key string) (time.Duration, error)
	MGet(ctx context.Context, keys ...string) ([]interface{}, error)
	MSet(ctx context.Context, items map[string]interface{}) error
	Close() error
	Tags() CacheTags
}

Cache defines the interface for caching operations. Implementations can be in-memory, file-based, or distributed (e.g., Redis).

func NewCache

func NewCache(cfg *CacheConfig) (Cache, error)

NewCache creates a new Cache instance based on the configuration. If cfg is nil, defaults to memory cache with 60-second cleanup interval.

Supported drivers:

  • "memory": In-memory cache with TTL support
  • "file": File-based cache
  • "redis": Redis cache (requires valid config)

type CacheConfig

type CacheConfig struct {
	Driver          string `mapstructure:"driver" yaml:"driver" json:"driver"`
	RedisAddr       string `mapstructure:"redis_addr" yaml:"redis_addr" json:"redis_addr"`
	RedisPassword   string `mapstructure:"redis_password" yaml:"redis_password" json:"redis_password"`
	RedisDB         int    `mapstructure:"redis_db" yaml:"redis_db" json:"redis_db"`
	RedisPoolSize   int    `mapstructure:"redis_pool_size" yaml:"redis_pool_size" json:"redis_pool_size"`
	RedisTLS        bool   `mapstructure:"redis_tls" yaml:"redis_tls" json:"redis_tls"`
	FilePath        string `mapstructure:"file_path" yaml:"file_path" json:"file_path"`
	TTL             int    `mapstructure:"ttl" yaml:"ttl" json:"ttl"`
	CleanupInterval int    `mapstructure:"cleanup_interval" yaml:"cleanup_interval" json:"cleanup_interval"`
	Enabled         bool   `mapstructure:"enabled" yaml:"enabled" json:"enabled"`
}

CacheConfig defines the configuration for the caching system.

type CacheTags

type CacheTags interface {
	SetTags(ctx context.Context, key string, tags ...string) error
	GetTags(ctx context.Context, key string) ([]string, error)
	InvalidateByTag(ctx context.Context, tag string) error
	InvalidateByTags(ctx context.Context, tags ...string) error
}

CacheTags defines the interface for cache tagging operations. Tags allow grouping related cache keys and invalidating them together.

type ComponentHealth

type ComponentHealth struct {
	Status  string `json:"status"`
	Message string `json:"message,omitempty"`
}

ComponentHealth represents the health status of a specific component.

type Compression

type Compression struct {
	// contains filtered or unexported fields
}

Compression is a middleware that compresses HTTP responses using gzip. The compression level is set during initialization (Default, Best, BestSpeed). It checks the Accept-Encoding header and only compresses if gzip is supported.

func NewCompression

func NewCompression(level int) *Compression

NewCompression creates a new Compression middleware with the specified level. Valid levels are gzip.DefaultCompression (6), gzip.BestSpeed (1), gzip.BestCompression (9). If an invalid level is provided, it defaults to gzip.DefaultCompression.

func (*Compression) Middleware

func (c *Compression) Middleware(next http.Handler) http.Handler

Middleware returns an http.Handler that compresses responses using gzip. It only compresses if the client accepts gzip encoding.

type Config

type Config struct {
	HTTP      *HTTPConfig      `mapstructure:"http" yaml:"http"`
	Logger    *LoggerConfig    `mapstructure:"logger" yaml:"logger"`
	Database  *DatabaseConfig  `mapstructure:"database" yaml:"database"`
	Cache     *CacheConfig     `mapstructure:"cache" yaml:"cache"`
	Cron      *CronConfig      `mapstructure:"cron" yaml:"cron"`
	Websocket *WebsocketConfig `mapstructure:"websocket" yaml:"websocket"`
	Graceful  *GracefulConfig  `mapstructure:"graceful" yaml:"graceful"`
}

Config is the root configuration struct.

type ConfigLoader

type ConfigLoader struct {
	// contains filtered or unexported fields
}

ConfigLoader wraps the viper library to provide a fluent configuration loading interface. It supports loading from files, environment variables, and can watch for configuration changes.

func NewConfigLoader

func NewConfigLoader() *ConfigLoader

NewConfigLoader creates a new ConfigLoader instance with a fresh viper instance.

func (*ConfigLoader) AddConfigPath

func (cl *ConfigLoader) AddConfigPath(path string) *ConfigLoader

AddConfigPath adds a directory path to search for configuration files. Multiple paths can be added and they are searched in order.

func (*ConfigLoader) AutomaticEnv

func (cl *ConfigLoader) AutomaticEnv() *ConfigLoader

AutomaticEnv enables automatic mapping of environment variables to configuration keys. It automatically reads environment variables that match the configuration structure.

func (*ConfigLoader) GetBool

func (cl *ConfigLoader) GetBool(key string) bool

GetBool returns the boolean value for the specified key. Returns false if the key does not exist.

func (*ConfigLoader) GetInt

func (cl *ConfigLoader) GetInt(key string) int

GetInt returns the integer value for the specified key. Returns 0 if the key does not exist.

func (*ConfigLoader) GetString

func (cl *ConfigLoader) GetString(key string) string

GetString returns the string value for the specified key. Returns empty string if the key does not exist.

func (*ConfigLoader) GetStringSlice

func (cl *ConfigLoader) GetStringSlice(key string) []string

GetStringSlice returns the string slice value for the specified key. Returns nil if the key does not exist.

func (*ConfigLoader) Load

func (cl *ConfigLoader) Load(cfg interface{}) error

Load reads the configuration file and unmarshals it into the provided struct. It returns an error if the file cannot be read or the content cannot be unmarshaled.

func (*ConfigLoader) LoadStrict

func (cl *ConfigLoader) LoadStrict(cfg interface{}) error

LoadStrict reads the configuration file and unmarshals it strictly into the provided struct. Strict unmarshaling requires exact field matching and returns an error for unknown fields.

func (*ConfigLoader) MergeConfigOverride

func (cl *ConfigLoader) MergeConfigOverride(override map[string]interface{}) error

MergeConfigOverride merges configuration overrides from a map. This is useful for programmatically overriding specific configuration values.

func (*ConfigLoader) OnConfigChange

func (cl *ConfigLoader) OnConfigChange(run func(e fsnotify.Event))

OnConfigChange registers a callback function to be called when configuration changes. The callback receives the fsnotify.Event describing the change.

func (*ConfigLoader) SetConfigFile

func (cl *ConfigLoader) SetConfigFile(path string) *ConfigLoader

SetConfigFile sets the configuration file path and type. This is used to specify the main configuration file.

func (*ConfigLoader) SetConfigType

func (cl *ConfigLoader) SetConfigType(typ string) *ConfigLoader

SetConfigType sets the configuration file type (e.g., "yaml", "json", "toml"). This is used when the file extension alone is not sufficient to determine the format.

func (*ConfigLoader) SetEnvKeyReplacer

func (cl *ConfigLoader) SetEnvKeyReplacer(oldNew ...string) *strings.Replacer

SetEnvKeyReplacer sets a replacer for environment variable keys. This allows transforming keys (e.g., replacing "-" with "."). Returns the created Replacer for reference.

func (*ConfigLoader) SetEnvPrefix

func (cl *ConfigLoader) SetEnvPrefix(prefix string) *ConfigLoader

SetEnvPrefix sets the prefix for environment variables. Environment variables with this prefix will be mapped to configuration keys.

func (*ConfigLoader) WatchConfig

func (cl *ConfigLoader) WatchConfig()

WatchConfig enables watching for configuration file changes. When the configuration file changes, it is automatically reloaded.

type ConnStats

type ConnStats struct {
	OpenConns    int           `json:"open_conns"`
	IdleConns    int           `json:"idle_conns"`
	InUseConns   int           `json:"in_use_conns"`
	WaitCount    int64         `json:"wait_count"`
	WaitDuration time.Duration `json:"wait_duration"`
	MaxOpenConns int           `json:"max_open_conns"`
}

ConnStats holds database connection pool statistics.

type ConsoleLoggerConfig

type ConsoleLoggerConfig struct {
	Colorable bool `mapstructure:"colorable" yaml:"colorable" json:"colorable"`
}

type Context

type Context struct {
	Request *http.Request
	Params  map[string]string // Route parameters from gorilla/mux
	Query   url.Values        // Query parameters

	App        *App
	Router     *Router
	Response   http.ResponseWriter
	StatusCode int
	// contains filtered or unexported fields
}

Context wraps http.Request and http.ResponseWriter for handler use. It provides a clean interface for handling HTTP requests with support for middleware chaining and error propagation.

func NewContext

func NewContext(w http.ResponseWriter, r *http.Request) *Context

NewContext creates a new Context from an HTTP request and response writer. Automatically extracts route parameters and query string values.

func (*Context) Abort

func (c *Context) Abort()

Abort stops the handler chain execution. Subsequent handlers in the chain will not be executed.

func (*Context) AbortWithError

func (c *Context) AbortWithError(code int, err error) error

AbortWithError sets the status code, adds an error, and stops the handler chain. Returns the error for convenience in handler return values.

func (*Context) AbortWithStatus

func (c *Context) AbortWithStatus(code int)

AbortWithStatus sets the status code and stops the handler chain.

func (*Context) AddError

func (c *Context) AddError(err error)

AddError adds an error to the context's error list. Errors can be retrieved later using Error() or Errors().

func (*Context) BindBody

func (c *Context) BindBody(bindFunc func([]byte, interface{}) error, obj interface{}) error

BindBody allows custom binding of the request body to an object.

func (*Context) BindForm

func (c *Context) BindForm(v interface{}) error

BindForm parses form data (application/x-www-form-urlencoded or multipart/form-data) into the given struct and validates it.

func (*Context) BindHeader

func (c *Context) BindHeader(v interface{}) error

BindHeader parses HTTP headers into the given struct and validates it. Header keys are converted to lowercase for the struct mapping.

func (*Context) BindJSON

func (c *Context) BindJSON(v interface{}) error

BindJSON parses the request body as JSON and validates it. Returns an error if the body is not valid JSON or validation fails.

func (*Context) BindQuery

func (c *Context) BindQuery(v interface{}) error

BindQuery parses query string parameters into the given struct and validates it.

func (*Context) BindURI

func (c *Context) BindURI(v interface{}) error

BindURI parses URL path parameters into the given struct and validates it.

func (*Context) Body

func (c *Context) Body() ([]byte, error)

Body reads and returns the entire request body.

func (*Context) Bytes

func (c *Context) Bytes(code int, contentType string, data []byte) error

Bytes is an alias for Data method.

func (*Context) ClientIP

func (c *Context) ClientIP() string

ClientIP returns the real IP address of the client. Checks X-Real-IP, X-Forwarded-For headers, then falls back to RemoteAddr.

func (*Context) ContentType

func (c *Context) ContentType() string

ContentType returns the Content-Type header of the request.

func (*Context) Context

func (c *Context) Context() context.Context

Context returns the underlying request context.

func (*Context) Cookie

func (c *Context) Cookie(name string) (*http.Cookie, error)

Cookie returns the named cookie from the request.

func (*Context) Cookies

func (c *Context) Cookies() []*http.Cookie

Cookies returns all cookies from the request.

func (*Context) Data

func (c *Context) Data(code int, contentType string, data []byte) error

Data sends a raw byte response with the given content type and status code.

func (Context) Deadline

func (c Context) Deadline() (deadline time.Time, ok bool)

Deadline returns the deadline for the request context.

func (*Context) DefaultParam

func (c *Context) DefaultParam(key, defaultValue string) string

DefaultParam returns the value of a URL parameter or a default if not found.

func (*Context) DefaultPostForm

func (c *Context) DefaultPostForm(key, defaultValue string) string

DefaultPostForm returns the value of a POST form field or a default if not found.

func (*Context) DefaultQuery

func (c *Context) DefaultQuery(key, defaultValue string) string

DefaultQuery returns the value of a query parameter or a default if not found.

func (*Context) DeleteCookie

func (c *Context) DeleteCookie(name string, path string, domains ...string)

DeleteCookie deletes a cookie by setting its expiration to the epoch. Supports optional domain parameters for domain-scoped cookies.

func (Context) Done

func (c Context) Done() <-chan struct{}

Done returns a channel that is closed when the request context is cancelled.

func (Context) Err

func (c Context) Err() error

Err returns an error if the request context is cancelled or times out.

func (*Context) Error

func (c *Context) Error() error

Error returns the first error in the context's error list. Returns nil if no errors have been added.

func (*Context) Errors

func (c *Context) Errors() []error

Errors returns all errors collected in the context.

func (*Context) File

func (c *Context) File(filepath string) error

File serves a file from disk at the given filepath. Sets appropriate Content-Type based on file extension.

func (*Context) FileInline

func (c *Context) FileInline(filepath string, name string) error

FileInline serves a file from disk with a custom filename in the Content-Disposition header. This forces the browser to download the file with the specified name.

func (*Context) FormFile

func (c *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)

FormFile returns the uploaded file and its metadata from a multipart form.

func (*Context) Get

func (c *Context) Get(key string) interface{}

Get retrieves a value from the request context.

func (*Context) GetBody

func (c *Context) GetBody() ([]byte, error)

GetBody reads the request body and returns it as bytes. The body is re-added to the request so it can be read again.

func (*Context) GetBool

func (c *Context) GetBool(key string) (bool, error)

GetBool parses and returns a bool from a query parameter.

func (*Context) GetFloat64

func (c *Context) GetFloat64(key string) (float64, error)

GetFloat64 parses and returns a float64 from a query parameter.

func (*Context) GetHeader

func (c *Context) GetHeader(key string) string

GetHeader returns the value of the specified request header.

func (*Context) GetHeaderReal

func (c *Context) GetHeaderReal(key string) string

GetHeaderReal returns the value of a response header.

func (*Context) GetInt

func (c *Context) GetInt(key string) (int, error)

GetInt parses and returns an integer from a query parameter.

func (*Context) GetInt64

func (c *Context) GetInt64(key string) (int64, error)

GetInt64 parses and returns an int64 from a query parameter.

func (*Context) GetQuery

func (c *Context) GetQuery(key string) (string, bool)

GetQuery returns both the value and existence flag of a query parameter.

func (*Context) HTML

func (c *Context) HTML(code int, html string) error

HTML sends an HTML response with the given status code.

func (*Context) Handler

func (c *Context) Handler() HandlerFunc

Handler returns the current handler in the chain. Returns nil if the index is past the end of the chain.

func (*Context) Header

func (c *Context) Header(key, value string)

Header sets a response header key-value pair.

func (*Context) Host

func (c *Context) Host() string

Host returns the host from the request.

func (*Context) IsAjax

func (c *Context) IsAjax() bool

IsAjax checks if the request is an AJAX request by checking X-Requested-With header.

func (*Context) IsSecure

func (c *Context) IsSecure() bool

IsSecure checks if the request was made over HTTPS.

func (*Context) IsWebSocket

func (c *Context) IsWebSocket() string

IsWebSocket returns the value of the Upgrade header (e.g., "websocket").

func (*Context) JSON

func (c *Context) JSON(code int, obj interface{}) error

JSON sends a JSON response with the given status code and object. Automatically sets Content-Type to application/json.

func (*Context) JSONCreated

func (c *Context) JSONCreated(data interface{}, message string) error

JSONCreated sends a created response with the given data and message. Uses StatusCreated (201). Default message is "Created successfully".

func (*Context) JSONError

func (c *Context) JSONError(code int, message string) error

JSONError sends an error response with the given status code and message.

func (*Context) JSONP

func (c *Context) JSONP(callback string, obj interface{}) error

JSONP sends a JSONP response with the given callback function and object. The response is wrapped in the callback function call.

func (*Context) JSONPaginated

func (c *Context) JSONPaginated(data interface{}, page, perPage int, total int64) error

JSONPaginated sends a paginated response with the given data and pagination info. Includes page, per_page, total, and total_pages in the meta.

func (*Context) JSONSuccess

func (c *Context) JSONSuccess(data interface{}) error

JSONSuccess sends a success response with the given data. Uses StatusOK (200) and wraps data in the standard response format.

func (*Context) JSONValidationError

func (c *Context) JSONValidationError(errors []ResponseError) error

JSONValidationError sends a validation error response with the given errors. Uses StatusUnprocessableEntity (422).

func (*Context) Logger

func (c *Context) Logger() *Logger

Logger returns the context's logger instance.

func (*Context) Loggerf

func (c *Context) Loggerf(format string, args ...interface{})

Loggerf logs a formatted message using the context's logger.

func (*Context) Method

func (c *Context) Method() string

Method returns the HTTP method of the request (GET, POST, etc.).

func (*Context) MultipartForm

func (c *Context) MultipartForm() (*multipart.Form, error)

MultipartForm parses and returns the multipart form data. Uses 32MB as the max memory size for parsing.

func (*Context) Next

func (c *Context) Next() error

Next executes the next handler in the chain. Used by middleware to pass control to the next handler.

func (*Context) NoContent

func (c *Context) NoContent(code int) error

NoContent sends a response with no body and the given status code. Common use: 204 No Content for successful DELETE operations.

func (*Context) Param

func (c *Context) Param(key string) string

Param returns the value of a URL path parameter.

func (*Context) PostForm

func (c *Context) PostForm(key string) string

PostForm returns the value of a POST form field.

func (*Context) QueryParam

func (c *Context) QueryParam(key string) string

QueryParam returns the value of a query string parameter.

func (*Context) RealIP

func (c *Context) RealIP() string

RealIP returns the real client IP from the context. This is set by the RealIP middleware.

func (*Context) Redirect

func (c *Context) Redirect(code int, url string) error

Redirect redirects the client to the given URL with the specified status code. Common use: 301 Moved Permanently or 302 Found.

func (*Context) RemoteAddr

func (c *Context) RemoteAddr() string

RemoteAddr returns the network address of the client.

func (*Context) RequestID

func (c *Context) RequestID() string

RequestID returns the request ID from the context. This is set by the RequestID middleware.

func (*Context) Reset

func (c *Context) Reset(w http.ResponseWriter, r *http.Request)

Reset reinitializes the Context with a new request/response pair. Used for request reuse in HTTP handler pools.

func (*Context) SendFile

func (c *Context) SendFile(file string, name string) error

SendFile reads a file and sends it as a response. The filename is used to determine the Content-Type.

func (*Context) ServeFile

func (c *Context) ServeFile(file string)

ServeFile serves the given file using http.ServeFile. Convenience method that delegates to the standard library.

func (*Context) Set

func (c *Context) Set(key string, value interface{})

Set stores a value in the request context.

func (*Context) SetCacheControl

func (c *Context) SetCacheControl(seconds int)

SetCacheControl sets the Cache-Control header with the given max-age seconds.

func (*Context) SetContentType

func (c *Context) SetContentType(contentType string)

SetContentType sets the Content-Type header to the given value.

func (*Context) SetCookie

func (c *Context) SetCookie(cookie *http.Cookie)

SetCookie sets a cookie on the response.

func (*Context) SetLogger

func (c *Context) SetLogger(logger *Logger)

SetLogger sets the logger for the context.

func (*Context) Status

func (c *Context) Status(code int)

Status sets the HTTP response status code.

func (*Context) Stream

func (c *Context) Stream(code int, contentType string, readFunc func(w io.Writer, fl http.Flusher) bool) error

Stream sends a streaming response with the given content type. The readFunc is called repeatedly to write data to the response. If the response writer supports http.Flusher, data is flushed after each write.

func (*Context) String

func (c *Context) String(code int, format string, args ...interface{}) error

String sends a plain text response with the given status code and format. Supports printf-style formatting with args.

func (*Context) URL

func (c *Context) URL() *url.URL

URL returns the parsed URL of the request.

func (*Context) UserAgent

func (c *Context) UserAgent() string

UserAgent returns the User-Agent header of the request.

func (*Context) UserID

func (c *Context) UserID() string

UserID returns the authenticated user ID from the context. This is typically set after JWT authentication.

func (Context) Value

func (c Context) Value(key interface{}) interface{}

Value returns the value for the given key in the request context.

func (*Context) XML

func (c *Context) XML(code int, obj interface{}) error

XML sends an XML response with the given status code and object. Note: Uses JSON encoder for simplicity; for proper XML, use dedicated XML marshaling.

type Cron

type Cron struct {
	// contains filtered or unexported fields
}

Cron is a job scheduler for running recurring tasks. It supports panic recovery and configurable timezones.

func NewCron

func NewCron(cfg *CronConfig, logger *Logger) *Cron

NewCron creates a new Cron scheduler with the given configuration. If cfg is nil, default configuration is used (UTC timezone, panic recovery enabled).

func (*Cron) AddFunc

func (c *Cron) AddFunc(name, spec string, fn func() error) (*CronJob, error)

AddFunc is an alias for AddJob.

func (*Cron) AddJob

func (c *Cron) AddJob(name, spec string, fn func() error) (*CronJob, error)

AddJob adds a new cron job with the given name, spec, and function. The spec is a cron expression (e.g., "0 0 * * *" for daily at midnight). Returns the CronJob and any error.

func (*Cron) Entries

func (c *Cron) Entries() []cron.Entry

Entries returns all registered cron job entries.

func (*Cron) ListJobs

func (c *Cron) ListJobs() []*CronJob

ListJobs returns all registered CronJob objects.

func (*Cron) Remove

func (c *Cron) Remove(id cron.EntryID)

Remove removes a cron job by its ID.

func (*Cron) Run

func (c *Cron) Run()

Run triggers all jobs to run immediately (for testing purposes).

func (*Cron) Start

func (c *Cron) Start()

Start starts the cron scheduler. Jobs begin running according to their schedules.

func (*Cron) Stop

func (c *Cron) Stop()

Stop stops the cron scheduler gracefully. Waits for running jobs to complete.

type CronConfig

type CronConfig struct {
	Timezone   string `mapstructure:"timezone" yaml:"timezone"`
	MaxJobs    int    `mapstructure:"max_jobs" yaml:"max_jobs"`
	RecoverPan bool   `mapstructure:"recover_pan" yaml:"recover_pan"`
}

CronConfig defines the configuration for cron jobs.

type CronJob

type CronJob struct {
	Name string
	Spec string
	Func func() error
	// contains filtered or unexported fields
}

CronJob represents a scheduled cron job.

type CustomValidator

type CustomValidator func(interface{}) error

type DBHealth

type DBHealth struct {
	Status    string        `json:"status"`
	Latency   time.Duration `json:"latency,omitempty"`
	Error     string        `json:"error,omitempty"`
	ConnStats ConnStats     `json:"conn_stats,omitempty"`
}

DBHealth represents the health status of a database connection.

type Database

type Database struct {
	*gorm.DB
	// contains filtered or unexported fields
}

Database wraps a GORM DB instance with configuration and logging.

func NewDatabase

func NewDatabase(cfg *DatabaseConfig, logger *Logger) (*Database, error)

NewDatabase creates a new Database instance with the given configuration. Supports drivers: postgres, mysql, sqlite, sqlserver. Configures connection pooling with default or custom values.

func (*Database) Close

func (d *Database) Close() error

Close closes the underlying database connection.

func (*Database) ConnectWithRetry

func (d *Database) ConnectWithRetry(cfg *DatabaseConfig, logger *Logger, maxRetries int, retryDelay time.Duration) (*Database, error)

ConnectWithRetry attempts to connect to the database with retry logic. It will retry up to maxRetries times with the specified retryDelay between attempts. Returns the connected database or an error if all retries fail.

func (*Database) Database

func (d *Database) Database() (*sql.DB, error)

Database returns the underlying sql.DB instance for direct SQL operations.

func (*Database) Health

func (d *Database) Health(ctx context.Context) DBHealth

Health checks the database connection and returns health status. Includes latency measurement and connection pool stats.

func (*Database) Ping

func (d *Database) Ping(ctx context.Context) error

Ping pings the database to check connectivity.

func (*Database) PoolStats

func (d *Database) PoolStats(ctx context.Context) (ConnStats, error)

PoolStats returns connection pool statistics.

func (*Database) Transaction

func (d *Database) Transaction(ctx context.Context, fn func(ctx context.Context) error) error

Transaction executes a function within a database transaction. If the function returns an error, the transaction is rolled back. Otherwise, the transaction is committed. The transaction is passed to the function via context (ctxTxKey).

type DatabaseConfig

type DatabaseConfig struct {
	Driver          string `mapstructure:"driver" yaml:"driver" json:"driver"`
	Host            string `mapstructure:"host" yaml:"host" json:"host"`
	Port            int    `mapstructure:"port" yaml:"port" json:"port"`
	User            string `mapstructure:"user" yaml:"user" json:"user"`
	Password        string `mapstructure:"password" yaml:"password" json:"password"`
	DBName          string `mapstructure:"db_name" yaml:"db_name" json:"db_name"`
	SSLMode         string `mapstructure:"ssl_mode" yaml:"ssl_mode" json:"ssl_mode"`
	Charset         string `mapstructure:"charset" yaml:"charset" json:"charset"`
	Timezone        string `mapstructure:"timezone" yaml:"timezone" json:"timezone"`
	MaxOpenConns    int    `mapstructure:"max_open_conns" yaml:"max_open_conns" json:"max_open_conns"`
	MaxIdleConns    int    `mapstructure:"max_idle_conns" yaml:"max_idle_conns" json:"max_idle_conns"`
	ConnMaxLifetime int    `mapstructure:"conn_max_lifetime" yaml:"conn_max_lifetime" json:"conn_max_lifetime"`
	ConnMaxIdleTime int    `mapstructure:"conn_max_idle_time" yaml:"conn_max_idle_time" json:"conn_max_idle_time"`
	ConnectTimeout  int    `mapstructure:"connect_timeout" yaml:"connect_timeout" json:"connect_timeout"`
	QueryTimeout    int    `mapstructure:"query_timeout" yaml:"query_timeout" json:"query_timeout"`
	PoolMode        string `mapstructure:"pool_mode" yaml:"pool_mode" json:"pool_mode"`
	ConnectionName  string `mapstructure:"connection_name" yaml:"connection_name" json:"connection_name"`
	LogLevel        string `mapstructure:"log_level" yaml:"log_level" json:"log_level"`
	CustomLogger    bool   `mapstructure:"custom_logger" yaml:"custom_logger" json:"custom_logger"`
	Enabled         bool   `mapstructure:"enabled" yaml:"enabled" json:"enabled"`
}

DatabaseConfig defines the configuration for database connections.

type ErrorCode

type ErrorCode string

ErrorCode represents a category of errors. These codes are used for programmatic error handling and categorization.

const (
	ErrCodeInternal           ErrorCode = "INTERNAL_ERROR"
	ErrCodeValidation         ErrorCode = "VALIDATION_ERROR"
	ErrCodeNotFound           ErrorCode = "NOT_FOUND"
	ErrCodeUnauthorized       ErrorCode = "UNAUTHORIZED"
	ErrCodeForbidden          ErrorCode = "FORBIDDEN"
	ErrCodeBadRequest         ErrorCode = "BAD_REQUEST"
	ErrCodeConflict           ErrorCode = "CONFLICT"
	ErrCodeTooManyRequests    ErrorCode = "TOO_MANY_REQUESTS"
	ErrCodeServiceUnavailable ErrorCode = "SERVICE_UNAVAILABLE"
	ErrCodeInvalidToken       ErrorCode = "INVALID_TOKEN"
	ErrCodeTokenExpired       ErrorCode = "TOKEN_EXPIRED"
	ErrCodeRateLimitExceeded  ErrorCode = "RATE_LIMIT_EXCEEDED"
	ErrCodeDatabaseError      ErrorCode = "DATABASE_ERROR"
	ErrCodeCacheError         ErrorCode = "CACHE_ERROR"
	ErrCodeExternalAPI        ErrorCode = "EXTERNAL_API_ERROR"
	ErrCodeTimeout            ErrorCode = "TIMEOUT"
	ErrCodeCanceled           ErrorCode = "CANCELED"
	ErrCodeAlreadyExists      ErrorCode = "ALREADY_EXISTS"
	ErrCodeInvalidInput       ErrorCode = "INVALID_INPUT"
	ErrCodeGatewayTimeout     ErrorCode = "GATEWAY_TIMEOUT"
	ErrCodeMethodNotAllowed   ErrorCode = "METHOD_NOT_ALLOWED"
)

type ErrorHandler

type ErrorHandler struct {
	// contains filtered or unexported fields
}

ErrorHandler handles errors and converts them to HTTP responses. It uses the logger to log errors and can handle both XError and standard errors.

func NewErrorHandler

func NewErrorHandler(logger *Logger) *ErrorHandler

NewErrorHandler creates a new ErrorHandler with an optional logger.

func (*ErrorHandler) Handle

func (h *ErrorHandler) Handle(err error) (int, interface{})

Handle processes an error and returns the HTTP status code and response body. For XError, it extracts status code and message. For other errors, returns 500.

func (*ErrorHandler) HandleError

func (h *ErrorHandler) HandleError(c *Context, err error) error

HandleError processes an error and sends an appropriate JSON response to the client. If the error is an XError, it extracts status code and message. Adds the request ID to the response if available.

func (*ErrorHandler) Middleware

func (h *ErrorHandler) Middleware(next HandlerFunc) HandlerFunc

Middleware returns a HandlerFunc that wraps the next handler with error handling. Catches errors returned by the handler and processes them through HandleError.

type ErrorResponse

type ErrorResponse struct {
	Status  ResponseStatus  `json:"status"`
	Code    int             `json:"code"`
	Message string          `json:"message"`
	Errors  []ResponseError `json:"errors,omitempty"`
	Meta    *ResponseMeta   `json:"meta,omitempty"`
}

ErrorResponse is a simplified error response structure.

func NewErrorResponse

func NewErrorResponse(code int, msg string) *ErrorResponse

NewErrorResponse creates a new ErrorResponse with the given code and message.

func (*ErrorResponse) WithErrors

func (e *ErrorResponse) WithErrors(errors []ResponseError) *ErrorResponse

WithErrors adds errors to the ErrorResponse.

func (*ErrorResponse) Write

func (e *ErrorResponse) Write(w http.ResponseWriter) error

Write writes the ErrorResponse to the http.ResponseWriter.

type FileCache

type FileCache struct {
	// contains filtered or unexported fields
}

FileCache is a file-based cache implementation. Data is stored as JSON files in the specified directory.

func NewFileCache

func NewFileCache(basePath string, ttl int) (*FileCache, error)

func (*FileCache) Clear

func (c *FileCache) Clear(ctx context.Context) error

func (*FileCache) Close

func (c *FileCache) Close() error

func (*FileCache) Delete

func (c *FileCache) Delete(ctx context.Context, key string) error

func (*FileCache) Exists

func (c *FileCache) Exists(ctx context.Context, key string) (bool, error)

func (*FileCache) Get

func (c *FileCache) Get(ctx context.Context, key string) (interface{}, error)

func (*FileCache) Keys

func (c *FileCache) Keys(ctx context.Context, pattern string) ([]string, error)

func (*FileCache) MGet

func (c *FileCache) MGet(ctx context.Context, keys ...string) ([]interface{}, error)

func (*FileCache) MSet

func (c *FileCache) MSet(ctx context.Context, items map[string]interface{}) error

func (*FileCache) Set

func (c *FileCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

func (*FileCache) TTL

func (c *FileCache) TTL(ctx context.Context, key string) (time.Duration, error)

func (*FileCache) Tags

func (c *FileCache) Tags() CacheTags

type FormBinding

type FormBinding struct{}

func (*FormBinding) Bind

func (f *FormBinding) Bind(req *http.Request, v interface{}) error

func (*FormBinding) Name

func (f *FormBinding) Name() string

type GormLogger

type GormLogger struct {
	// contains filtered or unexported fields
}

GormLogger wraps the xcore Logger for GORM logging.

func (*GormLogger) Error

func (g *GormLogger) Error(ctx context.Context, msg string, args ...interface{})

func (*GormLogger) Info

func (g *GormLogger) Info(ctx context.Context, msg string, args ...interface{})

func (*GormLogger) LogMode

func (g *GormLogger) LogMode(level logger.LogLevel) logger.Interface

func (*GormLogger) Trace

func (g *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)

func (*GormLogger) Warn

func (g *GormLogger) Warn(ctx context.Context, msg string, args ...interface{})

type Graceful

type Graceful struct {
	// contains filtered or unexported fields
}

Graceful manages the graceful shutdown process for the application. It coordinates shutdown of multiple components including HTTP servers, databases, caches, WebSocket connections, and user-defined services.

The Graceful struct is safe for concurrent use and can be configured with custom timeouts for overall shutdown and individual callbacks.

func NewGraceful

func NewGraceful(timeout int, logger *Logger) *Graceful

NewGraceful creates a new Graceful shutdown handler with the specified timeout. The timeout parameter specifies the maximum time to wait for shutdown in seconds. If timeout <= 0, defaults to 30 seconds. The logger is optional and is used to log shutdown events.

func (*Graceful) AddCache

func (g *Graceful) AddCache(cache Cache)

AddCache registers a cache for graceful shutdown. The cache's Clear() method will be called during shutdown.

func (*Graceful) AddCallback

func (g *Graceful) AddCallback(fn func() error)

AddCallback registers a callback function to be called during graceful shutdown. Callbacks are executed in the order they are registered. Each callback should be non-blocking and complete within the callback timeout. If a callback returns an error, it is logged but shutdown continues.

func (*Graceful) AddCallbackFunc

func (g *Graceful) AddCallbackFunc(name string, fn func() error)

AddCallbackFunc registers a named callback function to be called during graceful shutdown. The name is used for logging purposes. Callbacks are executed in the order they are registered.

func (*Graceful) AddDatabase

func (g *Graceful) AddDatabase(db *Database)

AddDatabase registers a database for graceful shutdown. The database's Close() method will be called during shutdown.

func (*Graceful) AddServer

func (g *Graceful) AddServer(server *http.Server)

AddServer registers an HTTP server for graceful shutdown. The server's Shutdown() method will be called during shutdown with a context timeout. If server is nil, no action is taken.

func (*Graceful) AddWebSocket

func (g *Graceful) AddWebSocket(ws *WebSocket)

AddWebSocket registers a WebSocket for graceful shutdown. The WebSocket's Shutdown() method will be called during shutdown.

func (*Graceful) Run

func (g *Graceful) Run(servers ...*http.Server)

Run starts the graceful shutdown handler and listens for shutdown signals. It should be called after all components have been registered. The servers parameter is a list of additional HTTP servers to shutdown. Run returns immediately after setting up signal handling.

func (*Graceful) SetCallbackTimeout

func (g *Graceful) SetCallbackTimeout(timeout time.Duration) *Graceful

SetCallbackTimeout sets the maximum time allowed for each shutdown callback to execute. If a callback exceeds this timeout, it will be cancelled and the next callback will proceed. Default is 10 seconds if not set.

func (*Graceful) SetLogger

func (g *Graceful) SetLogger(logger *Logger)

SetLogger sets the logger for graceful shutdown events. If nil is passed, no logging occurs during shutdown.

func (*Graceful) Shutdown

func (g *Graceful) Shutdown()

Shutdown triggers a graceful shutdown manually. This is useful for testing or when shutdown needs to be triggered from code rather than receiving a signal.

func (*Graceful) SignalChannel

func (g *Graceful) SignalChannel() chan os.Signal

SignalChannel returns the signal channel for external monitoring. This allows other parts of the application to observe shutdown signals.

func (*Graceful) Wait

func (g *Graceful) Wait()

Wait blocks until the graceful shutdown process has completed. This should be called after Run() to keep the main goroutine alive until a shutdown signal is received.

type GracefulConfig

type GracefulConfig struct {
	Timeout int `mapstructure:"timeout" yaml:"timeout"`
}

GracefulConfig defines the graceful shutdown configuration.

type HTTPConfig

type HTTPConfig struct {
	Host         string           `mapstructure:"host" yaml:"host" json:"host"`
	Port         int              `mapstructure:"port" yaml:"port" json:"port"`
	ReadTimeout  int              `mapstructure:"read_timeout" yaml:"read_timeout" json:"read_timeout"`
	WriteTimeout int              `mapstructure:"write_timeout" yaml:"write_timeout" json:"write_timeout"`
	IdleTimeout  int              `mapstructure:"idle_timeout" yaml:"idle_timeout" json:"idle_timeout"`
	Middlewares  []string         `mapstructure:"middlewares" yaml:"middlewares" json:"middlewares"`
	CORS         *CORSConfig      `mapstructure:"cors" yaml:"cors" json:"cors"`
	RateLimit    *RateLimitConfig `mapstructure:"rate_limit" yaml:"rate_limit" json:"rate_limit"`
	StaticPath   string           `mapstructure:"static_path" yaml:"static_path" json:"static_path"`
	StaticDir    string           `mapstructure:"static_dir" yaml:"static_dir" json:"static_dir"`
	EnablePprof  bool             `mapstructure:"enable_pprof" yaml:"enable_pprof" json:"enable_pprof"`
}

HTTPConfig defines the configuration for the HTTP server.

type HandlerFunc

type HandlerFunc func(c *Context) error

HandlerFunc is the function signature for context-based handlers. It receives a Context and returns an error if something goes wrong.

type HeaderBinding

type HeaderBinding struct{}

func (*HeaderBinding) Bind

func (h *HeaderBinding) Bind(req *http.Request, v interface{}) error

func (*HeaderBinding) Name

func (h *HeaderBinding) Name() string

type HealthChecker

type HealthChecker interface {
	Health() ComponentHealth
}

type HealthStatus

type HealthStatus struct {
	Status     string                     `json:"status"`
	Timestamp  time.Time                  `json:"timestamp"`
	Components map[string]ComponentHealth `json:"components,omitempty"`
}

HealthStatus represents the overall health status of the application.

type Hub

type Hub struct {
	// contains filtered or unexported fields
}

func (*Hub) BroadcastToRoom

func (h *Hub) BroadcastToRoom(room string, message []byte)

func (*Hub) Stop

func (h *Hub) Stop()

type JSONBinding

type JSONBinding struct{}

func (*JSONBinding) Bind

func (j *JSONBinding) Bind(req *http.Request, v interface{}) error

func (*JSONBinding) Name

func (j *JSONBinding) Name() string

type JWTClaims

type JWTClaims struct {
	jwt.RegisteredClaims
	UserID   string `json:"user_id"`
	Username string `json:"username"`
	Email    string `json:"email"`
	Role     string `json:"role"`
}

JWTClaims represents the standard claims for JWT tokens. It extends jwt.RegisteredClaims with additional user fields.

func GetJWTClaims

func GetJWTClaims(ctx context.Context) *JWTClaims

GetJWTClaims retrieves JWT claims from the context. Uses the default context key "user".

func NewJWTClaims

func NewJWTClaims(userID, username, email, role string) *JWTClaims

NewJWTClaims creates a new JWTClaims instance with the provided user information. Sets default expiration to 24 hours from now.

func (*JWTClaims) GetEmail

func (c *JWTClaims) GetEmail() string

GetEmail returns the email from the claims.

func (*JWTClaims) GetRole

func (c *JWTClaims) GetRole() string

GetRole returns the role from the claims.

func (*JWTClaims) GetUserID

func (c *JWTClaims) GetUserID() string

GetUserID returns the user ID from the claims.

func (*JWTClaims) GetUsername

func (c *JWTClaims) GetUsername() string

GetUsername returns the username from the claims.

type JWTConfig

type JWTConfig struct {
	Secret            string
	SignKey           interface{}
	VerifyKey         interface{}
	Algorithm         string
	Expiration        time.Duration
	RefreshExpiration time.Duration
	CookieName        string
	HeaderName        string
	Prefix            string
	Claims            jwt.Claims
	Lookup            string
	ContextKey        string
	TokenLookup       string
	CookieHTTPOnly    bool
	CookieSameSite    http.SameSite
	CookieSecure      bool
	CookiePath        string
	CookieDomain      string
}

JWTConfig defines the configuration for JWT authentication. It includes secret keys, algorithm selection, expiration times, and cookie settings.

func NewJWTConfig

func NewJWTConfig(secret string) *JWTConfig

NewJWTConfig creates a JWTConfig with default values. Default settings: Algorithm: HS256, Expiration: 24h, HeaderName: Authorization, Prefix: Bearer

func (*JWTConfig) WithAlgorithm

func (c *JWTConfig) WithAlgorithm(alg string) *JWTConfig

WithAlgorithm sets the JWT signing algorithm. Supported values: HS256, HS384, HS512, RS256, RS384, RS512

func (*JWTConfig) WithContextKey

func (c *JWTConfig) WithContextKey(key string) *JWTConfig

WithContextKey sets the context key for storing claims.

func (*JWTConfig) WithCookieHTTPOnly

func (c *JWTConfig) WithCookieHTTPOnly(httpOnly bool) *JWTConfig

WithCookieHTTPOnly sets the HttpOnly flag for the token cookie.

func (*JWTConfig) WithCookieName

func (c *JWTConfig) WithCookieName(name string) *JWTConfig

WithCookieName sets the cookie name for token storage.

func (*JWTConfig) WithCookieSameSite

func (c *JWTConfig) WithCookieSameSite(sameSite http.SameSite) *JWTConfig

WithCookieSameSite sets the SameSite mode for the token cookie.

func (*JWTConfig) WithCookieSecure

func (c *JWTConfig) WithCookieSecure(secure bool) *JWTConfig

WithCookieSecure sets the Secure flag for the token cookie.

func (*JWTConfig) WithExpiration

func (c *JWTConfig) WithExpiration(exp time.Duration) *JWTConfig

WithExpiration sets the token expiration duration.

func (*JWTConfig) WithRSAPrivateKey

func (c *JWTConfig) WithRSAPrivateKey(pemData []byte) (*JWTConfig, error)

WithRSAPrivateKey sets the RSA private key from PEM-encoded data. The private key is used for signing JWT tokens.

func (*JWTConfig) WithRSAPublicKey

func (c *JWTConfig) WithRSAPublicKey(pemData []byte) (*JWTConfig, error)

WithRSAPublicKey sets the RSA public key from PEM-encoded data. The public key is used for verifying JWT signatures.

func (*JWTConfig) WithRSAPublicKeyFromPrivateKey

func (c *JWTConfig) WithRSAPublicKeyFromPrivateKey(pemData []byte) (*JWTConfig, error)

WithRSAPublicKeyFromPrivateKey derives the public key from the private key PEM data. This is a convenience method when you have only the private key.

type JWTMiddleware

type JWTMiddleware struct {
	// contains filtered or unexported fields
}

JWTMiddleware provides JWT authentication middleware for HTTP requests. It validates tokens from Authorization header or cookies and extracts claims into the request context. Use Exclude() to specify paths that should bypass JWT validation.

func NewJWTMiddleware

func NewJWTMiddleware(config *JWTConfig) *JWTMiddleware

NewJWTMiddleware creates a new JWT middleware with the given configuration. If config is nil, default configuration is used.

func (*JWTMiddleware) ClearTokenCookie

func (m *JWTMiddleware) ClearTokenCookie(w http.ResponseWriter)

ClearTokenCookie removes the JWT token cookie by setting MaxAge to -1. This effectively deletes the cookie from the client.

func (*JWTMiddleware) Exclude

func (m *JWTMiddleware) Exclude(paths ...string) *JWTMiddleware

Exclude adds paths that should bypass JWT authentication. Paths are matched using strings.HasPrefix, so "/path" matches "/path" and "/path/sub". Returns the middleware for method chaining.

func (*JWTMiddleware) ExtractClaims

func (m *JWTMiddleware) ExtractClaims(r *http.Request) (jwt.Claims, error)

ExtractClaims extracts and parses JWT claims from an HTTP request. It first extracts the token, then validates it.

func (*JWTMiddleware) GenerateToken

func (m *JWTMiddleware) GenerateToken(claims *JWTClaims) (string, error)

GenerateToken creates a new JWT token with the given claims. Sets Expiration and IssuedAt based on config.Expiration. Uses the algorithm specified in the configuration.

func (*JWTMiddleware) GenerateTokenWithClaims

func (m *JWTMiddleware) GenerateTokenWithClaims(claims jwt.Claims) (string, error)

GenerateTokenWithClaims generates a token from a generic jwt.Claims. Returns an error if the claims cannot be cast to JWTClaims.

func (*JWTMiddleware) Middleware

func (m *JWTMiddleware) Middleware(next http.Handler) http.Handler

Middleware returns an http.Handler that validates JWT tokens. It extracts tokens from the Authorization header (with Bearer prefix) or cookies. If the token is valid, claims are stored in the request context.

func (*JWTMiddleware) ParseToken

func (m *JWTMiddleware) ParseToken(tokenString string) (jwt.Claims, error)

ParseToken is a public method to parse a token string without going through middleware. Useful for manual token validation in handlers.

func (*JWTMiddleware) SetTokenCookie

func (m *JWTMiddleware) SetTokenCookie(w http.ResponseWriter, token string)

SetTokenCookie sets a cookie containing the JWT token. The cookie is configured according to the JWTConfig settings (name, path, expiry, etc.).

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger provides a structured logging interface based on zerolog. It supports different log levels, output destinations, and formatting options.

func DefaultLogger

func DefaultLogger() *Logger

DefaultLogger returns the global default logger. Creates one if not set.

func NewLogger

func NewLogger(cfg *LoggerConfig) (*Logger, error)

NewLogger creates a new Logger with the given configuration. If cfg is nil, default configuration is used:

  • Level: "info"
  • Output: "console"
  • Format: "console"

Supported output modes: "console", "file", "both" Supported formats: "console" (human-readable), "json" (structured)

func (*Logger) Debug

func (l *Logger) Debug() *zerolog.Event

Debug returns an event for logging debug-level messages.

func (*Logger) Error

func (l *Logger) Error() *zerolog.Event

Error returns an event for logging error-level messages. If an error logger is configured, logs to the error file.

func (*Logger) Fatal

func (l *Logger) Fatal() *zerolog.Event

Fatal returns an event for logging fatal-level messages. After logging, it calls os.Exit(1).

func (*Logger) Hook

func (l *Logger) Hook(h zerolog.Hook) *Logger

Hook adds a hook to the logger for custom log processing.

func (*Logger) Info

func (l *Logger) Info() *zerolog.Event

Info returns an event for logging info-level messages.

func (*Logger) Level

func (l *Logger) Level(level string) *Logger

Level creates a new Logger with a different log level.

func (*Logger) Log

func (l *Logger) Log() *zerolog.Event

Log returns a generic event for logging at any level.

func (*Logger) LogLevel

func (l *Logger) LogLevel() string

LogLevel returns the current log level as a string.

func (*Logger) Output

func (l *Logger) Output(w io.Writer) *Logger

Output creates a new Logger with a different output writer.

func (*Logger) Panic

func (l *Logger) Panic() *zerolog.Event

Panic returns an event for logging panic-level messages. After logging, it calls panic().

func (*Logger) Warn

func (l *Logger) Warn() *zerolog.Event

Warn returns an event for logging warning-level messages.

func (*Logger) With

func (l *Logger) With() zerolog.Context

With returns a contextual logger with additional fields.

func (*Logger) WithErrorFile

func (l *Logger) WithErrorFile(path string, maxSize, maxAge, maxBackups int, compress bool) error

WithErrorFile adds a separate error log file with its own configuration. The error log file captures only error-level logs. Default values are used if any parameter is <= 0:

  • path: "./logs/error.log"
  • maxSize: 10 MB
  • maxAge: 30 days
  • maxBackups: 3

type LoggerConfig

type LoggerConfig struct {
	Level          string               `mapstructure:"level" yaml:"level" json:"level"`
	Output         string               `mapstructure:"output" yaml:"output" json:"output"`
	Format         string               `mapstructure:"format" yaml:"format" json:"format"`
	FilePath       string               `mapstructure:"file_path" yaml:"file_path" json:"file_path"`
	MaxSize        int                  `mapstructure:"max_size" yaml:"max_size" json:"max_size"`
	MaxAge         int                  `mapstructure:"max_age" yaml:"max_age" json:"max_age"`
	MaxBackups     int                  `mapstructure:"max_backups" yaml:"max_backups" json:"max_backups"`
	Compress       bool                 `mapstructure:"compress" yaml:"compress" json:"compress"`
	Caller         bool                 `mapstructure:"caller" yaml:"caller" json:"caller"`
	TimestampField string               `mapstructure:"timestamp_field" yaml:"timestamp_field" json:"timestamp_field"`
	Console        *ConsoleLoggerConfig `mapstructure:"console" yaml:"console" json:"console"`
}

LoggerConfig defines the configuration for the logging system.

type MemoryCache

type MemoryCache struct {
	// contains filtered or unexported fields
}

MemoryCache is an in-memory cache implementation with TTL and tagging support. It uses a sync.RWMutex for concurrent access and runs a background goroutine to clean up expired entries.

func NewMemoryCache

func NewMemoryCache(cleanupInterval int) *MemoryCache

NewMemoryCache creates a new in-memory cache with the specified cleanup interval. If cleanupInterval <= 0, defaults to 60 seconds. Starts a background goroutine for cleaning up expired entries.

func (*MemoryCache) Clear

func (c *MemoryCache) Clear(ctx context.Context) error

Clear removes all entries from the cache.

func (*MemoryCache) Close

func (c *MemoryCache) Close() error

Close stops the background cleanup goroutine.

func (*MemoryCache) Delete

func (c *MemoryCache) Delete(ctx context.Context, key string) error

Delete removes a key from the cache.

func (*MemoryCache) Exists

func (c *MemoryCache) Exists(ctx context.Context, key string) (bool, error)

Exists checks if a key exists and is not expired. Returns true if the key exists and is valid, false otherwise.

func (*MemoryCache) Get

func (c *MemoryCache) Get(ctx context.Context, key string) (interface{}, error)

Get retrieves a value from the cache by key. Returns the value if found and not expired, or an error if not found or expired.

func (*MemoryCache) Keys

func (c *MemoryCache) Keys(ctx context.Context, pattern string) ([]string, error)

Keys returns all non-expired keys matching the pattern. If pattern is empty or "*", returns all keys.

func (*MemoryCache) MGet

func (c *MemoryCache) MGet(ctx context.Context, keys ...string) ([]interface{}, error)

MGet retrieves multiple values by keys. Returns a slice with nil values for missing or expired keys.

func (*MemoryCache) MSet

func (c *MemoryCache) MSet(ctx context.Context, items map[string]interface{}) error

MSet sets multiple key-value pairs at once. All keys are set with a default TTL of 1 year.

func (*MemoryCache) Set

func (c *MemoryCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

Set stores a value in the cache with the specified TTL. If ttl <= 0, defaults to 1 year.

func (*MemoryCache) TTL

func (c *MemoryCache) TTL(ctx context.Context, key string) (time.Duration, error)

TTL returns the remaining time-to-live for a key. Returns an error if the key is not found or has expired.

func (*MemoryCache) Tags

func (c *MemoryCache) Tags() CacheTags

Tags returns a CacheTags implementation for managing cache tags.

type MemorySessionStore

type MemorySessionStore struct {
	// contains filtered or unexported fields
}

func NewMemorySessionStore

func NewMemorySessionStore(cleanupInterval time.Duration) *MemorySessionStore

func (*MemorySessionStore) Delete

func (s *MemorySessionStore) Delete(ctx context.Context, id string) error

func (*MemorySessionStore) Get

func (s *MemorySessionStore) Get(ctx context.Context, id string) (*Session, error)

func (*MemorySessionStore) Set

func (s *MemorySessionStore) Set(ctx context.Context, session *Session) error

func (*MemorySessionStore) Stop

func (s *MemorySessionStore) Stop()

type MethodOverride

type MethodOverride struct{}

MethodOverride is a middleware that allows clients to override the HTTP method using the X-HTTP-Method-Override header. This is useful when clients can only send GET and POST requests but need to use PUT, PATCH, or DELETE.

func NewMethodOverride

func NewMethodOverride() *MethodOverride

NewMethodOverride creates a new MethodOverride middleware.

func (*MethodOverride) Middleware

func (m *MethodOverride) Middleware(next http.Handler) http.Handler

Middleware returns an http.Handler that allows method override via header. Only applies to POST requests with X-HTTP-Method-Override header.

type MetricCounter

type MetricCounter struct {
	// contains filtered or unexported fields
}

func NewMetricCounter

func NewMetricCounter(name, help string, labels ...string) *MetricCounter

func (*MetricCounter) Add

func (c *MetricCounter) Add(n uint64, labels ...string)

func (*MetricCounter) GetValue

func (c *MetricCounter) GetValue(labels ...string) uint64

func (*MetricCounter) Inc

func (c *MetricCounter) Inc(labels ...string)

func (*MetricCounter) String

func (c *MetricCounter) String() string

type MetricGauge

type MetricGauge struct {
	// contains filtered or unexported fields
}

func NewMetricGauge

func NewMetricGauge(name, help string) *MetricGauge

func (*MetricGauge) Dec

func (g *MetricGauge) Dec(labels ...string)

func (*MetricGauge) GetValue

func (g *MetricGauge) GetValue(labels ...string) int64

func (*MetricGauge) Inc

func (g *MetricGauge) Inc(labels ...string)

func (*MetricGauge) Set

func (g *MetricGauge) Set(val int64, labels ...string)

type MetricHistogram

type MetricHistogram struct {
	// contains filtered or unexported fields
}

func NewMetricHistogram

func NewMetricHistogram(name, help string, bounds []float64) *MetricHistogram

func (*MetricHistogram) GetCount

func (h *MetricHistogram) GetCount(labels ...string) uint64

func (*MetricHistogram) Observe

func (h *MetricHistogram) Observe(val float64, labels ...string)

type MetricsConfig

type MetricsConfig struct {
	Path             string
	EnableAPIMetrics bool
	EnableDBMetrics  bool
	Buckets          []float64
}

MetricsConfig defines configuration for metrics collection.

func NewMetricsConfig

func NewMetricsConfig() *MetricsConfig

NewMetricsConfig creates a default MetricsConfig.

type MetricsMiddleware

type MetricsMiddleware struct {
	// contains filtered or unexported fields
}

func NewMetricsMiddleware

func NewMetricsMiddleware(cfg *MetricsConfig) *MetricsMiddleware

func (*MetricsMiddleware) Middleware

func (m *MetricsMiddleware) Middleware(next http.Handler) http.Handler

type Pagination

type Pagination struct {
	Page    int   `json:"page"`
	PerPage int   `json:"per_page"`
	Total   int64 `json:"total"`
}

Pagination holds pagination parameters for response.

type PrometheusExporter

type PrometheusExporter struct {
	// contains filtered or unexported fields
}

func NewPrometheusExporter

func NewPrometheusExporter() *PrometheusExporter

func (*PrometheusExporter) RegisterCounter

func (p *PrometheusExporter) RegisterCounter(name, help string, labels ...string) *MetricCounter

func (*PrometheusExporter) RegisterGauge

func (p *PrometheusExporter) RegisterGauge(name, help string) *MetricGauge

func (*PrometheusExporter) RegisterHistogram

func (p *PrometheusExporter) RegisterHistogram(name, help string, bounds []float64) *MetricHistogram

func (*PrometheusExporter) ServeHTTP

func (p *PrometheusExporter) ServeHTTP(w http.ResponseWriter, r *http.Request)

type QueryBinding

type QueryBinding struct{}

func (*QueryBinding) Bind

func (q *QueryBinding) Bind(req *http.Request, v interface{}) error

func (*QueryBinding) Name

func (q *QueryBinding) Name() string

type RateLimitConfig

type RateLimitConfig struct {
	RequestsPerSecond int `mapstructure:"requests_per_second" yaml:"requests_per_second"`
	Burst             int `mapstructure:"burst" yaml:"burst"`
}

RateLimitConfig defines rate limiting configuration.

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter implements token bucket rate limiting. It can operate in global mode (single bucket for all requests) or per-IP mode (separate bucket for each client IP).

func NewRateLimiter

func NewRateLimiter(requestsPerSecond, burst int) *RateLimiter

NewRateLimiter creates a new RateLimiter with the specified requests per second and burst. Default values are used if rps <= 0 (100) or burst <= 0 (100). Use EnablePerIP() to switch to per-IP rate limiting.

func (*RateLimiter) EnablePerIP

func (r *RateLimiter) EnablePerIP() *RateLimiter

EnablePerIP enables per-IP rate limiting. Each client IP gets its own token bucket. Returns the RateLimiter for method chaining. Background goroutine starts to clean up stale IP entries (older than 10 minutes).

func (*RateLimiter) Middleware

func (r *RateLimiter) Middleware(next http.Handler) http.Handler

Middleware returns an http.Handler that enforces rate limiting. Adds rate limit headers to responses: X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset. Returns 429 Too Many Requests when rate limit is exceeded.

func (*RateLimiter) Reset

func (r *RateLimiter) Reset()

Reset clears all per-IP rate limit data. This is useful for testing or manually resetting the rate limiter.

func (*RateLimiter) Stop

func (r *RateLimiter) Stop()

Stop stops the background cleanup goroutine for per-IP rate limiting. Call this when shutting down the server.

type RealIP

type RealIP struct{}

RealIP is a middleware that extracts the real client IP address from request headers. It checks X-Real-IP header first, then X-Forwarded-For, and finally falls back to RemoteAddr. The extracted IP is stored in the request context (key: RealIPKey).

func NewRealIP

func NewRealIP() *RealIP

NewRealIP creates a new RealIP middleware.

func (*RealIP) Middleware

func (r *RealIP) Middleware(next http.Handler) http.Handler

Middleware returns an http.Handler that extracts the real client IP. The IP is stored in context with key RealIPKey.

type Recovery

type Recovery struct {
	// contains filtered or unexported fields
}

Recovery is a middleware that recovers from panics in the handler chain. When a panic occurs, it logs the error and returns a 503 Service Unavailable response. The logger is optional and can be nil.

func NewRecovery

func NewRecovery(logger *Logger) *Recovery

NewRecovery creates a new Recovery middleware with an optional logger. If logger is nil, panic information will not be logged.

func (*Recovery) Middleware

func (r *Recovery) Middleware(next http.Handler) http.Handler

Middleware returns an http.Handler that recovers from panics in the next handler. If a panic occurs, it logs the panic details and returns a 503 response.

type RedisCache

type RedisCache struct {
	// contains filtered or unexported fields
}

RedisCache is a cache implementation backed by Redis.

func NewRedisCache

func NewRedisCache(cfg *CacheConfig) (*RedisCache, error)

NewRedisCache creates a new Redis cache with the given configuration.

func (*RedisCache) Clear

func (c *RedisCache) Clear(ctx context.Context) error

func (*RedisCache) Close

func (c *RedisCache) Close() error

func (*RedisCache) Delete

func (c *RedisCache) Delete(ctx context.Context, key string) error

func (*RedisCache) Exists

func (c *RedisCache) Exists(ctx context.Context, key string) (bool, error)

func (*RedisCache) Get

func (c *RedisCache) Get(ctx context.Context, key string) (interface{}, error)

func (*RedisCache) Keys

func (c *RedisCache) Keys(ctx context.Context, pattern string) ([]string, error)

func (*RedisCache) MGet

func (c *RedisCache) MGet(ctx context.Context, keys ...string) ([]interface{}, error)

func (*RedisCache) MSet

func (c *RedisCache) MSet(ctx context.Context, items map[string]interface{}) error

func (*RedisCache) Set

func (c *RedisCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error

func (*RedisCache) TTL

func (c *RedisCache) TTL(ctx context.Context, key string) (time.Duration, error)

func (*RedisCache) Tags

func (c *RedisCache) Tags() CacheTags

type RequestBodyLogger

type RequestBodyLogger struct {
	// contains filtered or unexported fields
}

RequestBodyLogger logs HTTP request bodies.

func NewRequestBodyLogger

func NewRequestBodyLogger(logger *Logger) *RequestBodyLogger

NewRequestBodyLogger creates a new RequestBodyLogger. Logs up to maxBytes (default 1MB) of request body.

func (*RequestBodyLogger) Middleware

func (l *RequestBodyLogger) Middleware(next http.Handler) http.Handler

type RequestID

type RequestID struct{}

RequestID is a middleware that adds a unique request ID to each request. If the X-Request-ID header is already present, it uses that value. Otherwise, it generates a new UUID. The request ID is set in the response header and in the request context.

func NewRequestID

func NewRequestID() *RequestID

NewRequestID creates a new RequestID middleware.

func (*RequestID) Middleware

func (r *RequestID) Middleware(next http.Handler) http.Handler

Middleware returns an http.Handler that adds a request ID to the request. The ID is stored in the context (key: RequestIDKey) and response header.

type RequestLogger

type RequestLogger struct {
	// contains filtered or unexported fields
}

RequestLogger is a middleware that logs HTTP requests. It logs method, path, status code, duration, and client IP.

func NewRequestLogger

func NewRequestLogger(logger *Logger) *RequestLogger

NewRequestLogger creates a new RequestLogger middleware.

func (*RequestLogger) Middleware

func (l *RequestLogger) Middleware(next http.Handler) http.Handler

Middleware returns an http.Handler that logs request details.

type Response

type Response struct {
	Status  ResponseStatus  `json:"status"`
	Code    int             `json:"code,omitempty"`
	Message string          `json:"message,omitempty"`
	Data    interface{}     `json:"data,omitempty"`
	Errors  []ResponseError `json:"errors,omitempty"`
	Meta    *ResponseMeta   `json:"meta,omitempty"`
}

Response is the standard response structure for all API responses.

func AlreadyExists

func AlreadyExists(msg string) *Response

AlreadyExists creates an already exists error response. Uses StatusConflict (409). Default message is "Resource already exists".

func BadRequest

func BadRequest(msg string) *Response

BadRequest creates a bad request error response. Uses StatusBadRequest (400).

func Conflict

func Conflict(msg string) *Response

Conflict creates a conflict error response. Uses StatusConflict (409). Default message is "Resource conflict".

func Created

func Created(data interface{}, msg string) *Response

Created creates a response for successful resource creation. Uses StatusCreated (201). Default message is "Resource created successfully".

func Error

func Error(msg string) *Response

Error creates a generic error response. Uses StatusInternalServerError (500).

func ErrorWithCode

func ErrorWithCode(code int, msg string) *Response

ErrorWithCode creates an error response with a custom status code.

func Forbidden

func Forbidden(msg string) *Response

Forbidden creates a forbidden error response. Uses StatusForbidden (403). Default message is "Access forbidden".

func GatewayTimeout

func GatewayTimeout(msg string) *Response

GatewayTimeout creates a gateway timeout error response. Uses StatusGatewayTimeout (504). Default message is "Gateway timeout".

func MethodNotAllowed

func MethodNotAllowed(msg string) *Response

MethodNotAllowed creates a method not allowed error response. Uses StatusMethodNotAllowed (405). Default message is "Method not allowed".

func NewResponse

func NewResponse() *Response

NewResponse creates a new Response with default values. Sets Status to success and initializes empty Errors slice.

func NotFound

func NotFound(msg string) *Response

NotFound creates a not found error response. Uses StatusNotFound (404). Default message is "Resource not found".

func Paginate

func Paginate(data interface{}, page, perPage int, total int64) *Response

Paginate creates a paginated response with the given data and pagination info.

func RequestTimeout

func RequestTimeout(msg string) *Response

RequestTimeout creates a request timeout error response. Uses StatusRequestTimeout (408). Default message is "Request timeout".

func ServiceUnavailable

func ServiceUnavailable(msg string) *Response

ServiceUnavailable creates a service unavailable error response. Uses StatusServiceUnavailable (503). Default message is "Service temporarily unavailable".

func Success

func Success(data interface{}) *Response

Success creates a success response with the given data. Uses StatusOK (200).

func SuccessMessage

func SuccessMessage(msg string) *Response

SuccessMessage creates a success response with a message but no data.

func TooManyRequests

func TooManyRequests(msg string) *Response

TooManyRequests creates a rate limit error response. Uses StatusTooManyRequests (429). Default message is "Too many requests".

func Unauthorized

func Unauthorized(msg string) *Response

Unauthorized creates an unauthorized error response. Uses StatusUnauthorized (401). Default message is "Unauthorized access".

func ValidationErrorResp

func ValidationErrorResp(errors []ResponseError) *Response

ValidationErrorResp creates a validation error response. Uses StatusUnprocessableEntity (422).

func (*Response) ToJSON

func (r *Response) ToJSON() ([]byte, error)

ToJSON converts the Response to JSON bytes.

func (*Response) WithCode

func (r *Response) WithCode(code int) *Response

WithCode sets the HTTP status code for the response.

func (*Response) WithData

func (r *Response) WithData(data interface{}) *Response

WithData sets the data payload for the response.

func (*Response) WithError

func (r *Response) WithError(err ResponseError) *Response

WithError adds a single error to the response and sets status to error.

func (*Response) WithErrors

func (r *Response) WithErrors(errs []ResponseError) *Response

WithErrors adds multiple errors to the response and sets status to error.

func (*Response) WithMessage

func (r *Response) WithMessage(msg string) *Response

WithMessage sets a message for the response.

func (*Response) WithMeta

func (r *Response) WithMeta(meta *ResponseMeta) *Response

WithMeta sets the metadata for the response.

func (*Response) WithPageMeta

func (r *Response) WithPageMeta(page, perPage int, total int64) *Response

WithPageMeta sets pagination metadata (page, per_page, total, total_pages).

func (*Response) WithRequestID

func (r *Response) WithRequestID(id string) *Response

WithRequestID sets the request ID in the response metadata.

func (*Response) WithStatus

func (r *Response) WithStatus(status ResponseStatus) *Response

WithStatus sets the response status (success, error, fail).

func (*Response) Write

func (r *Response) Write(w http.ResponseWriter) error

Write writes the response to the http.ResponseWriter. Sets Content-Type header and writes status code if set.

type ResponseData

type ResponseData struct {
	Code    int             `json:"code"`
	Status  string          `json:"status"`
	Message string          `json:"message,omitempty"`
	Data    interface{}     `json:"data,omitempty"`
	Errors  []ResponseError `json:"errors,omitempty"`
	Meta    *ResponseMeta   `json:"meta,omitempty"`
}

ResponseData is a structured response data container. Deprecated: Use Response struct instead.

type ResponseError

type ResponseError struct {
	Field   string `json:"field,omitempty"`
	Message string `json:"message"`
	Code    string `json:"code,omitempty"`
}

ResponseError represents a field-level error in validation or processing.

type ResponseLogger

type ResponseLogger struct {
	// contains filtered or unexported fields
}

func NewResponseLogger

func NewResponseLogger(logger *Logger) *ResponseLogger

func (*ResponseLogger) Middleware

func (l *ResponseLogger) Middleware(next http.Handler) http.Handler

type ResponseMeta

type ResponseMeta struct {
	Page       int       `json:"page,omitempty"`
	PerPage    int       `json:"per_page,omitempty"`
	Total      int64     `json:"total,omitempty"`
	TotalPages int       `json:"total_pages,omitempty"`
	RequestID  string    `json:"request_id,omitempty"`
	Timestamp  time.Time `json:"timestamp"`
}

ResponseMeta contains metadata about the response including pagination and timestamps.

type ResponseStatus

type ResponseStatus string

ResponseStatus represents the status of a response.

const (
	StatusSuccess ResponseStatus = "success"
	StatusError   ResponseStatus = "error"
	StatusFail    ResponseStatus = "fail"
)

Standard response statuses.

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router wraps the gorilla/mux router and provides additional functionality. It manages HTTP server configuration, middleware registration, and route handling.

func NewRouter

func NewRouter(cfg *HTTPConfig) *Router

NewRouter creates a new Router with optional configuration. If cfg is nil, default configuration is used (Port: 8080). The router is initialized with default timeouts: ReadTimeout 30s, WriteTimeout 30s, IdleTimeout 60s.

func (*Router) DeleteHandler

func (r *Router) DeleteHandler(path string, handler HandlerFunc) *mux.Route

DeleteHandler registers a DELETE handler for the given path. The handler receives a Context and can return an error.

func (*Router) Favicon

func (r *Router) Favicon(file string)

Favicon serves a favicon file at /favicon.ico.

func (*Router) GetHandler

func (r *Router) GetHandler(path string, handler HandlerFunc) *mux.Route

GetHandler registers a GET handler for the given path. The handler receives a Context and can return an error.

func (*Router) Group

func (r *Router) Group(prefix string, fn func(*Router)) *Router

Group creates a route group with a common prefix. The fn callback receives a sub-router that inherits the parent's configuration. Returns the parent router for method chaining.

func (*Router) HandleContext

func (r *Router) HandleContext(path string, handler HandlerFunc) *mux.Route

HandleContext registers a context-based handler for the given path. The handler receives a Context and can return an error that is handled by the error handler.

func (*Router) HandleFunc

func (r *Router) HandleFunc(path string, handler func(http.ResponseWriter, *http.Request)) *mux.Route

HandleFunc registers a standard http.HandlerFunc for the given path. This bypasses the Context-based error handling.

func (*Router) Name

func (r *Router) Name(name string) *mux.Route

func (*Router) NotFoundHandler

func (r *Router) NotFoundHandler(handler http.HandlerFunc)

NotFoundHandler sets a custom handler for routes that don't match any registered route.

func (*Router) OptionsHandler

func (r *Router) OptionsHandler(path string, handler HandlerFunc) *mux.Route

OptionsHandler registers an OPTIONS handler for the given path. The handler receives a Context and can return an error.

func (*Router) PatchHandler

func (r *Router) PatchHandler(path string, handler HandlerFunc) *mux.Route

PatchHandler registers a PATCH handler for the given path. The handler receives a Context and can return an error.

func (*Router) PostHandler

func (r *Router) PostHandler(path string, handler HandlerFunc) *mux.Route

PostHandler registers a POST handler for the given path. The handler receives a Context and can return an error.

func (*Router) PutHandler

func (r *Router) PutHandler(path string, handler HandlerFunc) *mux.Route

PutHandler registers a PUT handler for the given path. The handler receives a Context and can return an error.

func (*Router) Router

func (r *Router) Router() *mux.Router

Router returns the underlying gorilla/mux Router instance. This allows direct access to mux router features if needed.

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, rq *http.Request)

ServeHTTP implements the http.Handler interface. Delegates to the underlying gorilla/mux router.

func (*Router) Server

func (r *Router) Server() *http.Server

Server returns the underlying HTTP server instance. Used for graceful shutdown and server configuration.

func (*Router) SetAddress

func (r *Router) SetAddress(addr string)

SetAddress sets the server address (host:port).

func (*Router) SetHandler

func (r *Router) SetHandler(handler http.Handler)

SetHandler sets the HTTP handler for the server.

func (*Router) SetIdleTimeout

func (r *Router) SetIdleTimeout(timeout int)

SetIdleTimeout sets the HTTP server's idle timeout in seconds.

func (*Router) SetReadTimeout

func (r *Router) SetReadTimeout(timeout int)

SetReadTimeout sets the HTTP server's read timeout in seconds.

func (*Router) SetWriteTimeout

func (r *Router) SetWriteTimeout(timeout int)

SetWriteTimeout sets the HTTP server's write timeout in seconds.

func (*Router) Static

func (r *Router) Static(path, dir string)

Static serves static files from the specified directory at the given URL path. The path parameter is the URL prefix, dir is the filesystem directory.

func (*Router) StaticFS

func (r *Router) StaticFS(path string, fs http.FileSystem)

StaticFS serves static files from a custom FileSystem at the given URL path.

func (*Router) StaticWithOptions

func (r *Router) StaticWithOptions(path, dir string, opts StaticOptions)

StaticWithOptions serves static files with custom options including index, fallback, and directory listing. Options: Index (default "index.html"), Fallback (SPA fallback), DirectoryListing (enable/disable).

func (*Router) Use

func (r *Router) Use(middleware ...mux.MiddlewareFunc)

Use adds one or more gorilla/mux middleware functions to the router. Middlewares are executed in the order they are added.

func (*Router) UseBodyParser

func (r *Router) UseBodyParser(maxSize int64)

UseBodyParser adds body parsing middleware to the router. The maxSize parameter specifies the maximum body size in bytes.

func (*Router) UseCORS

func (r *Router) UseCORS(cfg *CORSConfig)

UseCORS adds CORS middleware to the router with the given configuration.

func (*Router) UseCompression

func (r *Router) UseCompression(level int)

UseCompression adds gzip compression middleware to the router. The level parameter specifies compression level (gzip.DefaultCompression, etc.).

func (*Router) UseErrorHandler

func (r *Router) UseErrorHandler()

UseErrorHandler adds the error handler middleware to the router. Creates a Context for each request and attaches the logger.

func (*Router) UseHandler

func (r *Router) UseHandler(h http.Handler)

UseHandler adds a standard http.Handler to the middleware chain.

func (*Router) UseMethodOverride

func (r *Router) UseMethodOverride()

UseMethodOverride adds HTTP method override middleware to the router. Allows POST requests to override method via X-HTTP-Method-Override header.

func (*Router) UseMiddleware

func (r *Router) UseMiddleware(mw func(http.Handler) http.Handler)

UseMiddleware adds a middleware function (func(http.Handler) http.Handler) to the router.

func (*Router) UseRateLimiter

func (r *Router) UseRateLimiter(rps, burst int)

UseRateLimiter adds global rate limiting to the router. The rps parameter is requests per second, burst is the maximum burst size.

func (*Router) UseRateLimiterPerIP

func (r *Router) UseRateLimiterPerIP(rps, burst int)

UseRateLimiterPerIP adds per-IP rate limiting to the router. Each IP has its own token bucket with the specified rps and burst values.

func (*Router) UseRealIP

func (r *Router) UseRealIP()

UseRealIP adds real IP extraction middleware to the router. Extracts client IP from X-Real-IP or X-Forwarded-For headers.

func (*Router) UseRecovery

func (r *Router) UseRecovery()

UseRecovery adds panic recovery middleware to the router. Catches panics and returns a 500 Internal Server Error response. Requires the router to have a logger attached via WithLogger().

func (*Router) UseRequestID

func (r *Router) UseRequestID()

UseRequestID adds request ID middleware to the router. Adds X-Request-ID header to requests.

func (*Router) UseRequestLogger

func (r *Router) UseRequestLogger()

UseRequestLogger adds request logging middleware to the router. Requires the router to have a logger attached via WithLogger().

func (*Router) UseTimeout

func (r *Router) UseTimeout(timeout time.Duration)

UseTimeout adds request timeout middleware to the router. The timeout parameter specifies the maximum duration for request processing.

func (*Router) Vars

func (r *Router) Vars(rq *http.Request) map[string]string

Vars returns the route variables for the given request. Uses gorilla/mux's Vars function.

func (*Router) WithLogger

func (r *Router) WithLogger(logger *Logger) *Router

WithLogger attaches a logger to the router and initializes the error handler. The logger is used for request logging and error reporting.

type SecureHeadersMiddleware

type SecureHeadersMiddleware struct {
	// contains filtered or unexported fields
}

func NewSecureHeadersMiddleware

func NewSecureHeadersMiddleware() *SecureHeadersMiddleware

func (*SecureHeadersMiddleware) HandlerFunc

func (m *SecureHeadersMiddleware) HandlerFunc(w http.ResponseWriter, r *http.Request)

func (*SecureHeadersMiddleware) Middleware

func (m *SecureHeadersMiddleware) Middleware(next http.Handler) http.Handler

func (*SecureHeadersMiddleware) WithCSP

func (*SecureHeadersMiddleware) WithHSTS

func (m *SecureHeadersMiddleware) WithHSTS(maxAge int, includeSubDomains bool) *SecureHeadersMiddleware

type SecurityHeaders

type SecurityHeaders struct {
	ContentTypeNosniff      string
	XFrameOptions           string
	XContentTypeOptions     string
	XXSSProtection          string
	ReferrerPolicy          string
	PermissionsPolicy       string
	StrictTransportSecurity string
	ContentSecurityPolicy   string
}

SecurityHeaders defines security headers for HTTP responses. These headers help protect against common web vulnerabilities.

func NewHelmet

func NewHelmet() *SecurityHeaders

func NewSecurityHeaders

func NewSecurityHeaders() *SecurityHeaders

func (*SecurityHeaders) Middleware

func (s *SecurityHeaders) Middleware(next http.Handler) http.Handler

func (*SecurityHeaders) WithCSP

func (s *SecurityHeaders) WithCSP(csp string) *SecurityHeaders

func (*SecurityHeaders) WithHSTS

func (s *SecurityHeaders) WithHSTS(maxAge int, includeSubDomains bool) *SecurityHeaders

func (*SecurityHeaders) WithReferrerPolicy

func (s *SecurityHeaders) WithReferrerPolicy(policy string) *SecurityHeaders

func (*SecurityHeaders) WithXFO

func (s *SecurityHeaders) WithXFO(xfo string) *SecurityHeaders

type Service

type Service interface {
	Start() error
	Stop() error
	Name() string
}

Service defines the interface for application services. Implement this interface to create custom services that can be managed by the framework.

type ServiceManager

type ServiceManager struct {
	// contains filtered or unexported fields
}

ServiceManager manages the lifecycle of application services. It starts services in order and stops them in reverse order during shutdown.

func NewServiceManager

func NewServiceManager(logger *Logger) *ServiceManager

NewServiceManager creates a new ServiceManager with an optional logger.

func (*ServiceManager) Add

func (sm *ServiceManager) Add(service Service)

Add registers a service with the service manager. The service will be started when StartAll is called.

func (*ServiceManager) Count

func (sm *ServiceManager) Count() int

Count returns the number of registered services.

func (*ServiceManager) Services

func (sm *ServiceManager) Services() []Service

Services returns a slice of all registered services.

func (*ServiceManager) StartAll

func (sm *ServiceManager) StartAll() error

StartAll starts all registered services in order. Returns an error if any service fails to start.

func (*ServiceManager) StopAll

func (sm *ServiceManager) StopAll()

StopAll stops all registered services in reverse order. Logs errors but continues stopping remaining services.

type Session

type Session struct {
	ID        string
	Values    map[string]interface{}
	CreatedAt time.Time
	ExpiresAt time.Time
}

Session represents a user session with data and expiration.

func GetSession

func GetSession(ctx context.Context) *Session

func NewSession

func NewSession(id string) *Session

func (*Session) Clear

func (s *Session) Clear()

func (*Session) Delete

func (s *Session) Delete(key string)

func (*Session) Get

func (s *Session) Get(key string) interface{}

func (*Session) IsExpired

func (s *Session) IsExpired() bool

func (*Session) Len

func (s *Session) Len() int

func (*Session) Set

func (s *Session) Set(key string, value interface{})

type SessionManager

type SessionManager struct {
	// contains filtered or unexported fields
}

func NewSessionManager

func NewSessionManager(store SessionStore) *SessionManager

func (*SessionManager) Middleware

func (m *SessionManager) Middleware(next http.Handler) http.Handler

func (*SessionManager) WithCookieName

func (m *SessionManager) WithCookieName(name string) *SessionManager

func (*SessionManager) WithCookiePath

func (m *SessionManager) WithCookiePath(path string) *SessionManager

func (*SessionManager) WithHTTPOnly

func (m *SessionManager) WithHTTPOnly(httpOnly bool) *SessionManager

func (*SessionManager) WithMaxAge

func (m *SessionManager) WithMaxAge(maxAge int) *SessionManager

func (*SessionManager) WithSameSite

func (m *SessionManager) WithSameSite(sameSite http.SameSite) *SessionManager

func (*SessionManager) WithSecure

func (m *SessionManager) WithSecure(secure bool) *SessionManager

type SessionMiddleware

type SessionMiddleware struct {
	// contains filtered or unexported fields
}

func NewSessionMiddleware

func NewSessionMiddleware(manager *SessionManager) *SessionMiddleware

func (*SessionMiddleware) Middleware

func (m *SessionMiddleware) Middleware(next http.Handler) http.Handler

type SessionStore

type SessionStore interface {
	Get(ctx context.Context, id string) (*Session, error)
	Set(ctx context.Context, session *Session) error
	Delete(ctx context.Context, id string) error
}

SessionStore defines the interface for session storage implementations.

type ShutdownCallback

type ShutdownCallback func() error

ShutdownCallback is a function type that will be called during graceful shutdown. It should perform cleanup operations and return an error if the cleanup failed. The callback is called with a limited timeout, so it should be non-blocking.

type StaticOptions

type StaticOptions struct {
	Index            string
	Fallback         string
	DirectoryListing bool
}

StaticOptions defines options for static file serving with fallback and directory listing.

type StreamResponse

type StreamResponse struct {
	ContentType string
	Headers     map[string]string
	Data        interface{}
}

StreamResponse represents a streaming response configuration.

func (*StreamResponse) Write

type StructuredLogger

type StructuredLogger struct {
	// contains filtered or unexported fields
}

func NewStructuredLogger

func NewStructuredLogger(logger *Logger) *StructuredLogger

func (*StructuredLogger) Middleware

func (l *StructuredLogger) Middleware(next http.Handler) http.Handler

func (*StructuredLogger) WithBody

func (l *StructuredLogger) WithBody(include bool) *StructuredLogger

func (*StructuredLogger) WithHeader

func (l *StructuredLogger) WithHeader(include bool) *StructuredLogger

type Timeout

type Timeout struct {
	// contains filtered or unexported fields
}

Timeout is a middleware that adds a timeout to request processing. If the request takes longer than the timeout duration, it returns a 503 response. Uses context timeout and ensures the handler goroutine completes before returning.

func NewTimeout

func NewTimeout(timeout time.Duration) *Timeout

NewTimeout creates a new Timeout middleware with the specified duration. If timeout <= 0, defaults to 30 seconds.

func (*Timeout) Middleware

func (t *Timeout) Middleware(next http.Handler) http.Handler

Middleware returns an http.Handler that enforces a timeout on request processing. If the handler doesn't complete within the timeout, a 503 response is returned.

type ValidationError

type ValidationError struct {
	Field   string      `json:"field"`
	Message string      `json:"message"`
	Tag     string      `json:"tag,omitempty"`
	Value   interface{} `json:"value,omitempty"`
}

ValidationError represents a single field validation error.

func AsValidationError

func AsValidationError(err error) ([]ValidationError, bool)

func GetXErrorValidationErrors

func GetXErrorValidationErrors(err error) []ValidationError

GetXErrorValidationErrors extracts validation errors from an XError. Returns nil if the error is not an XError or has no validation errors.

func NewValidationError

func NewValidationError(field, message string) ValidationError

NewValidationError creates a ValidationError for a specific field. Used when reporting validation failures in request data.

type ValidationErrors

type ValidationErrors []ValidationError

func GetValidationErrors

func GetValidationErrors(err error) ValidationErrors

func (ValidationErrors) Error

func (v ValidationErrors) Error() string

func (ValidationErrors) ToResponseErrors

func (v ValidationErrors) ToResponseErrors() []ResponseError

type Validator

type Validator struct {
	// contains filtered or unexported fields
}

func NewValidator

func NewValidator() *Validator

func (*Validator) RegisterValidation

func (v *Validator) RegisterValidation(tag string, fn validator.Func) error

func (*Validator) ValidateStruct

func (v *Validator) ValidateStruct(s interface{}) error

func (*Validator) ValidateVar

func (v *Validator) ValidateVar(field interface{}, tag string) error

type ValidatorMiddleware

type ValidatorMiddleware struct {
	// contains filtered or unexported fields
}

func NewValidatorMiddleware

func NewValidatorMiddleware(logger *Logger) *ValidatorMiddleware

type WSAuthFunc

type WSAuthFunc func(r *http.Request) (bool, string)

type WSConnection

type WSConnection struct {
	// contains filtered or unexported fields
}

func NewWSConnection

func NewWSConnection(conn *websocket.Conn, ws *WebSocket, id string) *WSConnection

func (*WSConnection) Close

func (c *WSConnection) Close() error

func (*WSConnection) ID

func (c *WSConnection) ID() string

func (*WSConnection) JoinRoom

func (c *WSConnection) JoinRoom(room string)

func (*WSConnection) LeaveRoom

func (c *WSConnection) LeaveRoom(room string)

func (*WSConnection) ReadLoop

func (c *WSConnection) ReadLoop()

func (*WSConnection) RemoteAddr

func (c *WSConnection) RemoteAddr() string

func (*WSConnection) Rooms

func (c *WSConnection) Rooms() []string

func (*WSConnection) Send

func (c *WSConnection) Send(message []byte) bool

func (*WSConnection) SendBinary

func (c *WSConnection) SendBinary(msg []byte) bool

func (*WSConnection) SendJSON

func (c *WSConnection) SendJSON(v interface{}) error

func (*WSConnection) SendText

func (c *WSConnection) SendText(msg string) bool

func (*WSConnection) WriteLoop

func (c *WSConnection) WriteLoop()

type WSMessage

type WSMessage struct {
	Type    WSMessageType `json:"type"`
	Payload []byte        `json:"payload"`
	Room    string        `json:"room,omitempty"`
}

WSMessage represents a WebSocket message structure.

type WSMessageType

type WSMessageType int

WSMessageType represents the type of WebSocket message.

const (
	WSMessageText   WSMessageType = 1
	WSMessageBinary WSMessageType = 2
	WSMessageClose  WSMessageType = 3
	WSMessagePing   WSMessageType = 4
	WSMessagePong   WSMessageType = 5
)

WebSocket message types.

type WebSocket

type WebSocket struct {
	// contains filtered or unexported fields
}

func NewWebSocket

func NewWebSocket(cfg *WebsocketConfig, logger *Logger) *WebSocket

func (*WebSocket) Broadcast

func (ws *WebSocket) Broadcast(message []byte)

func (*WebSocket) BroadcastJSON

func (ws *WebSocket) BroadcastJSON(v interface{}) error

func (*WebSocket) BroadcastText

func (ws *WebSocket) BroadcastText(msg string)

func (*WebSocket) BroadcastToRoom

func (ws *WebSocket) BroadcastToRoom(room string, message []byte)

func (*WebSocket) BroadcastToRoomJSON

func (ws *WebSocket) BroadcastToRoomJSON(room string, v interface{}) error

func (*WebSocket) BroadcastToRoomText

func (ws *WebSocket) BroadcastToRoomText(room string, msg string)

func (*WebSocket) HandleFunc

func (ws *WebSocket) HandleFunc(w http.ResponseWriter, r *http.Request)

func (*WebSocket) HandleHTTP

func (ws *WebSocket) HandleHTTP(w http.ResponseWriter, r *http.Request)

func (*WebSocket) Hub

func (ws *WebSocket) Hub() *Hub

func (*WebSocket) ServeHTTP

func (ws *WebSocket) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*WebSocket) Shutdown

func (ws *WebSocket) Shutdown()

func (*WebSocket) WithAuth

func (ws *WebSocket) WithAuth(authFn WSAuthFunc) *WebSocket

func (*WebSocket) WithUpgrader

func (ws *WebSocket) WithUpgrader(upgrader websocket.Upgrader) *WebSocket

type WebsocketConfig

type WebsocketConfig struct {
	ReadBufferSize  int      `mapstructure:"read_buffer_size" yaml:"read_buffer_size" json:"read_buffer_size"`
	WriteBufferSize int      `mapstructure:"write_buffer_size" yaml:"write_buffer_size" json:"write_buffer_size"`
	PingInterval    int      `mapstructure:"ping_interval" yaml:"ping_interval" json:"ping_interval"`
	PongTimeout     int      `mapstructure:"pong_timeout" yaml:"pong_timeout" json:"pong_timeout"`
	MaxMessageSize  int64    `mapstructure:"max_message_size" yaml:"max_message_size" json:"max_message_size"`
	Enabled         bool     `mapstructure:"enabled" yaml:"enabled" json:"enabled"`
	AllowedOrigins  []string `mapstructure:"allowed_origins" yaml:"allowed_origins" json:"allowed_origins"`
}

WebsocketConfig defines the WebSocket configuration.

type XError

type XError struct {
	Code       ErrorCode              `json:"code"`
	Message    string                 `json:"message"`
	StatusCode int                    `json:"-"`
	Errors     []ValidationError      `json:"errors,omitempty"`
	Meta       map[string]interface{} `json:"meta,omitempty"`
	// contains filtered or unexported fields
}

XError is the custom error type used throughout the xcore framework. It provides structured error information including code, message, HTTP status, and optional details.

func ErrAlreadyExists

func ErrAlreadyExists(msg string) *XError

ErrAlreadyExists creates an "already exists" error with the given message.

func ErrBadRequest

func ErrBadRequest(msg string) *XError

ErrBadRequest creates a bad request error with an optional message. If msg is empty, defaults to "Bad request".

func ErrCache

func ErrCache(err error) *XError

ErrCache wraps a cache error with the appropriate code and message.

func ErrCanceled

func ErrCanceled(msg string) *XError

ErrCanceled creates a canceled operation error with the given message.

func ErrConflict

func ErrConflict(msg string) *XError

ErrConflict creates a conflict error with an optional message. If msg is empty, defaults to "Resource conflict".

func ErrDatabase

func ErrDatabase(err error) *XError

ErrDatabase wraps a database error with the appropriate code and message.

func ErrExternalAPI

func ErrExternalAPI(err error, service string) *XError

ErrExternalAPI wraps an external API error with the service name in the message.

func ErrForbidden

func ErrForbidden(msg string) *XError

ErrForbidden creates a forbidden error with an optional message. If msg is empty, defaults to "Access forbidden".

func ErrGatewayTimeout

func ErrGatewayTimeout(msg string) *XError

ErrGatewayTimeout creates a gateway timeout error with the given message.

func ErrInternal

func ErrInternal(msg string) *XError

ErrInternal creates an internal server error with the given message.

func ErrInvalidInput

func ErrInvalidInput(msg string) *XError

ErrInvalidInput creates an invalid input error with the given message.

func ErrMethodNotAllowed

func ErrMethodNotAllowed(msg string) *XError

ErrMethodNotAllowed creates a method not allowed error with the given message.

func ErrNotFound

func ErrNotFound(msg string) *XError

ErrNotFound creates a not found error with an optional message. If msg is empty, defaults to "Resource not found".

func ErrTimeout

func ErrTimeout(msg string) *XError

ErrTimeout creates a timeout error with the given message.

func ErrTooManyRequests

func ErrTooManyRequests(msg string) *XError

ErrTooManyRequests creates a rate limit error with an optional message. If msg is empty, defaults to "Too many requests".

func ErrUnauthorized

func ErrUnauthorized(msg string) *XError

ErrUnauthorized creates an unauthorized error with an optional message. If msg is empty, defaults to "Unauthorized access".

func ErrValidation

func ErrValidation(msg string) *XError

ErrValidation creates a validation error with the given message.

func GetXError

func GetXError(err error) *XError

GetXError extracts an XError from the error chain. Returns nil if not found.

func NewError

func NewError(code ErrorCode, message string) *XError

NewError creates a new XError with the given code and message. The HTTP status code is automatically determined from the error code.

func NewErrorWithStatus

func NewErrorWithStatus(code ErrorCode, message string, statusCode int) *XError

NewErrorWithStatus creates a new XError with a custom HTTP status code. Use this when you need to override the default status code mapping.

func WrapError

func WrapError(err error, code ErrorCode, message string) *XError

WrapError wraps an existing error with a new code and message. The original error is preserved and can be unwrapped.

func WrapErrorWithStatus

func WrapErrorWithStatus(err error, code ErrorCode, message string, statusCode int) *XError

WrapErrorWithStatus wraps an existing error with a custom HTTP status code.

func (*XError) Error

func (e *XError) Error() string

Error implements the error interface. Returns a formatted string with the error code and message. If there is a cause, it includes the underlying error.

func (*XError) Is

func (e *XError) Is(target error) bool

Is reports whether this error matches target. It matches by comparing error codes, or if target is a string, by checking if the error message contains that string.

func (*XError) Unwrap

func (e *XError) Unwrap() error

Unwrap returns the underlying cause of the error. Implements the standard errors.Unwrap interface.

func (*XError) WithErrors

func (e *XError) WithErrors(errs []ValidationError) *XError

WithErrors attaches validation errors to the error. Used for field-level validation error reporting.

func (*XError) WithMeta

func (e *XError) WithMeta(key string, value interface{}) *XError

WithMeta adds metadata key-value pairs to the error. This is useful for attaching additional context information.

Jump to

Keyboard shortcuts

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