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
- Variables
- func CORSMiddlewareFunc(cfg *CORSConfig) func(http.Handler) http.Handler
- func GenerateSessionID() (string, error)
- func GetUserFromContext(ctx context.Context) (string, string, string)
- func GetUserIDFromContext(ctx context.Context) string
- func HealthMiddleware(app *App) func(http.Handler) http.Handler
- func HelmetCSPDefault() string
- func HelmetCSPStrict() string
- func IsXError(err error) bool
- func LoadConfigFromFile(path string, cfg interface{}) error
- func LoadConfigFromFiles(paths []string, cfg interface{}) error
- func LoadEnvConfig(prefix string, cfg interface{}) error
- func NoCache() func(http.Handler) http.Handler
- func RecordCacheHit()
- func RecordCacheMiss()
- func RecordDBQuery(query string, duration time.Duration)
- func RecordWSConnection()
- func RecordWSDisconnection()
- func RecordWSMessage()
- func RegisterCustomValidator(tag string, fn CustomValidator) error
- func SetDefaultLogger(logger *Logger)
- func StaticCache(maxAge int) func(http.Handler) http.Handler
- func Validate(s interface{}) error
- func ValidateContext(ctx context.Context, s interface{}) error
- func ValidateVar(field interface{}, tag string) error
- type App
- func (a *App) Cache() Cache
- func (a *App) Cron() *Cron
- func (a *App) Database() *Database
- func (a *App) Graceful() *Graceful
- func (a *App) Logger() *Logger
- func (a *App) Router() *Router
- func (a *App) Run() error
- func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (a *App) Services() *ServiceManager
- func (a *App) Use(mw func(http.Handler) http.Handler) *App
- func (a *App) WebSocket() *WebSocket
- func (a *App) WithCache(cfg *CacheConfig) *App
- func (a *App) WithConfig(cfg *Config) *App
- func (a *App) WithCron(cfg *CronConfig) *App
- func (a *App) WithDatabase(cfg *DatabaseConfig) *App
- func (a *App) WithGraceful(cfg *GracefulConfig) *App
- func (a *App) WithHTTP(cfg *HTTPConfig) *App
- func (a *App) WithLogger(cfg *LoggerConfig) *App
- func (a *App) WithService(service Service) *App
- func (a *App) WithWebSocket(cfg *WebsocketConfig) *App
- type Binding
- type BodyParser
- type CORSConfig
- type CORSMiddleware
- type CSRF
- type CSRFConfig
- type Cache
- type CacheConfig
- type CacheTags
- type ComponentHealth
- type Compression
- type Config
- type ConfigLoader
- func (cl *ConfigLoader) AddConfigPath(path string) *ConfigLoader
- func (cl *ConfigLoader) AutomaticEnv() *ConfigLoader
- func (cl *ConfigLoader) GetBool(key string) bool
- func (cl *ConfigLoader) GetInt(key string) int
- func (cl *ConfigLoader) GetString(key string) string
- func (cl *ConfigLoader) GetStringSlice(key string) []string
- func (cl *ConfigLoader) Load(cfg interface{}) error
- func (cl *ConfigLoader) LoadStrict(cfg interface{}) error
- func (cl *ConfigLoader) MergeConfigOverride(override map[string]interface{}) error
- func (cl *ConfigLoader) OnConfigChange(run func(e fsnotify.Event))
- func (cl *ConfigLoader) SetConfigFile(path string) *ConfigLoader
- func (cl *ConfigLoader) SetConfigType(typ string) *ConfigLoader
- func (cl *ConfigLoader) SetEnvKeyReplacer(oldNew ...string) *strings.Replacer
- func (cl *ConfigLoader) SetEnvPrefix(prefix string) *ConfigLoader
- func (cl *ConfigLoader) WatchConfig()
- type ConnStats
- type ConsoleLoggerConfig
- type Context
- func (c *Context) Abort()
- func (c *Context) AbortWithError(code int, err error) error
- func (c *Context) AbortWithStatus(code int)
- func (c *Context) AddError(err error)
- func (c *Context) BindBody(bindFunc func([]byte, interface{}) error, obj interface{}) error
- func (c *Context) BindForm(v interface{}) error
- func (c *Context) BindHeader(v interface{}) error
- func (c *Context) BindJSON(v interface{}) error
- func (c *Context) BindQuery(v interface{}) error
- func (c *Context) BindURI(v interface{}) error
- func (c *Context) Body() ([]byte, error)
- func (c *Context) Bytes(code int, contentType string, data []byte) error
- func (c *Context) ClientIP() string
- func (c *Context) ContentType() string
- func (c *Context) Context() context.Context
- func (c *Context) Cookie(name string) (*http.Cookie, error)
- func (c *Context) Cookies() []*http.Cookie
- func (c *Context) Data(code int, contentType string, data []byte) error
- func (c Context) Deadline() (deadline time.Time, ok bool)
- func (c *Context) DefaultParam(key, defaultValue string) string
- func (c *Context) DefaultPostForm(key, defaultValue string) string
- func (c *Context) DefaultQuery(key, defaultValue string) string
- func (c *Context) DeleteCookie(name string, path string, domains ...string)
- func (c Context) Done() <-chan struct{}
- func (c Context) Err() error
- func (c *Context) Error() error
- func (c *Context) Errors() []error
- func (c *Context) File(filepath string) error
- func (c *Context) FileInline(filepath string, name string) error
- func (c *Context) FormFile(key string) (multipart.File, *multipart.FileHeader, error)
- func (c *Context) Get(key string) interface{}
- func (c *Context) GetBody() ([]byte, error)
- func (c *Context) GetBool(key string) (bool, error)
- func (c *Context) GetFloat64(key string) (float64, error)
- func (c *Context) GetHeader(key string) string
- func (c *Context) GetHeaderReal(key string) string
- func (c *Context) GetInt(key string) (int, error)
- func (c *Context) GetInt64(key string) (int64, error)
- func (c *Context) GetQuery(key string) (string, bool)
- func (c *Context) HTML(code int, html string) error
- func (c *Context) Handler() HandlerFunc
- func (c *Context) Header(key, value string)
- func (c *Context) Host() string
- func (c *Context) IsAjax() bool
- func (c *Context) IsSecure() bool
- func (c *Context) IsWebSocket() string
- func (c *Context) JSON(code int, obj interface{}) error
- func (c *Context) JSONCreated(data interface{}, message string) error
- func (c *Context) JSONError(code int, message string) error
- func (c *Context) JSONP(callback string, obj interface{}) error
- func (c *Context) JSONPaginated(data interface{}, page, perPage int, total int64) error
- func (c *Context) JSONSuccess(data interface{}) error
- func (c *Context) JSONValidationError(errors []ResponseError) error
- func (c *Context) Logger() *Logger
- func (c *Context) Loggerf(format string, args ...interface{})
- func (c *Context) Method() string
- func (c *Context) MultipartForm() (*multipart.Form, error)
- func (c *Context) Next() error
- func (c *Context) NoContent(code int) error
- func (c *Context) Param(key string) string
- func (c *Context) PostForm(key string) string
- func (c *Context) QueryParam(key string) string
- func (c *Context) RealIP() string
- func (c *Context) Redirect(code int, url string) error
- func (c *Context) RemoteAddr() string
- func (c *Context) RequestID() string
- func (c *Context) Reset(w http.ResponseWriter, r *http.Request)
- func (c *Context) SendFile(file string, name string) error
- func (c *Context) ServeFile(file string)
- func (c *Context) Set(key string, value interface{})
- func (c *Context) SetCacheControl(seconds int)
- func (c *Context) SetContentType(contentType string)
- func (c *Context) SetCookie(cookie *http.Cookie)
- func (c *Context) SetLogger(logger *Logger)
- func (c *Context) Status(code int)
- func (c *Context) Stream(code int, contentType string, readFunc func(w io.Writer, fl http.Flusher) bool) error
- func (c *Context) String(code int, format string, args ...interface{}) error
- func (c *Context) URL() *url.URL
- func (c *Context) UserAgent() string
- func (c *Context) UserID() string
- func (c Context) Value(key interface{}) interface{}
- func (c *Context) XML(code int, obj interface{}) error
- type Cron
- func (c *Cron) AddFunc(name, spec string, fn func() error) (*CronJob, error)
- func (c *Cron) AddJob(name, spec string, fn func() error) (*CronJob, error)
- func (c *Cron) Entries() []cron.Entry
- func (c *Cron) ListJobs() []*CronJob
- func (c *Cron) Remove(id cron.EntryID)
- func (c *Cron) Run()
- func (c *Cron) Start()
- func (c *Cron) Stop()
- type CronConfig
- type CronJob
- type CustomValidator
- type DBHealth
- type Database
- func (d *Database) Close() error
- func (d *Database) ConnectWithRetry(cfg *DatabaseConfig, logger *Logger, maxRetries int, retryDelay time.Duration) (*Database, error)
- func (d *Database) Database() (*sql.DB, error)
- func (d *Database) Health(ctx context.Context) DBHealth
- func (d *Database) Ping(ctx context.Context) error
- func (d *Database) PoolStats(ctx context.Context) (ConnStats, error)
- func (d *Database) Transaction(ctx context.Context, fn func(ctx context.Context) error) error
- type DatabaseConfig
- type ErrorCode
- type ErrorHandler
- type ErrorResponse
- type FileCache
- func (c *FileCache) Clear(ctx context.Context) error
- func (c *FileCache) Close() error
- func (c *FileCache) Delete(ctx context.Context, key string) error
- func (c *FileCache) Exists(ctx context.Context, key string) (bool, error)
- func (c *FileCache) Get(ctx context.Context, key string) (interface{}, error)
- func (c *FileCache) Keys(ctx context.Context, pattern string) ([]string, error)
- func (c *FileCache) MGet(ctx context.Context, keys ...string) ([]interface{}, error)
- func (c *FileCache) MSet(ctx context.Context, items map[string]interface{}) error
- func (c *FileCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
- func (c *FileCache) TTL(ctx context.Context, key string) (time.Duration, error)
- func (c *FileCache) Tags() CacheTags
- type FormBinding
- type GormLogger
- func (g *GormLogger) Error(ctx context.Context, msg string, args ...interface{})
- func (g *GormLogger) Info(ctx context.Context, msg string, args ...interface{})
- func (g *GormLogger) LogMode(level logger.LogLevel) logger.Interface
- func (g *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)
- func (g *GormLogger) Warn(ctx context.Context, msg string, args ...interface{})
- type Graceful
- func (g *Graceful) AddCache(cache Cache)
- func (g *Graceful) AddCallback(fn func() error)
- func (g *Graceful) AddCallbackFunc(name string, fn func() error)
- func (g *Graceful) AddDatabase(db *Database)
- func (g *Graceful) AddServer(server *http.Server)
- func (g *Graceful) AddWebSocket(ws *WebSocket)
- func (g *Graceful) Run(servers ...*http.Server)
- func (g *Graceful) SetCallbackTimeout(timeout time.Duration) *Graceful
- func (g *Graceful) SetLogger(logger *Logger)
- func (g *Graceful) Shutdown()
- func (g *Graceful) SignalChannel() chan os.Signal
- func (g *Graceful) Wait()
- type GracefulConfig
- type HTTPConfig
- type HandlerFunc
- type HeaderBinding
- type HealthChecker
- type HealthStatus
- type Hub
- type JSONBinding
- type JWTClaims
- type JWTConfig
- func (c *JWTConfig) WithAlgorithm(alg string) *JWTConfig
- func (c *JWTConfig) WithContextKey(key string) *JWTConfig
- func (c *JWTConfig) WithCookieHTTPOnly(httpOnly bool) *JWTConfig
- func (c *JWTConfig) WithCookieName(name string) *JWTConfig
- func (c *JWTConfig) WithCookieSameSite(sameSite http.SameSite) *JWTConfig
- func (c *JWTConfig) WithCookieSecure(secure bool) *JWTConfig
- func (c *JWTConfig) WithExpiration(exp time.Duration) *JWTConfig
- func (c *JWTConfig) WithRSAPrivateKey(pemData []byte) (*JWTConfig, error)
- func (c *JWTConfig) WithRSAPublicKey(pemData []byte) (*JWTConfig, error)
- func (c *JWTConfig) WithRSAPublicKeyFromPrivateKey(pemData []byte) (*JWTConfig, error)
- type JWTMiddleware
- func (m *JWTMiddleware) ClearTokenCookie(w http.ResponseWriter)
- func (m *JWTMiddleware) Exclude(paths ...string) *JWTMiddleware
- func (m *JWTMiddleware) ExtractClaims(r *http.Request) (jwt.Claims, error)
- func (m *JWTMiddleware) GenerateToken(claims *JWTClaims) (string, error)
- func (m *JWTMiddleware) GenerateTokenWithClaims(claims jwt.Claims) (string, error)
- func (m *JWTMiddleware) Middleware(next http.Handler) http.Handler
- func (m *JWTMiddleware) ParseToken(tokenString string) (jwt.Claims, error)
- func (m *JWTMiddleware) SetTokenCookie(w http.ResponseWriter, token string)
- type Logger
- func (l *Logger) Debug() *zerolog.Event
- func (l *Logger) Error() *zerolog.Event
- func (l *Logger) Fatal() *zerolog.Event
- func (l *Logger) Hook(h zerolog.Hook) *Logger
- func (l *Logger) Info() *zerolog.Event
- func (l *Logger) Level(level string) *Logger
- func (l *Logger) Log() *zerolog.Event
- func (l *Logger) LogLevel() string
- func (l *Logger) Output(w io.Writer) *Logger
- func (l *Logger) Panic() *zerolog.Event
- func (l *Logger) Warn() *zerolog.Event
- func (l *Logger) With() zerolog.Context
- func (l *Logger) WithErrorFile(path string, maxSize, maxAge, maxBackups int, compress bool) error
- type LoggerConfig
- type MemoryCache
- func (c *MemoryCache) Clear(ctx context.Context) error
- func (c *MemoryCache) Close() error
- func (c *MemoryCache) Delete(ctx context.Context, key string) error
- func (c *MemoryCache) Exists(ctx context.Context, key string) (bool, error)
- func (c *MemoryCache) Get(ctx context.Context, key string) (interface{}, error)
- func (c *MemoryCache) Keys(ctx context.Context, pattern string) ([]string, error)
- func (c *MemoryCache) MGet(ctx context.Context, keys ...string) ([]interface{}, error)
- func (c *MemoryCache) MSet(ctx context.Context, items map[string]interface{}) error
- func (c *MemoryCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
- func (c *MemoryCache) TTL(ctx context.Context, key string) (time.Duration, error)
- func (c *MemoryCache) Tags() CacheTags
- type MemorySessionStore
- type MethodOverride
- type MetricCounter
- type MetricGauge
- type MetricHistogram
- type MetricsConfig
- type MetricsMiddleware
- type Pagination
- type PrometheusExporter
- func (p *PrometheusExporter) RegisterCounter(name, help string, labels ...string) *MetricCounter
- func (p *PrometheusExporter) RegisterGauge(name, help string) *MetricGauge
- func (p *PrometheusExporter) RegisterHistogram(name, help string, bounds []float64) *MetricHistogram
- func (p *PrometheusExporter) ServeHTTP(w http.ResponseWriter, r *http.Request)
- type QueryBinding
- type RateLimitConfig
- type RateLimiter
- type RealIP
- type Recovery
- type RedisCache
- func (c *RedisCache) Clear(ctx context.Context) error
- func (c *RedisCache) Close() error
- func (c *RedisCache) Delete(ctx context.Context, key string) error
- func (c *RedisCache) Exists(ctx context.Context, key string) (bool, error)
- func (c *RedisCache) Get(ctx context.Context, key string) (interface{}, error)
- func (c *RedisCache) Keys(ctx context.Context, pattern string) ([]string, error)
- func (c *RedisCache) MGet(ctx context.Context, keys ...string) ([]interface{}, error)
- func (c *RedisCache) MSet(ctx context.Context, items map[string]interface{}) error
- func (c *RedisCache) Set(ctx context.Context, key string, value interface{}, ttl time.Duration) error
- func (c *RedisCache) TTL(ctx context.Context, key string) (time.Duration, error)
- func (c *RedisCache) Tags() CacheTags
- type RequestBodyLogger
- type RequestID
- type RequestLogger
- type Response
- func AlreadyExists(msg string) *Response
- func BadRequest(msg string) *Response
- func Conflict(msg string) *Response
- func Created(data interface{}, msg string) *Response
- func Error(msg string) *Response
- func ErrorWithCode(code int, msg string) *Response
- func Forbidden(msg string) *Response
- func GatewayTimeout(msg string) *Response
- func MethodNotAllowed(msg string) *Response
- func NewResponse() *Response
- func NotFound(msg string) *Response
- func Paginate(data interface{}, page, perPage int, total int64) *Response
- func RequestTimeout(msg string) *Response
- func ServiceUnavailable(msg string) *Response
- func Success(data interface{}) *Response
- func SuccessMessage(msg string) *Response
- func TooManyRequests(msg string) *Response
- func Unauthorized(msg string) *Response
- func ValidationErrorResp(errors []ResponseError) *Response
- func (r *Response) ToJSON() ([]byte, error)
- func (r *Response) WithCode(code int) *Response
- func (r *Response) WithData(data interface{}) *Response
- func (r *Response) WithError(err ResponseError) *Response
- func (r *Response) WithErrors(errs []ResponseError) *Response
- func (r *Response) WithMessage(msg string) *Response
- func (r *Response) WithMeta(meta *ResponseMeta) *Response
- func (r *Response) WithPageMeta(page, perPage int, total int64) *Response
- func (r *Response) WithRequestID(id string) *Response
- func (r *Response) WithStatus(status ResponseStatus) *Response
- func (r *Response) Write(w http.ResponseWriter) error
- type ResponseData
- type ResponseError
- type ResponseLogger
- type ResponseMeta
- type ResponseStatus
- type Router
- func (r *Router) DeleteHandler(path string, handler HandlerFunc) *mux.Route
- func (r *Router) Favicon(file string)
- func (r *Router) GetHandler(path string, handler HandlerFunc) *mux.Route
- func (r *Router) Group(prefix string, fn func(*Router)) *Router
- func (r *Router) HandleContext(path string, handler HandlerFunc) *mux.Route
- func (r *Router) HandleFunc(path string, handler func(http.ResponseWriter, *http.Request)) *mux.Route
- func (r *Router) Name(name string) *mux.Route
- func (r *Router) NotFoundHandler(handler http.HandlerFunc)
- func (r *Router) OptionsHandler(path string, handler HandlerFunc) *mux.Route
- func (r *Router) PatchHandler(path string, handler HandlerFunc) *mux.Route
- func (r *Router) PostHandler(path string, handler HandlerFunc) *mux.Route
- func (r *Router) PutHandler(path string, handler HandlerFunc) *mux.Route
- func (r *Router) Router() *mux.Router
- func (r *Router) ServeHTTP(w http.ResponseWriter, rq *http.Request)
- func (r *Router) Server() *http.Server
- func (r *Router) SetAddress(addr string)
- func (r *Router) SetHandler(handler http.Handler)
- func (r *Router) SetIdleTimeout(timeout int)
- func (r *Router) SetReadTimeout(timeout int)
- func (r *Router) SetWriteTimeout(timeout int)
- func (r *Router) Static(path, dir string)
- func (r *Router) StaticFS(path string, fs http.FileSystem)
- func (r *Router) StaticWithOptions(path, dir string, opts StaticOptions)
- func (r *Router) Use(middleware ...mux.MiddlewareFunc)
- func (r *Router) UseBodyParser(maxSize int64)
- func (r *Router) UseCORS(cfg *CORSConfig)
- func (r *Router) UseCompression(level int)
- func (r *Router) UseErrorHandler()
- func (r *Router) UseHandler(h http.Handler)
- func (r *Router) UseMethodOverride()
- func (r *Router) UseMiddleware(mw func(http.Handler) http.Handler)
- func (r *Router) UseRateLimiter(rps, burst int)
- func (r *Router) UseRateLimiterPerIP(rps, burst int)
- func (r *Router) UseRealIP()
- func (r *Router) UseRecovery()
- func (r *Router) UseRequestID()
- func (r *Router) UseRequestLogger()
- func (r *Router) UseTimeout(timeout time.Duration)
- func (r *Router) Vars(rq *http.Request) map[string]string
- func (r *Router) WithLogger(logger *Logger) *Router
- type SecureHeadersMiddleware
- func (m *SecureHeadersMiddleware) HandlerFunc(w http.ResponseWriter, r *http.Request)
- func (m *SecureHeadersMiddleware) Middleware(next http.Handler) http.Handler
- func (m *SecureHeadersMiddleware) WithCSP(csp string) *SecureHeadersMiddleware
- func (m *SecureHeadersMiddleware) WithHSTS(maxAge int, includeSubDomains bool) *SecureHeadersMiddleware
- type SecurityHeaders
- func (s *SecurityHeaders) Middleware(next http.Handler) http.Handler
- func (s *SecurityHeaders) WithCSP(csp string) *SecurityHeaders
- func (s *SecurityHeaders) WithHSTS(maxAge int, includeSubDomains bool) *SecurityHeaders
- func (s *SecurityHeaders) WithReferrerPolicy(policy string) *SecurityHeaders
- func (s *SecurityHeaders) WithXFO(xfo string) *SecurityHeaders
- type Service
- type ServiceManager
- type Session
- type SessionManager
- func (m *SessionManager) Middleware(next http.Handler) http.Handler
- func (m *SessionManager) WithCookieName(name string) *SessionManager
- func (m *SessionManager) WithCookiePath(path string) *SessionManager
- func (m *SessionManager) WithHTTPOnly(httpOnly bool) *SessionManager
- func (m *SessionManager) WithMaxAge(maxAge int) *SessionManager
- func (m *SessionManager) WithSameSite(sameSite http.SameSite) *SessionManager
- func (m *SessionManager) WithSecure(secure bool) *SessionManager
- type SessionMiddleware
- type SessionStore
- type ShutdownCallback
- type StaticOptions
- type StreamResponse
- type StructuredLogger
- type Timeout
- type ValidationError
- type ValidationErrors
- type Validator
- type ValidatorMiddleware
- type WSAuthFunc
- type WSConnection
- func (c *WSConnection) Close() error
- func (c *WSConnection) ID() string
- func (c *WSConnection) JoinRoom(room string)
- func (c *WSConnection) LeaveRoom(room string)
- func (c *WSConnection) ReadLoop()
- func (c *WSConnection) RemoteAddr() string
- func (c *WSConnection) Rooms() []string
- func (c *WSConnection) Send(message []byte) bool
- func (c *WSConnection) SendBinary(msg []byte) bool
- func (c *WSConnection) SendJSON(v interface{}) error
- func (c *WSConnection) SendText(msg string) bool
- func (c *WSConnection) WriteLoop()
- type WSMessage
- type WSMessageType
- type WebSocket
- func (ws *WebSocket) Broadcast(message []byte)
- func (ws *WebSocket) BroadcastJSON(v interface{}) error
- func (ws *WebSocket) BroadcastText(msg string)
- func (ws *WebSocket) BroadcastToRoom(room string, message []byte)
- func (ws *WebSocket) BroadcastToRoomJSON(room string, v interface{}) error
- func (ws *WebSocket) BroadcastToRoomText(room string, msg string)
- func (ws *WebSocket) HandleFunc(w http.ResponseWriter, r *http.Request)
- func (ws *WebSocket) HandleHTTP(w http.ResponseWriter, r *http.Request)
- func (ws *WebSocket) Hub() *Hub
- func (ws *WebSocket) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (ws *WebSocket) Shutdown()
- func (ws *WebSocket) WithAuth(authFn WSAuthFunc) *WebSocket
- func (ws *WebSocket) WithUpgrader(upgrader websocket.Upgrader) *WebSocket
- type WebsocketConfig
- type XError
- func ErrAlreadyExists(msg string) *XError
- func ErrBadRequest(msg string) *XError
- func ErrCache(err error) *XError
- func ErrCanceled(msg string) *XError
- func ErrConflict(msg string) *XError
- func ErrDatabase(err error) *XError
- func ErrExternalAPI(err error, service string) *XError
- func ErrForbidden(msg string) *XError
- func ErrGatewayTimeout(msg string) *XError
- func ErrInternal(msg string) *XError
- func ErrInvalidInput(msg string) *XError
- func ErrMethodNotAllowed(msg string) *XError
- func ErrNotFound(msg string) *XError
- func ErrTimeout(msg string) *XError
- func ErrTooManyRequests(msg string) *XError
- func ErrUnauthorized(msg string) *XError
- func ErrValidation(msg string) *XError
- func GetXError(err error) *XError
- func NewError(code ErrorCode, message string) *XError
- func NewErrorWithStatus(code ErrorCode, message string, statusCode int) *XError
- func WrapError(err error, code ErrorCode, message string) *XError
- func WrapErrorWithStatus(err error, code ErrorCode, message string, statusCode int) *XError
Constants ¶
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.
const (
Version = "1.0.0"
)
Variables ¶
var ( ErrKeyNotFound = fmt.Errorf("key not found") ErrKeyExpired = fmt.Errorf("key expired") )
Cache errors.
var ( ErrInvalidToken = NewError(ErrCodeInvalidToken, "Invalid token") ErrTokenExpired = NewError(ErrCodeTokenExpired, "Token expired") )
Predefined errors for common cases.
Functions ¶
func CORSMiddlewareFunc ¶
func CORSMiddlewareFunc(cfg *CORSConfig) func(http.Handler) http.Handler
func GenerateSessionID ¶
func GetUserFromContext ¶
GetUserFromContext extracts user information (ID, username, email) from JWT claims. Returns empty strings if no claims found.
func GetUserIDFromContext ¶
GetUserIDFromContext extracts the user ID from JWT claims in the context. Returns empty string if no claims found.
func HelmetCSPDefault ¶
func HelmetCSPDefault() string
func HelmetCSPStrict ¶
func HelmetCSPStrict() string
func LoadConfigFromFile ¶
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 ¶
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 ¶
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 RecordCacheHit ¶
func RecordCacheHit()
func RecordCacheMiss ¶
func RecordCacheMiss()
func RecordDBQuery ¶
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 ValidateContext ¶
func ValidateVar ¶
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 ¶
Cache returns the cache instance. Returns nil if WithCache() has not been called or if initialization failed.
func (*App) Cron ¶
Cron returns the cron scheduler instance. Returns nil if WithCron() has not been called.
func (*App) Database ¶
Database returns the database instance. Returns nil if WithDatabase() has not been called or if initialization failed.
func (*App) Graceful ¶
Graceful returns the graceful shutdown handler instance. Returns nil if WithGraceful() has not been called.
func (*App) Logger ¶
Logger returns the application's logger instance. Returns nil if WithLogger() has not been called.
func (*App) 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 ¶
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:
- Marks the app as started (prevents multiple calls)
- Creates a default logger if none configured
- Creates a default graceful shutdown handler if none configured
- Registers database, cache, and WebSocket with graceful shutdown
- Starts cron jobs (if configured)
- Starts the HTTP server in a goroutine
- Starts all user-defined services
- Registers services shutdown with graceful handler
- Runs graceful shutdown and waits for completion
Returns an error if the app has already been started.
func (*App) Services ¶
func (a *App) Services() *ServiceManager
func (*App) Use ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) 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 ¶
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 ¶
AbortWithStatus sets the status code and stops the handler chain.
func (*Context) AddError ¶
AddError adds an error to the context's error list. Errors can be retrieved later using Error() or Errors().
func (*Context) BindForm ¶
BindForm parses form data (application/x-www-form-urlencoded or multipart/form-data) into the given struct and validates it.
func (*Context) BindHeader ¶
BindHeader parses HTTP headers into the given struct and validates it. Header keys are converted to lowercase for the struct mapping.
func (*Context) BindJSON ¶
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 ¶
BindQuery parses query string parameters into the given struct and validates it.
func (*Context) BindURI ¶
BindURI parses URL path parameters into the given struct and validates it.
func (*Context) ClientIP ¶
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 ¶
ContentType returns the Content-Type header of the request.
func (*Context) DefaultParam ¶
DefaultParam returns the value of a URL parameter or a default if not found.
func (*Context) DefaultPostForm ¶
DefaultPostForm returns the value of a POST form field or a default if not found.
func (*Context) DefaultQuery ¶
DefaultQuery returns the value of a query parameter or a default if not found.
func (*Context) DeleteCookie ¶
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) Error ¶
Error returns the first error in the context's error list. Returns nil if no errors have been added.
func (*Context) File ¶
File serves a file from disk at the given filepath. Sets appropriate Content-Type based on file extension.
func (*Context) FileInline ¶
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 ¶
FormFile returns the uploaded file and its metadata from a multipart form.
func (*Context) GetBody ¶
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) GetFloat64 ¶
GetFloat64 parses and returns a float64 from a query parameter.
func (*Context) GetHeaderReal ¶
GetHeaderReal returns the value of a response header.
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) IsAjax ¶
IsAjax checks if the request is an AJAX request by checking X-Requested-With header.
func (*Context) IsWebSocket ¶
IsWebSocket returns the value of the Upgrade header (e.g., "websocket").
func (*Context) JSON ¶
JSON sends a JSON response with the given status code and object. Automatically sets Content-Type to application/json.
func (*Context) JSONCreated ¶
JSONCreated sends a created response with the given data and message. Uses StatusCreated (201). Default message is "Created successfully".
func (*Context) JSONError ¶
JSONError sends an error response with the given status code and message.
func (*Context) JSONP ¶
JSONP sends a JSONP response with the given callback function and object. The response is wrapped in the callback function call.
func (*Context) JSONPaginated ¶
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 ¶
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) MultipartForm ¶
MultipartForm parses and returns the multipart form data. Uses 32MB as the max memory size for parsing.
func (*Context) Next ¶
Next executes the next handler in the chain. Used by middleware to pass control to the next handler.
func (*Context) NoContent ¶
NoContent sends a response with no body and the given status code. Common use: 204 No Content for successful DELETE operations.
func (*Context) QueryParam ¶
QueryParam returns the value of a query string parameter.
func (*Context) RealIP ¶
RealIP returns the real client IP from the context. This is set by the RealIP middleware.
func (*Context) Redirect ¶
Redirect redirects the client to the given URL with the specified status code. Common use: 301 Moved Permanently or 302 Found.
func (*Context) RemoteAddr ¶
RemoteAddr returns the network address of the client.
func (*Context) RequestID ¶
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 ¶
SendFile reads a file and sends it as a response. The filename is used to determine the Content-Type.
func (*Context) ServeFile ¶
ServeFile serves the given file using http.ServeFile. Convenience method that delegates to the standard library.
func (*Context) SetCacheControl ¶
SetCacheControl sets the Cache-Control header with the given max-age seconds.
func (*Context) SetContentType ¶
SetContentType sets the Content-Type header to the given value.
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 ¶
String sends a plain text response with the given status code and format. Supports printf-style formatting with args.
func (*Context) UserID ¶
UserID returns the authenticated user ID from the context. This is typically set after JWT authentication.
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) AddJob ¶
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) Run ¶
func (c *Cron) Run()
Run triggers all jobs to run immediately (for testing purposes).
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 ¶
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) 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 ¶
Database returns the underlying sql.DB instance for direct SQL operations.
func (*Database) Health ¶
Health checks the database connection and returns health status. Includes latency measurement and connection pool stats.
func (*Database) Transaction ¶
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" ErrCodeForbidden ErrorCode = "FORBIDDEN" ErrCodeBadRequest ErrorCode = "BAD_REQUEST" ErrCodeConflict ErrorCode = "CONFLICT" ErrCodeTooManyRequests ErrorCode = "TOO_MANY_REQUESTS" 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.
type FormBinding ¶
type FormBinding struct{}
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{})
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 ¶
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 ¶
AddCache registers a cache for graceful shutdown. The cache's Clear() method will be called during shutdown.
func (*Graceful) AddCallback ¶
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 ¶
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 ¶
AddDatabase registers a database for graceful shutdown. The database's Close() method will be called during shutdown.
func (*Graceful) AddServer ¶
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 ¶
AddWebSocket registers a WebSocket for graceful shutdown. The WebSocket's Shutdown() method will be called during shutdown.
func (*Graceful) Run ¶
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 ¶
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 ¶
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 ¶
SignalChannel returns the signal channel for external monitoring. This allows other parts of the application to observe shutdown signals.
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 ¶
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) 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 ¶
type JSONBinding ¶
type JSONBinding struct{}
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 ¶
GetJWTClaims retrieves JWT claims from the context. Uses the default context key "user".
func NewJWTClaims ¶
NewJWTClaims creates a new JWTClaims instance with the provided user information. Sets default expiration to 24 hours from now.
func (*JWTClaims) GetUsername ¶
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 ¶
NewJWTConfig creates a JWTConfig with default values. Default settings: Algorithm: HS256, Expiration: 24h, HeaderName: Authorization, Prefix: Bearer
func (*JWTConfig) WithAlgorithm ¶
WithAlgorithm sets the JWT signing algorithm. Supported values: HS256, HS384, HS512, RS256, RS384, RS512
func (*JWTConfig) WithContextKey ¶
WithContextKey sets the context key for storing claims.
func (*JWTConfig) WithCookieHTTPOnly ¶
WithCookieHTTPOnly sets the HttpOnly flag for the token cookie.
func (*JWTConfig) WithCookieName ¶
WithCookieName sets the cookie name for token storage.
func (*JWTConfig) WithCookieSameSite ¶
WithCookieSameSite sets the SameSite mode for the token cookie.
func (*JWTConfig) WithCookieSecure ¶
WithCookieSecure sets the Secure flag for the token cookie.
func (*JWTConfig) WithExpiration ¶
WithExpiration sets the token expiration duration.
func (*JWTConfig) WithRSAPrivateKey ¶
WithRSAPrivateKey sets the RSA private key from PEM-encoded data. The private key is used for signing JWT tokens.
func (*JWTConfig) WithRSAPublicKey ¶
WithRSAPublicKey sets the RSA public key from PEM-encoded data. The public key is used for verifying JWT signatures.
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 ¶
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) Error ¶
Error returns an event for logging error-level messages. If an error logger is configured, logs to the error file.
func (*Logger) Fatal ¶
Fatal returns an event for logging fatal-level messages. After logging, it calls os.Exit(1).
func (*Logger) Panic ¶
Panic returns an event for logging panic-level messages. After logging, it calls panic().
func (*Logger) WithErrorFile ¶
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 ¶
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 ¶
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 ¶
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) 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) 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).
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 ¶
NewRecovery creates a new Recovery middleware with an optional logger. If logger is nil, panic information will not be logged.
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) Close ¶
func (c *RedisCache) Close() error
func (*RedisCache) Get ¶
func (c *RedisCache) Get(ctx context.Context, key string) (interface{}, 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) 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.
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 ¶
AlreadyExists creates an already exists error response. Uses StatusConflict (409). Default message is "Resource already exists".
func BadRequest ¶
BadRequest creates a bad request error response. Uses StatusBadRequest (400).
func Conflict ¶
Conflict creates a conflict error response. Uses StatusConflict (409). Default message is "Resource conflict".
func Created ¶
Created creates a response for successful resource creation. Uses StatusCreated (201). Default message is "Resource created successfully".
func ErrorWithCode ¶
ErrorWithCode creates an error response with a custom status code.
func Forbidden ¶
Forbidden creates a forbidden error response. Uses StatusForbidden (403). Default message is "Access forbidden".
func GatewayTimeout ¶
GatewayTimeout creates a gateway timeout error response. Uses StatusGatewayTimeout (504). Default message is "Gateway timeout".
func MethodNotAllowed ¶
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 ¶
NotFound creates a not found error response. Uses StatusNotFound (404). Default message is "Resource not found".
func RequestTimeout ¶
RequestTimeout creates a request timeout error response. Uses StatusRequestTimeout (408). Default message is "Request timeout".
func ServiceUnavailable ¶
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 ¶
SuccessMessage creates a success response with a message but no data.
func TooManyRequests ¶
TooManyRequests creates a rate limit error response. Uses StatusTooManyRequests (429). Default message is "Too many requests".
func Unauthorized ¶
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) 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 ¶
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 ¶
WithPageMeta sets pagination metadata (page, per_page, total, total_pages).
func (*Response) WithRequestID ¶
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).
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) 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 ¶
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) 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 ¶
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 ¶
Server returns the underlying HTTP server instance. Used for graceful shutdown and server configuration.
func (*Router) SetAddress ¶
SetAddress sets the server address (host:port).
func (*Router) SetHandler ¶
SetHandler sets the HTTP handler for the server.
func (*Router) SetIdleTimeout ¶
SetIdleTimeout sets the HTTP server's idle timeout in seconds.
func (*Router) SetReadTimeout ¶
SetReadTimeout sets the HTTP server's read timeout in seconds.
func (*Router) SetWriteTimeout ¶
SetWriteTimeout sets the HTTP server's write timeout in seconds.
func (*Router) Static ¶
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 ¶
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 ¶
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 ¶
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 ¶
UseMiddleware adds a middleware function (func(http.Handler) http.Handler) to the router.
func (*Router) UseRateLimiter ¶
UseRateLimiter adds global rate limiting to the router. The rps parameter is requests per second, burst is the maximum burst size.
func (*Router) UseRateLimiterPerIP ¶
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 ¶
UseTimeout adds request timeout middleware to the router. The timeout parameter specifies the maximum duration for request processing.
func (*Router) Vars ¶
Vars returns the route variables for the given request. Uses gorilla/mux's Vars function.
func (*Router) WithLogger ¶
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 (m *SecureHeadersMiddleware) WithCSP(csp string) *SecureHeadersMiddleware
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 ¶
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 NewSession ¶
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 ¶
StaticOptions defines options for static file serving with fallback and directory listing.
type StreamResponse ¶
StreamResponse represents a streaming response configuration.
func (*StreamResponse) Write ¶
func (s *StreamResponse) Write(w http.ResponseWriter) error
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 ¶
NewTimeout creates a new Timeout middleware with the specified duration. If timeout <= 0, defaults to 30 seconds.
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 (*Validator) ValidateStruct ¶
func (*Validator) ValidateVar ¶
type ValidatorMiddleware ¶
type ValidatorMiddleware struct {
// contains filtered or unexported fields
}
func NewValidatorMiddleware ¶
func NewValidatorMiddleware(logger *Logger) *ValidatorMiddleware
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) BroadcastJSON ¶
func (*WebSocket) BroadcastText ¶
func (*WebSocket) BroadcastToRoom ¶
func (*WebSocket) BroadcastToRoomJSON ¶
func (*WebSocket) BroadcastToRoomText ¶
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) ServeHTTP ¶
func (ws *WebSocket) ServeHTTP(w http.ResponseWriter, r *http.Request)
func (*WebSocket) WithAuth ¶
func (ws *WebSocket) WithAuth(authFn WSAuthFunc) *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 ¶
ErrAlreadyExists creates an "already exists" error with the given message.
func ErrBadRequest ¶
ErrBadRequest creates a bad request error with an optional message. If msg is empty, defaults to "Bad request".
func ErrCanceled ¶
ErrCanceled creates a canceled operation error with the given message.
func ErrConflict ¶
ErrConflict creates a conflict error with an optional message. If msg is empty, defaults to "Resource conflict".
func ErrDatabase ¶
ErrDatabase wraps a database error with the appropriate code and message.
func ErrExternalAPI ¶
ErrExternalAPI wraps an external API error with the service name in the message.
func ErrForbidden ¶
ErrForbidden creates a forbidden error with an optional message. If msg is empty, defaults to "Access forbidden".
func ErrGatewayTimeout ¶
ErrGatewayTimeout creates a gateway timeout error with the given message.
func ErrInternal ¶
ErrInternal creates an internal server error with the given message.
func ErrInvalidInput ¶
ErrInvalidInput creates an invalid input error with the given message.
func ErrMethodNotAllowed ¶
ErrMethodNotAllowed creates a method not allowed error with the given message.
func ErrNotFound ¶
ErrNotFound creates a not found error with an optional message. If msg is empty, defaults to "Resource not found".
func ErrTimeout ¶
ErrTimeout creates a timeout error with the given message.
func ErrTooManyRequests ¶
ErrTooManyRequests creates a rate limit error with an optional message. If msg is empty, defaults to "Too many requests".
func ErrUnauthorized ¶
ErrUnauthorized creates an unauthorized error with an optional message. If msg is empty, defaults to "Unauthorized access".
func ErrValidation ¶
ErrValidation creates a validation error with the given message.
func NewError ¶
NewError creates a new XError with the given code and message. The HTTP status code is automatically determined from the error code.
func NewErrorWithStatus ¶
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 ¶
WrapError wraps an existing error with a new code and message. The original error is preserved and can be unwrapped.
func WrapErrorWithStatus ¶
WrapErrorWithStatus wraps an existing error with a custom HTTP status code.
func (*XError) Error ¶
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 ¶
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 ¶
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.
Source Files
¶
- cache.go
- cache_file.go
- cache_memory.go
- cache_redis.go
- config.go
- config_loader.go
- context.go
- context_requests.go
- context_response.go
- cors.go
- cron.go
- csrf.go
- database.go
- doc.go
- error.go
- graceful.go
- health.go
- jwt.go
- logger.go
- metrics.go
- middleware.go
- rate_limiter.go
- request_logger.go
- response.go
- router.go
- security.go
- service.go
- session.go
- validation.go
- version.go
- websocket.go
- xcore.go