Documentation
¶
Overview ¶
Package api provides HTTP server functionality for the xg2g application.
Package api provides HTTP server functionality for the xg2g application.
Package api provides HTTP server functionality for the xg2g application.
Package api provides HTTP server functionality for the xg2g application.
Package api provides HTTP server functionality for the xg2g application.
Index ¶
- Variables
- func AuthMiddleware(next http.Handler) http.Handler
- func NewRouter(cfg jobs.Config) http.Handler
- func RespondError(w http.ResponseWriter, r *http.Request, statusCode int, apiErr *APIError, ...)
- type APIError
- type AuditLogger
- type AuthService
- type CircuitBreaker
- type CircuitBreakerOption
- type ConfigHolder
- type DeprecationConfig
- type Deps
- type Logger
- type Metrics
- type RateLimitAuditor
- type RefreshService
- type Server
- func (s *Server) GetConfig() jobs.Config
- func (s *Server) GetStatus() jobs.Status
- func (s *Server) HDHomeRunServer() *hdhr.Server
- func (s *Server) HandleRefreshInternal(w http.ResponseWriter, r *http.Request)
- func (s *Server) Handler() http.Handler
- func (s *Server) SetAuditLogger(logger AuditLogger)
- func (s *Server) SetConfigHolder(holder ConfigHolder)
- func (s *Server) SetRefreshFunc(fn func(context.Context, jobs.Config) (*jobs.Status, error))
- func (s *Server) SetStatus(status jobs.Status)
- type Store
Constants ¶
This section is empty.
Variables ¶
var ( ErrUnauthorized = &APIError{ Code: "UNAUTHORIZED", Message: "Authentication required", } ErrForbidden = &APIError{ Code: "FORBIDDEN", Message: "Access denied", } ErrInvalidToken = &APIError{ Code: "INVALID_TOKEN", Message: "Invalid or expired API token", } // Resource errors ErrBouquetNotFound = &APIError{ Code: "BOUQUET_NOT_FOUND", Message: "Bouquet not found", } ErrServiceNotFound = &APIError{ Code: "SERVICE_NOT_FOUND", Message: "Service not found", } ErrFileNotFound = &APIError{ Code: "FILE_NOT_FOUND", Message: "File not found", } // Operation errors ErrRefreshInProgress = &APIError{ Code: "REFRESH_IN_PROGRESS", Message: "A refresh operation is already in progress", } ErrRefreshFailed = &APIError{ Code: "REFRESH_FAILED", Message: "Refresh operation failed", } ErrCircuitOpen = &APIError{ Code: "CIRCUIT_OPEN", Message: "Service temporarily unavailable due to repeated failures", } // Validation errors ErrInvalidInput = &APIError{ Code: "INVALID_INPUT", Message: "Invalid input parameters", } ErrPathTraversal = &APIError{ Code: "PATH_TRAVERSAL", Message: "Invalid file path - security violation", } // Rate limiting ErrRateLimitExceeded = &APIError{ Code: "RATE_LIMIT_EXCEEDED", Message: "Rate limit exceeded - too many requests", } // Generic errors ErrInternalServer = &APIError{ Code: "INTERNAL_SERVER_ERROR", Message: "An internal error occurred", } Code: "SERVICE_UNAVAILABLE", Message: "Service temporarily unavailable", } )
Common API error definitions
Functions ¶
func AuthMiddleware ¶
AuthMiddleware is a middleware that enforces API token authentication. It checks the "X-API-Token" header against the configured token. If the token is missing or invalid, it responds with an error.
func NewRouter ¶
NewRouter creates and configures a new router with all middlewares and handlers. This includes the logging middleware, security headers, and the API routes.
func RespondError ¶ added in v1.7.0
func RespondError(w http.ResponseWriter, r *http.Request, statusCode int, apiErr *APIError, details ...any)
RespondError sends a structured error response to the client. It automatically extracts the request ID from the context.
Types ¶
type APIError ¶ added in v1.7.0
type APIError struct {
Code string `json:"code"` // Machine-readable error code
Message string `json:"message"` // Human-readable error message
RequestID string `json:"request_id"` // Request ID for support/debugging
Details any `json:"details,omitempty"` // Optional additional context
}
APIError represents a structured error response for the API. It provides machine-readable error codes and human-friendly messages.
type AuditLogger ¶ added in v1.7.0
type AuditLogger interface {
ConfigReload(actor, result string, details map[string]string)
RefreshStart(actor string, bouquets []string)
RefreshComplete(actor string, channels, bouquets int, durationMS int64)
RefreshError(actor, reason string)
AuthSuccess(remoteAddr, endpoint string)
AuthFailure(remoteAddr, endpoint, reason string)
AuthMissing(remoteAddr, endpoint string)
RateLimitExceeded(remoteAddr, endpoint string)
}
AuditLogger interface for audit logging (optional).
type AuthService ¶ added in v1.7.0
type AuthService interface {
ValidateToken(ctx context.Context, token string) (principal string, err error)
Authorize(principal, action, resource string) bool
}
AuthService defines authentication and authorization interface
type CircuitBreaker ¶
type CircuitBreaker struct {
// contains filtered or unexported fields
}
CircuitBreaker is a minimal circuit breaker with three states: closed, open, half-open. It opens after 'threshold' consecutive failures and remains open for 'timeout'. After timeout, it transitions to half-open and allows a single trial. On success, it closes; on failure/panic, it opens again.
func NewCircuitBreaker ¶
func NewCircuitBreaker(threshold int, timeout time.Duration, opts ...CircuitBreakerOption) *CircuitBreaker
NewCircuitBreaker creates a new circuit breaker with the specified threshold and timeout. Accepts optional configuration via CircuitBreakerOption.
func (*CircuitBreaker) Call ¶
func (cb *CircuitBreaker) Call(fn func() error) (err error)
Call executes fn respecting the breaker state. It records failures and panics.
func (*CircuitBreaker) State ¶
func (cb *CircuitBreaker) State() string
State returns the current state (for debugging/metrics if needed).
type CircuitBreakerOption ¶ added in v1.7.3
type CircuitBreakerOption func(*CircuitBreaker)
CircuitBreakerOption is a functional option for CircuitBreaker configuration.
func WithClock ¶ added in v1.7.3
func WithClock(c clock) CircuitBreakerOption
WithClock sets a custom clock for testing.
type ConfigHolder ¶ added in v1.7.0
ConfigHolder interface allows hot configuration reloading without import cycles. Implemented by config.ConfigHolder.
type DeprecationConfig ¶ added in v1.5.0
type DeprecationConfig struct {
SunsetVersion string // Version when the deprecated API will be removed
SunsetDate string // Date when the deprecated API will be removed (RFC3339 format)
SuccessorPath string // Path to the successor API version
}
DeprecationConfig holds configuration for API deprecation warnings
type Deps ¶ added in v1.7.0
type Deps struct {
Log Logger
Metrics Metrics
Auth AuthService
Refresh RefreshService
Store Store
Config jobs.Config
}
Deps holds all dependencies for the API server
type Logger ¶ added in v1.7.0
type Logger interface {
Info() *zerolog.Event
Warn() *zerolog.Event
Error() *zerolog.Event
Debug() *zerolog.Event
}
Logger defines the logging interface for API handlers
type Metrics ¶ added in v1.7.0
type Metrics interface {
Inc(name string, labels ...string)
Observe(name string, v float64, labels ...string)
}
Metrics defines the metrics recording interface
type RateLimitAuditor ¶ added in v1.7.0
type RateLimitAuditor interface {
RateLimitExceeded(remoteAddr, endpoint string)
}
RateLimitAuditor provides audit logging for rate limit events
type RefreshService ¶ added in v1.7.0
type RefreshService interface {
Trigger(ctx context.Context, opts jobs.Options) (*jobs.Artifacts, error)
}
RefreshService defines the interface for triggering refresh operations
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server represents the HTTP API server for xg2g.
func (*Server) GetStatus ¶ added in v1.5.0
GetStatus returns the current server status (thread-safe) This method is exposed for use by versioned API handlers
func (*Server) HDHomeRunServer ¶ added in v1.4.0
HDHomeRunServer returns the HDHomeRun server instance if enabled
func (*Server) HandleRefreshInternal ¶ added in v1.5.0
func (s *Server) HandleRefreshInternal(w http.ResponseWriter, r *http.Request)
HandleRefreshInternal exposes the refresh handler for versioned APIs This allows different API versions to wrap the core refresh logic
func (*Server) Handler ¶
Handler returns the configured HTTP handler with all routes and middleware applied.
func (*Server) SetAuditLogger ¶ added in v1.7.0
func (s *Server) SetAuditLogger(logger AuditLogger)
SetAuditLogger sets the audit logger for security event logging (optional).
func (*Server) SetConfigHolder ¶ added in v1.7.0
func (s *Server) SetConfigHolder(holder ConfigHolder)
SetConfigHolder sets the config holder for hot reload support (optional). Must be called before routes are registered if hot reload is desired.
func (*Server) SetRefreshFunc ¶ added in v1.7.0
SetRefreshFunc sets a custom refresh function for testing This allows tests to stub the refresh operation
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package middleware provides HTTP middleware for the API server.
|
Package middleware provides HTTP middleware for the API server. |
|
Package v1 provides version 1 API handlers.
|
Package v1 provides version 1 API handlers. |