Documentation
¶
Index ¶
- Constants
- func APIKeyFunc(r *http.Request) string
- func APIVersion(version string) func(next http.Handler) http.Handler
- func CORS(allowedOrigins []string) func(next http.Handler) http.Handler
- func ChainMiddleware(middlewares ...func(http.Handler) http.Handler) func(http.Handler) http.Handler
- func ContentTypeJSON(next http.Handler) http.Handler
- func Created(w http.ResponseWriter, data interface{}, opts ...ResponseOption) error
- func Error(w http.ResponseWriter, status int, code, message string, ...) error
- func ErrorHandler(debug bool) func(next http.Handler) http.Handler
- func Forbidden(w http.ResponseWriter, message string, opts ...ResponseOption) error
- func GetAPIVersion(ctx context.Context) string
- func GetClientIP(r *http.Request, trustedProxies []string) string
- func GetRequestStartTime(ctx context.Context) time.Time
- func Health() http.HandlerFunc
- func IPKeyFunc(r *http.Request) string
- func InternalServerError(w http.ResponseWriter, message string, opts ...ResponseOption) error
- func JSON(w http.ResponseWriter, status int, data interface{}, opts ...ResponseOption) error
- func JSONRequest(dst interface{}) func(next http.Handler) http.Handler
- func MethodNotAllowedHandler() http.HandlerFunc
- func NoContent(w http.ResponseWriter)
- func NotFound(w http.ResponseWriter, message string, opts ...ResponseOption) error
- func NotFoundHandler() http.HandlerFunc
- func Param(r *http.Request, key string) string
- func Query(r *http.Request, key string) string
- func QueryBool(r *http.Request, key string, defaultValue bool) bool
- func QueryInt(r *http.Request, key string, defaultValue int) int
- func RateLimitMiddleware(limiter RateLimiter, keyFunc func(*http.Request) string) func(http.Handler) http.Handler
- func RawJSON(w http.ResponseWriter, status int, data interface{}) error
- func RequestTimer(next http.Handler) http.Handler
- func RequireAuth(authFunc func(r *http.Request) (bool, error)) func(next http.Handler) http.Handler
- func SecureHeaders(next http.Handler) http.Handler
- func TrustedProxyIPKeyFunc(trustedProxies []string) func(*http.Request) string
- func Unauthorized(w http.ResponseWriter, message string, opts ...ResponseOption) error
- func UserKeyFunc(userIDFunc func(*http.Request) string) func(*http.Request) string
- func ValidationErrors(w http.ResponseWriter, errors []ValidationError, opts ...ResponseOption) error
- func VersionMiddleware(config *VersionConfig) func(next http.Handler) http.Handler
- func XML(w http.ResponseWriter, status int, data interface{}, opts ...ResponseOption) error
- type API
- func (api *API) Group(pattern string, middlewares ...func(http.Handler) http.Handler) *Router
- func (api *API) Mount(pattern string, handler http.Handler)
- func (api *API) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (api *API) SetupRoutes()
- func (api *API) Use(middlewares ...func(http.Handler) http.Handler)
- type APIConfig
- type ErrorInfo
- type Meta
- type RateLimitInfo
- type RateLimiter
- type ResourceController
- type Response
- type ResponseOption
- type Router
- func (r *Router) Delete(pattern string, handler http.HandlerFunc)
- func (r *Router) Get(pattern string, handler http.HandlerFunc)
- func (r *Router) Patch(pattern string, handler http.HandlerFunc)
- func (r *Router) Post(pattern string, handler http.HandlerFunc)
- func (r *Router) Put(pattern string, handler http.HandlerFunc)
- func (r *Router) Resource(pattern string, controller ResourceController)
- func (r *Router) Route(pattern string, fn func(r chi.Router))
- type SlidingWindow
- type TokenBucket
- type ValidationError
- type VersionConfig
- type VersionNegotiator
- type VersionRouter
- func (vr *VersionRouter) DeprecateVersion(version, sunsetDate string)
- func (vr *VersionRouter) GetVersion(r *http.Request) string
- func (vr *VersionRouter) Mount(pattern string, handler http.Handler)
- func (vr *VersionRouter) RegisterVersion(version string) *chi.Mux
- func (vr *VersionRouter) ServeHTTP(w http.ResponseWriter, r *http.Request)
Constants ¶
const ( // ContextKeyAPIVersion stores the API version in context ContextKeyAPIVersion contextKey = "api_version" // ContextKeyRequestID stores the request ID in context ContextKeyRequestID contextKey = "request_id" // ContextKeyStartTime stores the request start time ContextKeyStartTime contextKey = "start_time" )
Variables ¶
This section is empty.
Functions ¶
func APIKeyFunc ¶
APIKeyFunc returns API key as rate limit key
func APIVersion ¶
APIVersion middleware adds API version to context
func ChainMiddleware ¶
func ChainMiddleware(middlewares ...func(http.Handler) http.Handler) func(http.Handler) http.Handler
ChainMiddleware chains multiple middleware functions
func ContentTypeJSON ¶
ContentTypeJSON ensures JSON content type for requests
func Created ¶
func Created(w http.ResponseWriter, data interface{}, opts ...ResponseOption) error
Created sends a 201 response
func Error ¶
func Error(w http.ResponseWriter, status int, code, message string, details map[string]interface{}, opts ...ResponseOption) error
Error sends an error response
func ErrorHandler ¶
ErrorHandler handles panics and errors in API routes
func Forbidden ¶
func Forbidden(w http.ResponseWriter, message string, opts ...ResponseOption) error
Forbidden sends a 403 response
func GetAPIVersion ¶
GetAPIVersion gets API version from context
func GetClientIP ¶
GetClientIP extracts the real client IP with optional trusted proxy validation
func GetRequestStartTime ¶
GetRequestStartTime gets request start time from context
func InternalServerError ¶
func InternalServerError(w http.ResponseWriter, message string, opts ...ResponseOption) error
InternalServerError sends a 500 response
func JSON ¶
func JSON(w http.ResponseWriter, status int, data interface{}, opts ...ResponseOption) error
JSON sends a JSON response
func JSONRequest ¶
JSONRequest parses JSON request body
func MethodNotAllowedHandler ¶
func MethodNotAllowedHandler() http.HandlerFunc
MethodNotAllowedHandler returns a 405 handler
func NotFound ¶
func NotFound(w http.ResponseWriter, message string, opts ...ResponseOption) error
NotFound sends a 404 response
func NotFoundHandler ¶
func NotFoundHandler() http.HandlerFunc
NotFoundHandler returns a 404 handler
func RateLimitMiddleware ¶
func RateLimitMiddleware(limiter RateLimiter, keyFunc func(*http.Request) string) func(http.Handler) http.Handler
RateLimitMiddleware creates rate limiting middleware
func RawJSON ¶
func RawJSON(w http.ResponseWriter, status int, data interface{}) error
RawJSON sends raw JSON without wrapper
func RequestTimer ¶
RequestTimer adds timing information to responses
func RequireAuth ¶
RequireAuth checks for authentication
func SecureHeaders ¶
SecureHeaders adds security headers
func TrustedProxyIPKeyFunc ¶
TrustedProxyIPKeyFunc returns a key function that validates proxy headers
func Unauthorized ¶
func Unauthorized(w http.ResponseWriter, message string, opts ...ResponseOption) error
Unauthorized sends a 401 response
func UserKeyFunc ¶
UserKeyFunc returns user ID as rate limit key (requires authentication)
func ValidationErrors ¶
func ValidationErrors(w http.ResponseWriter, errors []ValidationError, opts ...ResponseOption) error
ValidationErrors sends validation error response
func VersionMiddleware ¶
func VersionMiddleware(config *VersionConfig) func(next http.Handler) http.Handler
VersionMiddleware adds version to context and validates it
func XML ¶
func XML(w http.ResponseWriter, status int, data interface{}, opts ...ResponseOption) error
XML sends an XML response
Types ¶
type API ¶
type API struct {
Router *chi.Mux
Config *APIConfig
VersionRouter *VersionRouter
RateLimiter RateLimiter
// contains filtered or unexported fields
}
API represents the main API structure
type APIConfig ¶
type APIConfig struct {
Version string
RateLimitPerMin int
EnableCORS bool
AllowedOrigins []string
EnableMetrics bool
Debug bool
}
APIConfig holds API configuration
type ErrorInfo ¶
type ErrorInfo struct {
Code string `json:"code" xml:"code"`
Message string `json:"message" xml:"message"`
Details map[string]interface{} `json:"details,omitempty" xml:"details,omitempty"`
}
ErrorInfo contains error details
type Meta ¶
type Meta struct {
Page int `json:"page,omitempty" xml:"page,omitempty"`
PerPage int `json:"per_page,omitempty" xml:"per_page,omitempty"`
Total int `json:"total,omitempty" xml:"total,omitempty"`
TotalPages int `json:"total_pages,omitempty" xml:"total_pages,omitempty"`
Version string `json:"version,omitempty" xml:"version,omitempty"`
RequestID string `json:"request_id,omitempty" xml:"request_id,omitempty"`
}
Meta contains pagination and other metadata
type RateLimitInfo ¶
RateLimitInfo contains rate limit information
type RateLimiter ¶
type RateLimiter interface {
Allow(key string) (bool, *RateLimitInfo)
Reset(key string)
}
RateLimiter interface for different rate limiting strategies
type ResourceController ¶
type ResourceController interface {
List(w http.ResponseWriter, r *http.Request)
Create(w http.ResponseWriter, r *http.Request)
Get(w http.ResponseWriter, r *http.Request)
Update(w http.ResponseWriter, r *http.Request)
Delete(w http.ResponseWriter, r *http.Request)
}
ResourceController defines methods for a RESTful resource
type Response ¶
type Response struct {
Success bool `json:"success" xml:"success"`
Data interface{} `json:"data,omitempty" xml:"data,omitempty"`
Error *ErrorInfo `json:"error,omitempty" xml:"error,omitempty"`
Meta *Meta `json:"meta,omitempty" xml:"meta,omitempty"`
Timestamp int64 `json:"timestamp" xml:"timestamp"`
}
Response represents a standard API response
type ResponseOption ¶
type ResponseOption func(*Response)
ResponseOption allows customizing responses
func WithPagination ¶
func WithPagination(page, perPage, total int) ResponseOption
WithPagination adds pagination metadata
func WithRequestID ¶
func WithRequestID(requestID string) ResponseOption
WithRequestID adds request ID to metadata
func WithVersion ¶
func WithVersion(version string) ResponseOption
WithVersion adds API version to metadata
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router represents an API route group
func (*Router) Delete ¶
func (r *Router) Delete(pattern string, handler http.HandlerFunc)
Delete registers a DELETE route
func (*Router) Get ¶
func (r *Router) Get(pattern string, handler http.HandlerFunc)
Get registers a GET route
func (*Router) Patch ¶
func (r *Router) Patch(pattern string, handler http.HandlerFunc)
Patch registers a PATCH route
func (*Router) Post ¶
func (r *Router) Post(pattern string, handler http.HandlerFunc)
Post registers a POST route
func (*Router) Put ¶
func (r *Router) Put(pattern string, handler http.HandlerFunc)
Put registers a PUT route
func (*Router) Resource ¶
func (r *Router) Resource(pattern string, controller ResourceController)
Resource creates RESTful routes for a resource
type SlidingWindow ¶
type SlidingWindow struct {
// contains filtered or unexported fields
}
SlidingWindow implements sliding window rate limiting
func NewSlidingWindow ¶
func NewSlidingWindow(limit int, duration time.Duration) *SlidingWindow
NewSlidingWindow creates a new sliding window rate limiter
func (*SlidingWindow) Allow ¶
func (sw *SlidingWindow) Allow(key string) (bool, *RateLimitInfo)
Allow checks if request is allowed
func (*SlidingWindow) Reset ¶
func (sw *SlidingWindow) Reset(key string)
Reset resets the window for a key
func (*SlidingWindow) Stop ¶
func (sw *SlidingWindow) Stop()
Stop gracefully stops the sliding window and cleans up resources
type TokenBucket ¶
type TokenBucket struct {
// contains filtered or unexported fields
}
TokenBucket implements token bucket rate limiting
func NewTokenBucket ¶
func NewTokenBucket(rate, capacity int, interval time.Duration) *TokenBucket
NewTokenBucket creates a new token bucket rate limiter
func (*TokenBucket) Allow ¶
func (tb *TokenBucket) Allow(key string) (bool, *RateLimitInfo)
Allow checks if request is allowed
func (*TokenBucket) Reset ¶
func (tb *TokenBucket) Reset(key string)
Reset resets the bucket for a key
func (*TokenBucket) Stop ¶
func (tb *TokenBucket) Stop()
Stop gracefully stops the token bucket and cleans up resources
type ValidationError ¶
type ValidationError struct {
Field string `json:"field" xml:"field"`
Message string `json:"message" xml:"message"`
Value string `json:"value,omitempty" xml:"value,omitempty"`
}
ValidationError represents field validation errors
type VersionConfig ¶
type VersionConfig struct {
DefaultVersion string
SupportedVersions []string
VersionHeader string
VersionInPath bool
VersionInQuery bool
Deprecated map[string]string // Maps deprecated versions to sunset dates
}
VersionConfig holds versioning configuration
func DefaultVersionConfig ¶
func DefaultVersionConfig() *VersionConfig
DefaultVersionConfig returns a default version configuration
type VersionNegotiator ¶
type VersionNegotiator struct {
// contains filtered or unexported fields
}
VersionNegotiator handles version negotiation
func NewVersionNegotiator ¶
func NewVersionNegotiator(defaultVersion string) *VersionNegotiator
NewVersionNegotiator creates a new version negotiator
func (*VersionNegotiator) AddVersion ¶
func (vn *VersionNegotiator) AddVersion(version string, handler http.HandlerFunc)
AddVersion adds a version handler
func (*VersionNegotiator) ServeHTTP ¶
func (vn *VersionNegotiator) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP negotiates and serves the appropriate version
type VersionRouter ¶
type VersionRouter struct {
// contains filtered or unexported fields
}
VersionRouter manages API versioning
func NewVersionRouter ¶
func NewVersionRouter(config *VersionConfig) *VersionRouter
NewVersionRouter creates a new version router
func (*VersionRouter) DeprecateVersion ¶
func (vr *VersionRouter) DeprecateVersion(version, sunsetDate string)
DeprecateVersion marks a version as deprecated
func (*VersionRouter) GetVersion ¶
func (vr *VersionRouter) GetVersion(r *http.Request) string
GetVersion extracts API version from request
func (*VersionRouter) Mount ¶
func (vr *VersionRouter) Mount(pattern string, handler http.Handler)
Mount mounts versioned API routes
func (*VersionRouter) RegisterVersion ¶
func (vr *VersionRouter) RegisterVersion(version string) *chi.Mux
RegisterVersion registers a new API version
func (*VersionRouter) ServeHTTP ¶
func (vr *VersionRouter) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler