Documentation
¶
Overview ¶
cache.go
config.go
Index ¶
- Constants
- Variables
- func GenerateRequestID() string
- func ValidateConfig(config *Config) error
- type CORSConfig
- type CacheConfig
- type CacheStore
- type CompressionConfig
- type Config
- type Context
- type DefaultLogger
- func (l *DefaultLogger) Debug(v ...interface{})
- func (l *DefaultLogger) Debugf(format string, v ...interface{})
- func (l *DefaultLogger) Error(v ...interface{})
- func (l *DefaultLogger) Errorf(format string, v ...interface{})
- func (l *DefaultLogger) Fatal(v ...interface{})
- func (l *DefaultLogger) Fatalf(format string, v ...interface{})
- func (l *DefaultLogger) Info(v ...interface{})
- func (l *DefaultLogger) Infof(format string, v ...interface{})
- func (l *DefaultLogger) IsAfterHandler() bool
- func (l *DefaultLogger) IsBeforeHandler() bool
- func (l *DefaultLogger) IsPrintRequestID() bool
- func (l *DefaultLogger) Print(v ...interface{})
- func (l *DefaultLogger) Printf(format string, v ...interface{})
- func (l *DefaultLogger) Warn(v ...interface{})
- func (l *DefaultLogger) Warnf(format string, v ...interface{})
- type DefaultLoggerConfig
- type FileHandler
- type FileInfo
- type HandlerFunc
- type HeaderAuthorization
- type LogLevel
- type Logger
- type MemoryCache
- type MemorySession
- type Middleware
- func MiddlewareBasicAuth(username, password string) Middleware
- func MiddlewareCORS(config *CORSConfig) Middleware
- func MiddlewareCache(config CacheConfig) Middleware
- func MiddlewareCompress(config CompressionConfig) Middleware
- func MiddlewareHeaderParser() Middleware
- func MiddlewareLogger(log Logger) Middleware
- func MiddlewareRateLimiter(config RateLimitConfig) Middleware
- func MiddlewareRecover(config ...RecoverConfig) Middleware
- func MiddlewareRequestID() Middleware
- func MiddlewareSecurity(config SecurityConfig) Middleware
- func MiddlewareTimeout(config TimeOutConfig) Middleware
- type MiddlewareFunc
- func BasicAuth(username, password string) MiddlewareFunc
- func CORS(config *CORSConfig) MiddlewareFunc
- func Compress(config CompressionConfig) MiddlewareFunc
- func HeaderParser() MiddlewareFunc
- func RateLimiter(config RateLimitConfig) MiddlewareFunc
- func Recover(config ...RecoverConfig) MiddlewareFunc
- func RequestID() MiddlewareFunc
- func Security(config SecurityConfig) MiddlewareFunc
- func SimpleCache(config CacheConfig) MiddlewareFunc
- func SimpleLog(log Logger) MiddlewareFunc
- func Timeout(config TimeOutConfig) MiddlewareFunc
- type NamedMiddleware
- type RateLimit
- type RateLimitConfig
- type RecoverConfig
- type RequestHeader
- type Router
- type Routes
- type SSEEvent
- type SSEHandler
- type SSEWriter
- type SecurityConfig
- type Server
- type Session
- type SimpleHttpError
- type TimeOutConfig
- type Websocket
Constants ¶
const ( // in seconds, later converted to time.Duration DEFAULT_HTTP_READ_TIMEOUT = 30 DEFAULT_HTTP_WRITE_TIMEOUT = 30 DEFAULT_HTTP_IDLE_TIMEOUT = 60 // This was used in fiber DEFAULT_HTTP_CONCURRENCY = 512 * 1024 // environment string SIMPLEHTTP_FRAMEWORK = "SIMPLEHTTP_FRAMEWORK" SIMPLEHTTP_PORT = "SIMPLEHTTP_PORT" SIMPLEHTTP_APP_NAME = "SIMPLEHTTP_APP_NAME" SIMPLEHTTP_HOST_NAME = "SIMPLEHTTP_HOST_NAME" SIMPLEHTTP_READ_TIMEOUT = "SIMPLEHTTP_READ_TIMEOUT" SIMPLEHTTP_WRITE_TIMEOUT = "SIMPLEHTTP_WRITE_TIMEOUT" SIMPLEHTTP_IDLE_TIMEOUT = "SIMPLEHTTP_IDLE_TIMEOUT" SIMPLEHTTP_DEBUG = "SIMPLEHTTP_DEBUG" SIMPLEHTTP_FRAMEWORK_STARTUP_MESSAGE = "SIMPLEHTTP_FRAMEWORK_STARTUP_MESSAGE" SIMPLEHTTP_INTERNAL_API = "SIMPLEHTTP_INTERNAL_API" SIMPLEHTTP_INTERNAL_STATUS = "SIMPLEHTTP_INTERNAL_STATUS" // internal API (if enabled) DEFAULT_INTERNAL_API = "/internal_d" // internal debug DEFAULT_INTERNAL_STATUS = "/http_status" )
const ( LogLevelDebug LogLevel = iota LogLevelInfo LogLevelWarn LogLevelError LogLevelFatal DEFAULT_LOG_TIME_FORMAT = "2006/01/02 15:04:05" DEFAULT_LOG_PREFIX = "[HTTP] " DEFAULT_AFTER_HANDLER = true DEFAULT_BEFORE_HANDLER = false )
Variables ¶
var ( ErrInvalidConfig = fmt.Errorf("invalid configuration") ErrServerStartup = fmt.Errorf("server startup failed") ErrNotFound = fmt.Errorf("resource not found") ErrForbidden = fmt.Errorf("forbidden") ErrRateLimitExceeded = fmt.Errorf("limit exceeded") )
Error types
var ( // Use this so we can change it on by reading from environment PathInternalAPI string = DEFAULT_INTERNAL_API PathInternalStatus string = DEFAULT_INTERNAL_STATUS )
var ( REQUEST_HEADER_PARSED_STRING string = "request_header" HEADER_AUTHORIZATION string = "authorization" HEADER_MEDA_API_KEY string = "MEDA_API_KEY" HEADER_API_KEY string = "API_KEY" HEADER_PRIVATE_TOKEN string = "PRIVATE_TOKEN" HEADER_CODE string = "code" HEADER_CONNECTING_IP string = "CF-Connecting-IP" HEADER_FORWARDED_FOR string = "X-Forwarded-For" HEADER_REAL_IP string = "X-Real-IP" HEADER_TRUE_CLIENT_IP string = "True-Client-IP" HEADER_USER_AGENT string = "User-Agent" HEADER_ACCEPT_TYPE string = "Accept" HEADER_TRACE_ID string = "X-Trace-ID" HEADER_REQUEST_ID string = "X-Request-ID" HEADER_ORIGIN string = "Origin" )
var DefaultConfig = &Config{ Framework: "fiber", AppName: "MedaHTTP", Hostname: "localhost", Port: "8080", ConfigTimeOut: &TimeOutConfig{ ReadTimeout: time.Second * DEFAULT_HTTP_READ_TIMEOUT, WriteTimeout: time.Second * DEFAULT_HTTP_WRITE_TIMEOUT, IdleTimeout: time.Second * DEFAULT_HTTP_IDLE_TIMEOUT, }, MaxHeaderBytes: 1 << 20, MaxRequestSize: 32 << 20, Debug: false, FrameworkStartupMessage: true, Logger: NewDefaultLogger(), Concurrency: DEFAULT_HTTP_CONCURRENCY, }
Default configuration values
Functions ¶
func GenerateRequestID ¶
func GenerateRequestID() string
Types ¶
type CORSConfig ¶
type CORSConfig struct {
AllowOrigins []string
AllowMethods []string
AllowHeaders []string
ExposeHeaders []string
AllowCredentials bool
MaxAge time.Duration
}
CORSConfig defines CORS settings
type CacheConfig ¶
type CacheConfig struct {
TTL time.Duration
KeyPrefix string
KeyFunc func(Context) string
Store CacheStore
IgnoreHeaders []string
}
Cache middleware configuration
type CacheStore ¶
type CacheStore interface {
Get(key string) (interface{}, bool)
Set(key string, value interface{}, ttl time.Duration) error
Delete(key string) error
Clear() error
}
Cache defines the interface for cache implementations
func NewMemoryCache ¶
func NewMemoryCache() CacheStore
type CompressionConfig ¶
type CompressionConfig struct {
Level int // Compression level (1-9)
MinSize int64 // Minimum size to compress
Types []string // Content types to compress
}
Compression middleware configuration
type Config ¶
type Config struct {
Framework string
AppName string
Hostname string
Port string
// ReadTimeout time.Duration
// WriteTimeout time.Duration
// IdleTimeout time.Duration
MaxHeaderBytes int
MaxRequestSize int64
UploadDir string
TempDir string
TrustedProxies []string
Debug bool
FrameworkStartupMessage bool // true means display the default framework startup message, false: quite mode
Concurrency int // for fiber settings
// TLS Configuration
TLSCert string
TLSKey string
AutoTLS bool
TLSDomain string
// Security
AllowedHosts []string
SSLRedirect bool
// CORS Configuration
ConfigCORS *CORSConfig
ConfigTimeOut *TimeOutConfig
// Custom error handlers
ErrorHandler func(error, Context) error
// Additional components
Logger Logger // Interface defined in logger.go
}
Configuration holds server settings
func LoadConfig ¶
func LoadConfig() *Config
LoadConfig loads configuration from environment variables
type Context ¶ added in v0.0.3
type Context interface {
// Request information
GetPath() string
GetMethod() string
GetHeader(key string) string
GetHeaders() *RequestHeader
SetRequestHeader(key, value string)
SetResponseHeader(key, value string)
SetHeader(key, value string)
GetQueryParam(key string) string
GetQueryParams() map[string][]string
GetBody() []byte
// Added these two methods
Request() *http.Request
Response() http.ResponseWriter
// Response methods
JSON(code int, data interface{}) error
String(code int, data string) error
Stream(code int, contentType string, reader io.Reader) error
// File handling
GetFile(fieldName string) (*multipart.FileHeader, error)
SaveFile(file *multipart.FileHeader, dst string) error
SendFile(filepath string, attachment bool) error
// SSE (Server-Sent Events)
SSE(handler SSEHandler) error
// Websocket
Upgrade() (Websocket, error)
// Context handling
Context() context.Context
SetContext(ctx context.Context)
Set(key string, value interface{})
Get(key string) interface{}
// Request binding
Bind(interface{}) error // Generic binding based on Content-Type
BindJSON(interface{}) error
BindForm(interface{}) error
}
Context represents our framework-agnostic request context
type DefaultLogger ¶
type DefaultLogger struct {
// contains filtered or unexported fields
}
DefaultLogger holds configuration for DefaultLogger
func (*DefaultLogger) Debug ¶
func (l *DefaultLogger) Debug(v ...interface{})
func (*DefaultLogger) Debugf ¶
func (l *DefaultLogger) Debugf(format string, v ...interface{})
func (*DefaultLogger) Error ¶
func (l *DefaultLogger) Error(v ...interface{})
func (*DefaultLogger) Errorf ¶
func (l *DefaultLogger) Errorf(format string, v ...interface{})
func (*DefaultLogger) Fatal ¶
func (l *DefaultLogger) Fatal(v ...interface{})
func (*DefaultLogger) Fatalf ¶
func (l *DefaultLogger) Fatalf(format string, v ...interface{})
func (*DefaultLogger) Info ¶
func (l *DefaultLogger) Info(v ...interface{})
func (*DefaultLogger) Infof ¶
func (l *DefaultLogger) Infof(format string, v ...interface{})
func (*DefaultLogger) IsAfterHandler ¶ added in v0.0.3
func (l *DefaultLogger) IsAfterHandler() bool
func (*DefaultLogger) IsBeforeHandler ¶ added in v0.0.3
func (l *DefaultLogger) IsBeforeHandler() bool
Getter
func (*DefaultLogger) IsPrintRequestID ¶ added in v0.0.3
func (l *DefaultLogger) IsPrintRequestID() bool
func (*DefaultLogger) Print ¶
func (l *DefaultLogger) Print(v ...interface{})
func (*DefaultLogger) Printf ¶
func (l *DefaultLogger) Printf(format string, v ...interface{})
func (*DefaultLogger) Warn ¶
func (l *DefaultLogger) Warn(v ...interface{})
func (*DefaultLogger) Warnf ¶
func (l *DefaultLogger) Warnf(format string, v ...interface{})
type DefaultLoggerConfig ¶
type FileHandler ¶
File handling utilities
func NewFileHandler ¶
func NewFileHandler(uploadDir string) *FileHandler
func (*FileHandler) HandleDownload ¶
func (h *FileHandler) HandleDownload(filepath string) HandlerFunc
func (*FileHandler) HandleUpload ¶
func (h *FileHandler) HandleUpload() HandlerFunc
This is independent of implementation Make sure the implementation context has .GetFile and .SaveFile
type FileInfo ¶
type FileInfo struct {
Filename string
Size int64
ContentType string
LastModified time.Time
Hash string // MD5/SHA hash of file
}
FileInfo represents uploaded file metadata
type HandlerFunc ¶ added in v0.0.3
HandlerFunc is our framework-agnostic handler function
type HeaderAuthorization ¶
type Logger ¶
type Logger interface {
Print(v ...interface{})
Printf(format string, v ...interface{})
Debug(v ...interface{})
Debugf(format string, v ...interface{})
Info(v ...interface{})
Infof(format string, v ...interface{})
Warn(v ...interface{})
Warnf(format string, v ...interface{})
Error(v ...interface{})
Errorf(format string, v ...interface{})
Fatal(v ...interface{})
Fatalf(format string, v ...interface{})
IsBeforeHandler() bool
IsAfterHandler() bool
IsPrintRequestID() bool
}
Logger interface for all logging operations
func NewDefaultLogger ¶
func NewDefaultLogger(config ...*DefaultLoggerConfig) Logger
NewDefaultLogger creates a new DefaultLogger with optional configuration
type MemoryCache ¶
MemoryCache provides a simple in-memory cache implementation
func (*MemoryCache) Clear ¶
func (c *MemoryCache) Clear() error
func (*MemoryCache) Delete ¶
func (c *MemoryCache) Delete(key string) error
func (*MemoryCache) Get ¶
func (c *MemoryCache) Get(key string) (interface{}, bool)
type MemorySession ¶
type MemorySession struct {
// contains filtered or unexported fields
}
MemorySession provides a simple in-memory session implementation
func (*MemorySession) Clear ¶
func (s *MemorySession) Clear() error
func (*MemorySession) Delete ¶
func (s *MemorySession) Delete(key string) error
func (*MemorySession) Get ¶
func (s *MemorySession) Get(key string) interface{}
func (*MemorySession) ID ¶
func (s *MemorySession) ID() string
func (*MemorySession) Save ¶
func (s *MemorySession) Save() error
func (*MemorySession) Set ¶
func (s *MemorySession) Set(key string, value interface{}) error
type Middleware ¶ added in v0.0.3
type Middleware interface {
Name() string
Handle(HandlerFunc) HandlerFunc
}
Predefined common Middleware as global variables
func MiddlewareBasicAuth ¶
func MiddlewareBasicAuth(username, password string) Middleware
func MiddlewareCORS ¶
func MiddlewareCORS(config *CORSConfig) Middleware
func MiddlewareCache ¶
func MiddlewareCache(config CacheConfig) Middleware
func MiddlewareCompress ¶
func MiddlewareCompress(config CompressionConfig) Middleware
func MiddlewareHeaderParser ¶
func MiddlewareHeaderParser() Middleware
func MiddlewareLogger ¶
func MiddlewareLogger(log Logger) Middleware
func MiddlewareRateLimiter ¶
func MiddlewareRateLimiter(config RateLimitConfig) Middleware
func MiddlewareRecover ¶
func MiddlewareRecover(config ...RecoverConfig) Middleware
func MiddlewareRequestID ¶
func MiddlewareRequestID() Middleware
func MiddlewareSecurity ¶
func MiddlewareSecurity(config SecurityConfig) Middleware
func MiddlewareTimeout ¶
func MiddlewareTimeout(config TimeOutConfig) Middleware
type MiddlewareFunc ¶ added in v0.0.3
type MiddlewareFunc func(HandlerFunc) HandlerFunc
MiddlewareFunc defines the contract for middleware
func BasicAuth ¶
func BasicAuth(username, password string) MiddlewareFunc
func CORS ¶
func CORS(config *CORSConfig) MiddlewareFunc
CORS middleware returns a Middleware that adds CORS headers to the response
func Compress ¶
func Compress(config CompressionConfig) MiddlewareFunc
Compress returns a compression middleware
func RateLimiter ¶
func RateLimiter(config RateLimitConfig) MiddlewareFunc
RateLimiter returns a rate limiting middleware
func Recover ¶
func Recover(config ...RecoverConfig) MiddlewareFunc
Recover returns a middleware that recovers from panics
func RequestID ¶
func RequestID() MiddlewareFunc
RequestID middleware adds a unique ID to each request
func Security ¶
func Security(config SecurityConfig) MiddlewareFunc
Security returns security middleware
func SimpleCache ¶
func SimpleCache(config CacheConfig) MiddlewareFunc
SimpleCache returns a caching middleware
func SimpleLog ¶
func SimpleLog(log Logger) MiddlewareFunc
Print logs for every request (2 lines) [prefix] INFO [date] time [rid] --Started [method] path [prefix] INFO [date] time [rid] Completed [method] path [duration] [prefix] INFO [date] time [rid] Failed [method] path [error] [duration]
func Timeout ¶
func Timeout(config TimeOutConfig) MiddlewareFunc
Timeout middleware adds a timeout to the request context
type NamedMiddleware ¶
type NamedMiddleware struct {
// contains filtered or unexported fields
}
NamedMiddleware wraps a middleware with a name for debugging
func WithName ¶
func WithName(name string, m MiddlewareFunc) NamedMiddleware
WithName adds a name to a middleware
func (NamedMiddleware) Handle ¶
func (n NamedMiddleware) Handle(next HandlerFunc) HandlerFunc
Implement the SimpleHttpMiddleware interface
func (NamedMiddleware) Name ¶
func (m NamedMiddleware) Name() string
GetMiddlewareName returns the name of the middleware if it's a NamedMiddleware, or "unnamed" if it's a regular middleware
func GetMiddlewareName(m MiddlewareFunc) string {
if named, ok := m.(*NamedMiddleware); ok {
return named.name
}
return "unnamed"
}
type RateLimit ¶
type RateLimit struct {
// contains filtered or unexported fields
}
Rate limit, remember burst is usually the one that taking effects (as maximum) Tested OK, it works fine. NOTE: make sure the cache middleware is not interfeering, because that can effect the rateLimit. When it is returned from cache, it doesn't hit the rate limit at all.
type RateLimitConfig ¶
type RateLimitConfig struct {
RequestsPerSecond int
BurstSize int
ClientTimeout time.Duration
KeyFunc func(Context) string // Function to generate rate limit key
}
RateLimiter middleware configuration
type RecoverConfig ¶
type RecoverConfig struct {
// StackTrace determines whether to include stack traces in error responses
StackTrace bool
// LogStackTrace determines whether to log stack traces
LogStackTrace bool
// ErrorHandler is a custom handler for recovered panics
ErrorHandler func(c Context, err interface{}, stack []byte) error
// Logger for recording panic information
Logger Logger
}
RecoverConfig holds configuration for the Recover middleware
type RequestHeader ¶
type RequestHeader struct {
Authorization HeaderAuthorization `db:"header_authorization" json:"header_authorization,omitempty"`
// below are specific to some Meda lib, in this case auth-lib
MedaAPIKey string `db:"meda_api_key" json:"MEDA_API_KEY,omitempty"`
APIKey string `db:"api_key" json:"API_KEY,omitempty"`
PrivateToken string `db:"private_token" json:"PRIVATE_TOKEN,omitempty"`
Code string `db:"code" json:"code,omitempty"`
// standard header
UserAgent string `db:"user_agent" json:"User-Agent,omitempty"`
AcceptType string `db:"accept_type" json:"Accept,omitempty"`
TraceID string `db:"trace_id" json:"X-Trace-ID,omitempty"`
RequestID string `db:"request_id" json:"X-Request-ID,omitempty"`
Origin string `db:"origin" json:"Origin,omitempty"`
ForwardedFor string `db:"forwarded_for" json:"X-Forwarded-For,omitempty"`
RealIP string `db:"real_ip" json:"X-Real-IP,omitempty"`
ConnectingIP string `db:"connecting_ip" json:"CF-Connecting-IP,omitempty"`
TrueIP string `db:"true_ip" json:"true-client-ip,omitempty"`
RemoteIP string `db:"remote_ip" json:"remote-address,omitempty"`
Browser string `db:"browser" json:"browser,omitempty"`
BrowserVersion string `db:"browser_version" json:"browser_version,omitempty"`
PlatformOS string `db:"platform_os" json:"platform_os,omitempty"`
PlatformOSVersion string `db:"platform_os_version" json:"platform_os_version,omitempty"`
Platform string `db:"platform" json:"platform,omitempty"` // mobile, desktop, unknown
Device string `db:"device" json:"device,omitempty"` // usually if mobile, this one has value
}
Please change this if RequestHeader struct is changed
func (*RequestHeader) FromHttpRequest ¶
func (mh *RequestHeader) FromHttpRequest(stdRequest *http.Request)
func (*RequestHeader) IP ¶
func (mh *RequestHeader) IP() string
type Router ¶ added in v0.0.3
type Router interface {
GET(path string, handler HandlerFunc)
POST(path string, handler HandlerFunc)
PUT(path string, handler HandlerFunc)
DELETE(path string, handler HandlerFunc)
PATCH(path string, handler HandlerFunc)
OPTIONS(path string, handler HandlerFunc)
HEAD(path string, handler HandlerFunc)
// Static file serving
Static(prefix, root string)
StaticFile(path, filepath string)
// Websocket
WebSocket(path string, handler func(Websocket) error)
Group(prefix string) Router
Use(middleware ...Middleware)
}
Router interface defines common routing operations
func CreateInternalAPI ¶
type SSEEvent ¶ added in v0.0.8
type SSEEvent struct {
ID string // Optional event ID
Event string // Event type (defaults to "message")
Data string // Event data
Retry int // Optional retry interval in milliseconds
}
SSEEvent represents a Server-Sent Event
type SSEHandler ¶ added in v0.0.8
SSEHandler is a function that receives an SSEWriter for streaming events
type SSEWriter ¶ added in v0.0.8
type SSEWriter interface {
// Send sends a simple data message
Send(data string) error
// SendEvent sends a full SSE event
SendEvent(event SSEEvent) error
// Flush flushes the response writer
Flush()
}
SSEWriter provides methods for writing SSE events
func NewSSEWriter ¶ added in v0.0.8
func NewSSEWriter(w http.ResponseWriter) SSEWriter
NewSSEWriter creates a new SSE writer from an http.ResponseWriter
type SecurityConfig ¶
type SecurityConfig struct {
AllowedHosts []string
SSLRedirect bool
SSLHost string
STSSeconds int64
STSIncludeSubdomains bool
FrameDeny bool
ContentTypeNosniff bool
BrowserXssFilter bool
ContentSecurityPolicy string
}
Security middleware configuration
type Session ¶
type Session interface {
Get(key string) interface{}
Set(key string, value interface{}) error
Delete(key string) error
Clear() error
ID() string
Save() error
}
Session defines the interface for session management
func NewMemorySession ¶
type SimpleHttpError ¶ added in v0.0.3
type SimpleHttpError struct {
Code int `json:"code"`
Message string `json:"message"`
Details interface{} `json:"details,omitempty"`
}
SimpleHttpError represents a standardized error response
func NewError ¶
func NewError(code int, message string, details ...interface{}) *SimpleHttpError
NewError creates a new SimpleHttpError
func (*SimpleHttpError) Error ¶ added in v0.0.3
func (e *SimpleHttpError) Error() string