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 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) 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 HeaderAuthorization
- type LogLevel
- type Logger
- type MedaContext
- type MedaError
- type MedaHandlerFunc
- type MedaMiddleware
- func MiddlewareBasicAuth(username, password string) MedaMiddleware
- func MiddlewareCORS(config *CORSConfig) MedaMiddleware
- func MiddlewareCache(config CacheConfig) MedaMiddleware
- func MiddlewareCompress(config CompressionConfig) MedaMiddleware
- func MiddlewareHeaderParser() MedaMiddleware
- func MiddlewareLogger(log Logger) MedaMiddleware
- func MiddlewareRateLimiter(config RateLimitConfig) MedaMiddleware
- func MiddlewareRecover(config ...RecoverConfig) MedaMiddleware
- func MiddlewareRequestID() MedaMiddleware
- func MiddlewareSecurity(config SecurityConfig) MedaMiddleware
- func MiddlewareTimeout(config TimeOutConfig) MedaMiddleware
- type MedaMiddlewareFunc
- func BasicAuth(username, password string) MedaMiddlewareFunc
- func CORS(config *CORSConfig) MedaMiddlewareFunc
- func Compress(config CompressionConfig) MedaMiddlewareFunc
- func HeaderParser() MedaMiddlewareFunc
- func RateLimiter(config RateLimitConfig) MedaMiddlewareFunc
- func Recover(config ...RecoverConfig) MedaMiddlewareFunc
- func RequestID() MedaMiddlewareFunc
- func Security(config SecurityConfig) MedaMiddlewareFunc
- func SimpleCache(config CacheConfig) MedaMiddlewareFunc
- func SimpleLog(log Logger) MedaMiddlewareFunc
- func Timeout(config TimeOutConfig) MedaMiddlewareFunc
- type MedaRouter
- type MedaServer
- type MedaWebsocket
- type MemoryCache
- type MemorySession
- type NamedMiddleware
- type RateLimit
- type RateLimitConfig
- type RecoverConfig
- type RequestHeader
- type Routes
- type SecurityConfig
- type Session
- type TimeOutConfig
Constants ¶
const ( // in seconds, later converted to time.Duration MEDA_DEFAULT_HTTP_READ_TIMEOUT = 30 MEDA_DEFAULT_HTTP_WRITE_TIMEOUT = 30 MEDA_DEFAULT_HTTP_IDLE_TIMEOUT = 60 // This was used in fiber MEDA_DEFAULT_HTTP_CONCURRENCY = 512 * 1024 // environment string MEDA_FRAMEWORK = "MEDA_FRAMEWORK" MEDA_PORT = "MEDA_PORT" MEDA_APP_NAME = "MEDA_APP_NAME" MEDA_HOST_NAME = "MEDA_HOST_NAME" MEDA_READ_TIMEOUT = "MEDA_READ_TIMEOUT" MEDA_WRITE_TIMEOUT = "MEDA_WRITE_TIMEOUT" MEDA_IDLE_TIMEOUT = "MEDA_IDLE_TIMEOUT" MEDA_DEBUG = "MEDA_DEBUG" FRAMEWORK_STARTUP_MESSAGE = "FRAMEWORK_STARTUP_MESSAGE" INTERNAL_API = "DEFAULT_INTERNAL_API" INTERNAL_STATUS = "DEFAULT_INTERNAL_STATUS" // internal API (if enabled) DEFAULT_INTERNAL_API = "/internal_d" // internal debug DEFAULT_INTERNAL_STATUS = "/http_status" )
const ( REQUEST_HEADER_PARSED_STRING = "request_header" HEADER_AUTHORIZATION = "authorization" HEADER_MEDA_API_KEY = "MEDA_API_KEY" HEADER_PRIVATE_TOKEN = "PRIVATE_TOKEN" HEADER_CODE = "code" HEADER_CONNECTING_IP = "CF-Connecting-IP" HEADER_FORWARDED_FOR = "X-Forwarded-For" HEADER_REAL_IP = "X-Real-IP" HEADER_TRUE_CLIENT_IP = "True-Client-IP" HEADER_USER_AGENT = "User-Agent" HEADER_ACCEPT_TYPE = "Accept" HEADER_TRACE_ID = "X-Trace-ID" HEADER_REQUEST_ID = "X-Request-ID" HEADER_ORIGIN = "Origin" )
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 DefaultConfig = &Config{ Framework: "fiber", AppName: "MedaHTTP", Hostname: "localhost", Port: "8080", ConfigTimeOut: &TimeOutConfig{ ReadTimeout: time.Second * MEDA_DEFAULT_HTTP_READ_TIMEOUT, WriteTimeout: time.Second * MEDA_DEFAULT_HTTP_WRITE_TIMEOUT, IdleTimeout: time.Second * MEDA_DEFAULT_HTTP_IDLE_TIMEOUT, }, MaxHeaderBytes: 1 << 20, MaxRequestSize: 32 << 20, Debug: false, FrameworkStartupMessage: true, Logger: NewDefaultLogger(), Concurrency: MEDA_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(MedaContext) 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, MedaContext) 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 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) 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) MedaHandlerFunc
func (*FileHandler) HandleUpload ¶
func (h *FileHandler) HandleUpload() MedaHandlerFunc
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 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{})
}
Logger interface for all logging operations
func NewDefaultLogger ¶
func NewDefaultLogger(config ...*DefaultLoggerConfig) Logger
NewDefaultLogger creates a new DefaultLogger with optional configuration
type MedaContext ¶
type MedaContext 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
// Websocket
Upgrade() (MedaWebsocket, 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
}
MedaContext represents our framework-agnostic request context
type MedaError ¶
type MedaError struct {
Code int `json:"code"`
Message string `json:"message"`
Details interface{} `json:"details,omitempty"`
}
MedaError represents a standardized error response
type MedaHandlerFunc ¶
type MedaHandlerFunc func(MedaContext) error
MedaHandlerFunc is our framework-agnostic handler function
type MedaMiddleware ¶
type MedaMiddleware interface {
Name() string
Handle(MedaHandlerFunc) MedaHandlerFunc
}
Predefined common MedaMiddleware as global variables
func MiddlewareBasicAuth ¶
func MiddlewareBasicAuth(username, password string) MedaMiddleware
func MiddlewareCORS ¶
func MiddlewareCORS(config *CORSConfig) MedaMiddleware
func MiddlewareCache ¶
func MiddlewareCache(config CacheConfig) MedaMiddleware
func MiddlewareCompress ¶
func MiddlewareCompress(config CompressionConfig) MedaMiddleware
func MiddlewareHeaderParser ¶
func MiddlewareHeaderParser() MedaMiddleware
func MiddlewareLogger ¶
func MiddlewareLogger(log Logger) MedaMiddleware
func MiddlewareRateLimiter ¶
func MiddlewareRateLimiter(config RateLimitConfig) MedaMiddleware
func MiddlewareRecover ¶
func MiddlewareRecover(config ...RecoverConfig) MedaMiddleware
func MiddlewareRequestID ¶
func MiddlewareRequestID() MedaMiddleware
func MiddlewareSecurity ¶
func MiddlewareSecurity(config SecurityConfig) MedaMiddleware
func MiddlewareTimeout ¶
func MiddlewareTimeout(config TimeOutConfig) MedaMiddleware
type MedaMiddlewareFunc ¶
type MedaMiddlewareFunc func(MedaHandlerFunc) MedaHandlerFunc
MedaMiddlewareFunc defines the contract for middleware
func BasicAuth ¶
func BasicAuth(username, password string) MedaMiddlewareFunc
func CORS ¶
func CORS(config *CORSConfig) MedaMiddlewareFunc
CORS middleware returns a Middleware that adds CORS headers to the response
func Compress ¶
func Compress(config CompressionConfig) MedaMiddlewareFunc
Compress returns a compression middleware
func RateLimiter ¶
func RateLimiter(config RateLimitConfig) MedaMiddlewareFunc
RateLimiter returns a rate limiting middleware
func Recover ¶
func Recover(config ...RecoverConfig) MedaMiddlewareFunc
Recover returns a middleware that recovers from panics
func RequestID ¶
func RequestID() MedaMiddlewareFunc
RequestID middleware adds a unique ID to each request
func Security ¶
func Security(config SecurityConfig) MedaMiddlewareFunc
Security returns security middleware
func SimpleCache ¶
func SimpleCache(config CacheConfig) MedaMiddlewareFunc
SimpleCache returns a caching middleware
func SimpleLog ¶
func SimpleLog(log Logger) MedaMiddlewareFunc
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) MedaMiddlewareFunc
Timeout middleware adds a timeout to the request context
type MedaRouter ¶
type MedaRouter interface {
GET(path string, handler MedaHandlerFunc)
POST(path string, handler MedaHandlerFunc)
PUT(path string, handler MedaHandlerFunc)
DELETE(path string, handler MedaHandlerFunc)
PATCH(path string, handler MedaHandlerFunc)
OPTIONS(path string, handler MedaHandlerFunc)
HEAD(path string, handler MedaHandlerFunc)
// Static file serving
Static(prefix, root string)
StaticFile(path, filepath string)
// Websocket
WebSocket(path string, handler func(MedaWebsocket) error)
Group(prefix string) MedaRouter
Use(middleware ...MedaMiddleware)
}
MedaRouter interface defines common routing operations
func CreateInternalAPI ¶
func CreateInternalAPI(s MedaServer) MedaRouter
type MedaServer ¶
type MedaServer interface {
MedaRouter
Start(address string) error
Shutdown(ctx context.Context) error
}
MedaServer interface defines the contract for our web server
type MedaWebsocket ¶
type MedaWebsocket interface {
WriteJSON(v interface{}) error
ReadJSON(v interface{}) error
WriteMessage(messageType int, data []byte) error
ReadMessage() (messageType int, p []byte, err error)
Close() error
}
MedaWebsocket interface for websocket connections
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 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 MedaMiddlewareFunc) NamedMiddleware
WithName adds a name to a middleware
func (NamedMiddleware) Handle ¶
func (n NamedMiddleware) Handle(next MedaHandlerFunc) MedaHandlerFunc
Implement the MedaMiddleware 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 MedaMiddlewareFunc) 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(MedaContext) 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 MedaContext, 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
APIKey string `db:"api_key" json:"MEDA_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 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