Documentation
¶
Overview ¶
Package rue is a high-performance, extensible Go web framework. It provides REST API, WebSocket, gRPC, GraphQL, SSE, WebRTC, and QUIC/HTTP3 support.
Index ¶
- Constants
- Variables
- func DefaultErrorHandler(c *Context, err error)
- func GRPCAuth(authFunc func(ctx context.Context) (context.Context, error)) grpc.UnaryServerInterceptor
- func GRPCLogger() grpc.UnaryServerInterceptor
- func GRPCRateLimiter(allowFunc func(key string) bool, keyFunc func(ctx context.Context) string) grpc.UnaryServerInterceptor
- func GRPCRecovery() grpc.UnaryServerInterceptor
- func GRPCStreamAuth(authFunc func(ctx context.Context) (context.Context, error)) grpc.StreamServerInterceptor
- func GRPCStreamLogger() grpc.StreamServerInterceptor
- func GRPCStreamRecovery() grpc.StreamServerInterceptor
- func GenerateToken(claims *JWTClaims, secret []byte) (string, error)
- func GenerateTokenWithMethod(claims *JWTClaims, secret []byte, method string) (string, error)
- func IsDevMode() bool
- func IsPrdMode() bool
- func LogDebug(msg string)
- func LogDebugf(format string, args ...any)
- func LogError(msg string)
- func LogErrorWithErr(msg string, err error)
- func LogErrorf(format string, args ...any)
- func LogFatal(msg string)
- func LogFatalf(format string, args ...any)
- func LogInfo(msg string)
- func LogInfof(format string, args ...any)
- func LogStat(msg string)
- func LogStatf(format string, args ...any)
- func LogWarn(msg string)
- func LogWarnf(format string, args ...any)
- func SetDefaultLogger(l *Logger)
- type APIKeyConfig
- type Agent
- func (a *Agent) AddHeader(key, value string) *Agent
- func (a *Agent) ClearCookies() *Agent
- func (a *Agent) ClearHeaders() *Agent
- func (a *Agent) Delete(path string) *AgentResponse
- func (a *Agent) Do(method, path string, body io.Reader) *AgentResponse
- func (a *Agent) Get(path string) *AgentResponse
- func (a *Agent) Head(path string) *AgentResponse
- func (a *Agent) NewRequest(method, path string) *Request
- func (a *Agent) Options(path string) *AgentResponse
- func (a *Agent) Patch(path string, body io.Reader) *AgentResponse
- func (a *Agent) PatchJSON(path string, obj any) *AgentResponse
- func (a *Agent) Post(path string, body io.Reader) *AgentResponse
- func (a *Agent) PostForm(path string, data url.Values) *AgentResponse
- func (a *Agent) PostJSON(path string, obj any) *AgentResponse
- func (a *Agent) Put(path string, body io.Reader) *AgentResponse
- func (a *Agent) PutJSON(path string, obj any) *AgentResponse
- func (a *Agent) SetCookie(cookie *http.Cookie) *Agent
- func (a *Agent) SetHeader(key, value string) *Agent
- type AgentResponse
- type Argument
- type Binder
- type BindingError
- type BrotliConfig
- type CORSConfig
- type CompressConfig
- type Context
- func (c *Context) Abort()
- func (c *Context) AbortWithError(code int, err error)
- func (c *Context) AbortWithJSON(code int, obj any)
- func (c *Context) AbortWithStatus(code int)
- func (c *Context) Bind(obj any) error
- func (c *Context) BindJSON(obj any) error
- func (c *Context) BindQuery(obj any) error
- func (c *Context) ClientIP() string
- func (c *Context) ContentType() string
- func (c *Context) Context() context.Context
- func (c *Context) Cookie(name string) (string, error)
- func (c *Context) Data(code int, contentType string, data []byte) error
- func (c *Context) Deadline() (deadline time.Time, ok bool)
- func (c *Context) DefaultQuery(key, defaultValue string) string
- func (c *Context) Done() <-chan struct{}
- func (c *Context) Err() error
- func (c *Context) Error(err error)
- func (c *Context) File(filepath string)
- func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
- func (c *Context) FullPath() string
- func (c *Context) Get(key string) (any, bool)
- func (c *Context) GetBool(key string) bool
- func (c *Context) GetInt(key string) int
- func (c *Context) GetString(key string) string
- func (c *Context) HTML(code int, name string, data any) error
- func (c *Context) Header(key string) string
- func (c *Context) IndentedJSON(code int, obj any) error
- func (c *Context) IsAborted() bool
- func (c *Context) JSON(code int, obj any) error
- func (c *Context) MultipartForm() (*multipart.Form, error)
- func (c *Context) MustGet(key string) any
- func (c *Context) Next()
- func (c *Context) Param(key string) string
- func (c *Context) PostForm(key string) string
- func (c *Context) PostFormArray(key string) []string
- func (c *Context) PostFormDefault(key, defaultValue string) string
- func (c *Context) Query(key string) string
- func (c *Context) QueryArray(key string) []string
- func (c *Context) QueryDefault(key, defaultValue string) string
- func (c *Context) QueryMap(key string) map[string]string
- func (c *Context) Redirect(code int, location string)
- func (c *Context) Set(key string, value any)
- func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
- func (c *Context) SetHeader(key, value string)
- func (c *Context) ShouldBind(obj any) error
- func (c *Context) ShouldBindJSON(obj any) error
- func (c *Context) Status(code int) *Context
- func (c *Context) Stream(code int, contentType string, reader io.Reader) error
- func (c *Context) String(code int, format string, values ...any) error
- func (c *Context) Text(code int, text string) error
- func (c *Context) Validate(obj any) error
- func (c *Context) Value(key any) any
- func (c *Context) XML(code int, obj any) error
- type DefaultBinder
- type DefaultValidator
- type Delims
- type Engine
- func (e *Engine) Delims(left, right string) *Engine
- func (e *Engine) DisableStats() *Engine
- func (e *Engine) GetHTMLTemplate() *template.Template
- func (e *Engine) LoadHTMLFS(fsys fs.FS, patterns ...string) error
- func (e *Engine) LoadHTMLFSRecursive(fsys fs.FS, root string, filePattern string) error
- func (e *Engine) LoadHTMLFiles(files ...string) error
- func (e *Engine) LoadHTMLGlob(pattern string) error
- func (e *Engine) OnRequest(fn func(*Context))
- func (e *Engine) OnResponse(fn func(*Context))
- func (e *Engine) OnShutdown(fn func())
- func (e *Engine) OnStart(fn func())
- func (e *Engine) Run(addr string) error
- func (e *Engine) RunDualStack(httpAddr, http3Addr, certFile, keyFile string) error
- func (e *Engine) RunQUIC(addr, certFile, keyFile string) error
- func (e *Engine) RunQUICWithConfig(addr, certFile, keyFile string, config QUICConfig) error
- func (e *Engine) RunTLS(addr, certFile, keyFile string) error
- func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (e *Engine) SetFuncMap(funcMap template.FuncMap)
- func (e *Engine) SetHTMLTemplate(tmpl *template.Template)
- func (e *Engine) SetStatsConfig(config StatsConfig) *Engine
- func (e *Engine) SetStatsInterval(interval time.Duration) *Engine
- func (e *Engine) SetTrustedProxies(proxies []string) error
- func (e *Engine) Shutdown(ctx context.Context) error
- type Error
- type ErrorHandler
- type ErrorHandlerFunc
- type Executor
- type Field
- type GRPCConfig
- type GRPCContext
- func (gc *GRPCContext) Abort()
- func (gc *GRPCContext) Context() context.Context
- func (gc *GRPCContext) Error(err error)
- func (gc *GRPCContext) Errors() []error
- func (gc *GRPCContext) Get(key string) (any, bool)
- func (gc *GRPCContext) GetMetadata(key string) string
- func (gc *GRPCContext) IsAborted() bool
- func (gc *GRPCContext) Metadata() metadata.MD
- func (gc *GRPCContext) MustGet(key string) any
- func (gc *GRPCContext) Set(key string, value any)
- type GRPCServer
- func (gs *GRPCServer) Build(opts ...grpc.ServerOption) *grpc.Server
- func (gs *GRPCServer) GracefulStop()
- func (gs *GRPCServer) Run(addr string) error
- func (gs *GRPCServer) Serve(lis net.Listener) error
- func (gs *GRPCServer) Server() *grpc.Server
- func (gs *GRPCServer) Stop()
- func (gs *GRPCServer) Use(middleware ...HandlerFunc) *GRPCServer
- func (gs *GRPCServer) UseStream(interceptor grpc.StreamServerInterceptor) *GRPCServer
- func (gs *GRPCServer) UseUnary(interceptor grpc.UnaryServerInterceptor) *GRPCServer
- type GraphQLConfig
- type GraphQLError
- type GraphQLRequest
- type GraphQLResponse
- type GraphQLType
- type GzipConfig
- type H
- type HTMLRenderer
- type HTTP3Handler
- type HTTP3Server
- type HandlerFunc
- func APIKey(validator func(string) bool) HandlerFunc
- func APIKeyWithConfig(config APIKeyConfig) HandlerFunc
- func AltSvc(port int) HandlerFunc
- func AltSvcWithMaxAge(port int, maxAge int) HandlerFunc
- func Brotli() HandlerFunc
- func BrotliWithConfig(config BrotliConfig) HandlerFunc
- func CORS() HandlerFunc
- func CORSWithConfig(config CORSConfig) HandlerFunc
- func Compress() HandlerFunc
- func CompressWithConfig(config CompressConfig) HandlerFunc
- func GraphQL(schema *Schema) HandlerFunc
- func GraphQLWithConfig(config GraphQLConfig) HandlerFunc
- func Gzip() HandlerFunc
- func GzipWithConfig(config GzipConfig) HandlerFunc
- func JWT(secret []byte) HandlerFunc
- func JWTWithConfig(config JWTConfig) HandlerFunc
- func RateLimiter() HandlerFunc
- func RateLimiterWithConfig(config RateLimiterConfig) HandlerFunc
- func Recovery() HandlerFunc
- func RecoveryWithConfig(config RecoveryConfig) HandlerFunc
- func RequestLogger() HandlerFunc
- func RequestLoggerWithConfig(config RequestLoggerConfig) HandlerFunc
- func SystemStats() HandlerFunc
- func SystemStatsWithConfig(config StatsConfig) HandlerFunc
- func WebSocket(handler *WebSocketHandler) HandlerFunc
- func WebSocketWithConfig(handler *WebSocketHandler, config WebSocketConfig) HandlerFunc
- type HandlersChain
- type ICECandidate
- type JWTClaims
- type JWTConfig
- type Location
- type LogEntry
- type LogFormat
- type LogLevel
- type Logger
- func (l *Logger) Debug(msg string)
- func (l *Logger) Debugf(format string, args ...any)
- func (l *Logger) Error(msg string)
- func (l *Logger) ErrorWithErr(msg string, err error)
- func (l *Logger) Errorf(format string, args ...any)
- func (l *Logger) Fatal(msg string)
- func (l *Logger) Fatalf(format string, args ...any)
- func (l *Logger) Info(msg string)
- func (l *Logger) Infof(format string, args ...any)
- func (l *Logger) SetFormat(format LogFormat)
- func (l *Logger) SetLevel(level LogLevel)
- func (l *Logger) Stat(msg string)
- func (l *Logger) Statf(format string, args ...any)
- func (l *Logger) Warn(msg string)
- func (l *Logger) Warnf(format string, args ...any)
- func (l *Logger) WithFields(fields map[string]any) *Logger
- type LoggerOption
- func WithCaller(enable bool) LoggerOption
- func WithCallerSkip(skip int) LoggerOption
- func WithColor(enable bool) LoggerOption
- func WithFormat(format LogFormat) LoggerOption
- func WithLevel(level LogLevel) LoggerOption
- func WithOutput(w io.Writer) LoggerOption
- func WithTimeFormat(format string) LoggerOption
- type Mode
- type ModeBuilder
- type ModeConfig
- type ObjectType
- type Operation
- type Param
- type Params
- type QUICConfig
- type RateLimiterConfig
- type RecoveryConfig
- type Renderer
- type Request
- type RequestLoggerConfig
- type ResolveContext
- type ResolveFunc
- type ResolveInfo
- type ResponseWriter
- type Router
- type RouterGroup
- func (g *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (g *RouterGroup) CONNECT(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (g *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (g *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (g *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (g *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (g *RouterGroup) Handle(method, relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (g *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (g *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (g *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (g *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (g *RouterGroup) Static(relativePath, root string) *RouterGroup
- func (g *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) *RouterGroup
- func (g *RouterGroup) StaticFile(relativePath, filepath string) *RouterGroup
- func (g *RouterGroup) TRACE(relativePath string, handlers ...HandlerFunc) *RouterGroup
- func (g *RouterGroup) Use(middleware ...HandlerFunc) *RouterGroup
- type SDPMessage
- type SSEClient
- func (s *SSEClient) Close()
- func (s *SSEClient) Done() <-chan struct{}
- func (s *SSEClient) IsClosed() bool
- func (s *SSEClient) Send(event *SSEEvent) error
- func (s *SSEClient) SendComment(comment string) error
- func (s *SSEClient) SendData(data string) error
- func (s *SSEClient) SendEvent(event, data string) error
- func (s *SSEClient) SendEventWithID(id, event, data string) error
- type SSEConfig
- type SSEEvent
- type SSEHub
- func (h *SSEHub) Broadcast(event *SSEEvent)
- func (h *SSEHub) BroadcastData(data string)
- func (h *SSEHub) BroadcastDataToRoom(room, data string)
- func (h *SSEHub) BroadcastToRoom(room string, event *SSEEvent)
- func (h *SSEHub) Count() int
- func (h *SSEHub) Join(client *SSEClient, room string)
- func (h *SSEHub) Leave(client *SSEClient, room string)
- func (h *SSEHub) Register(client *SSEClient)
- func (h *SSEHub) RoomCount(room string) int
- func (h *SSEHub) Unregister(client *SSEClient)
- type ScalarType
- type Schema
- type Selection
- type SignalMessage
- type SignalType
- type SignalingPeer
- type SignalingServer
- func (s *SignalingServer) AddPeer(id string, conn *WebSocketConn) *SignalingPeer
- func (s *SignalingServer) Broadcast(roomID string, msg *SignalMessage, excludePeerID string)
- func (s *SignalingServer) GetPeer(id string) *SignalingPeer
- func (s *SignalingServer) GetRoomPeers(roomID string) []*SignalingPeer
- func (s *SignalingServer) HandleMessage(peerID string, data []byte) error
- func (s *SignalingServer) JoinRoom(peerID, roomID string)
- func (s *SignalingServer) LeaveRoom(peerID string)
- func (s *SignalingServer) PeerCount() int
- func (s *SignalingServer) RemovePeer(id string)
- func (s *SignalingServer) RoomCount() int
- func (s *SignalingServer) SendTo(peerID string, msg *SignalMessage) error
- func (s *SignalingServer) WebSocketHandler() *WebSocketHandler
- type StatsConfig
- type ValidationError
- type ValidationErrors
- type ValidationFunc
- type Validator
- type WebSocketConfig
- type WebSocketConn
- func (c *WebSocketConn) Close() error
- func (c *WebSocketConn) CloseWithCode(code int, reason string) error
- func (c *WebSocketConn) Get(key string) (any, bool)
- func (c *WebSocketConn) IsClosed() bool
- func (c *WebSocketConn) LocalAddr() net.Addr
- func (c *WebSocketConn) Ping(data []byte) error
- func (c *WebSocketConn) Pong(data []byte) error
- func (c *WebSocketConn) ReadMessage() (messageType int, data []byte, err error)
- func (c *WebSocketConn) RemoteAddr() net.Addr
- func (c *WebSocketConn) Send(message string) error
- func (c *WebSocketConn) SendBinary(data []byte) error
- func (c *WebSocketConn) Set(key string, value any)
- func (c *WebSocketConn) WriteMessage(messageType int, data []byte) error
- type WebSocketHandler
- type WebSocketHub
- func (h *WebSocketHub) Broadcast(message string)
- func (h *WebSocketHub) BroadcastBinary(data []byte)
- func (h *WebSocketHub) BroadcastBinaryToRoom(room string, data []byte)
- func (h *WebSocketHub) BroadcastToRoom(room, message string)
- func (h *WebSocketHub) Count() int
- func (h *WebSocketHub) Join(conn *WebSocketConn, room string)
- func (h *WebSocketHub) Leave(conn *WebSocketConn, room string)
- func (h *WebSocketHub) Register(conn *WebSocketConn)
- func (h *WebSocketHub) RoomCount(room string) int
- func (h *WebSocketHub) Unregister(conn *WebSocketConn)
Constants ¶
const ( // Frame types TextMessage = 1 BinaryMessage = 2 CloseMessage = 8 PingMessage = 9 PongMessage = 10 )
WebSocket constants
const (
// Environment variable name for mode
EnvRueMode = "RUE_MODE"
)
Variables ¶
var ( ErrBadRequest = NewError(http.StatusBadRequest, "Bad Request") ErrForbidden = NewError(http.StatusForbidden, "Forbidden") ErrNotFound = NewError(http.StatusNotFound, "Not Found") ErrMethodNotAllowed = NewError(http.StatusMethodNotAllowed, "Method Not Allowed") ErrConflict = NewError(http.StatusConflict, "Conflict") ErrUnprocessableEntity = NewError(http.StatusUnprocessableEntity, "Unprocessable Entity") ErrTooManyRequests = NewError(http.StatusTooManyRequests, "Too Many Requests") ErrInternalServerError = NewError(http.StatusInternalServerError, "Internal Server Error") ErrGatewayTimeout = NewError(http.StatusGatewayTimeout, "Gateway Timeout") ErrRequestTimeout = NewError(http.StatusRequestTimeout, "Request Timeout") ErrPayloadTooLarge = NewError(http.StatusRequestEntityTooLarge, "Payload Too Large") ErrUnsupportedMedia = NewError(http.StatusUnsupportedMediaType, "Unsupported Media Type") )
Predefined errors
var ( GraphQLString = &ScalarType{name: "String", description: "A UTF-8 string"} GraphQLInt = &ScalarType{name: "Int", description: "A 32-bit integer"} GraphQLFloat = &ScalarType{name: "Float", description: "A floating point number"} GraphQLBoolean = &ScalarType{name: "Boolean", description: "A boolean value"} GraphQLID = &ScalarType{name: "ID", description: "A unique identifier"} )
Built-in scalar types
var ( ErrWebSocketUpgrade = errors.New("websocket: upgrade failed") ErrWebSocketClosed = errors.New("websocket: connection closed") ErrWebSocketInvalidData = errors.New("websocket: invalid data") )
WebSocket errors
var DefaultFuncMap = template.FuncMap{ "safe": func(s string) template.HTML { return template.HTML(s) }, "safeJS": func(s string) template.JS { return template.JS(s) }, "safeCSS": func(s string) template.CSS { return template.CSS(s) }, "safeURL": func(s string) template.URL { return template.URL(s) }, "upper": strings.ToUpper, "lower": strings.ToLower, "title": strings.Title, "trim": strings.TrimSpace, "join": strings.Join, "split": strings.Split, "contains": strings.Contains, "hasPrefix": strings.HasPrefix, "hasSuffix": strings.HasSuffix, "replace": func(s, old, new string) string { return strings.ReplaceAll(s, old, new) }, }
Common template functions
var ErrRequestBodyTooLarge = errors.New("request body too large")
ErrRequestBodyTooLarge is returned when request body exceeds MaxRequestBodySize
var ErrWebSocketOriginNotAllowed = errors.New("websocket: origin not allowed")
ErrWebSocketOriginNotAllowed is returned when Origin validation fails
Functions ¶
func DefaultErrorHandler ¶
DefaultErrorHandler is the default error handler
func GRPCAuth ¶
func GRPCAuth(authFunc func(ctx context.Context) (context.Context, error)) grpc.UnaryServerInterceptor
GRPCAuth returns an authentication interceptor
func GRPCLogger ¶
func GRPCLogger() grpc.UnaryServerInterceptor
GRPCLogger returns a logging interceptor for gRPC
func GRPCRateLimiter ¶
func GRPCRateLimiter(allowFunc func(key string) bool, keyFunc func(ctx context.Context) string) grpc.UnaryServerInterceptor
GRPCRateLimiter returns a rate limiting interceptor using a custom limiter interface
func GRPCRecovery ¶
func GRPCRecovery() grpc.UnaryServerInterceptor
GRPCRecovery returns a recovery interceptor for gRPC
func GRPCStreamAuth ¶
func GRPCStreamAuth(authFunc func(ctx context.Context) (context.Context, error)) grpc.StreamServerInterceptor
GRPCStreamAuth returns an authentication interceptor for streams
func GRPCStreamLogger ¶
func GRPCStreamLogger() grpc.StreamServerInterceptor
GRPCStreamLogger returns a logging interceptor for gRPC streams
func GRPCStreamRecovery ¶
func GRPCStreamRecovery() grpc.StreamServerInterceptor
GRPCStreamRecovery returns a recovery interceptor for gRPC streams
func GenerateToken ¶
GenerateToken generates a JWT token with the given claims
func GenerateTokenWithMethod ¶
GenerateTokenWithMethod generates a JWT token with the specified signing method
func IsDevMode ¶ added in v0.0.2
func IsDevMode() bool
IsDevMode returns true if running in development mode
func IsPrdMode ¶ added in v0.0.2
func IsPrdMode() bool
IsPrdMode returns true if running in production mode
func LogErrorWithErr ¶ added in v0.0.2
func SetDefaultLogger ¶ added in v0.0.2
func SetDefaultLogger(l *Logger)
SetDefaultLogger sets the default logger
Types ¶
type APIKeyConfig ¶
type APIKeyConfig struct {
KeyLookup string // "header:X-API-Key", "query:api_key"
Validator func(string) bool // Function to validate the API key
ContextKey string // Key to store API key in context
ErrorFunc func(*Context) // Custom error handler
SkipFunc func(*Context) bool // Skip API key validation for certain requests
}
APIKeyConfig defines the config for APIKey middleware
func DefaultAPIKeyConfig ¶
func DefaultAPIKeyConfig() APIKeyConfig
DefaultAPIKeyConfig returns the default API key config
type Agent ¶
type Agent struct {
// contains filtered or unexported fields
}
Agent is a test client for making requests to the engine
func (*Agent) Delete ¶
func (a *Agent) Delete(path string) *AgentResponse
Delete performs a DELETE request
func (*Agent) Do ¶
func (a *Agent) Do(method, path string, body io.Reader) *AgentResponse
Do performs a request with the given method, path, and body
func (*Agent) NewRequest ¶
NewRequest creates a new request builder
func (*Agent) Options ¶
func (a *Agent) Options(path string) *AgentResponse
Options performs an OPTIONS request
func (*Agent) Patch ¶
func (a *Agent) Patch(path string, body io.Reader) *AgentResponse
Patch performs a PATCH request with the given body
func (*Agent) PatchJSON ¶
func (a *Agent) PatchJSON(path string, obj any) *AgentResponse
PatchJSON performs a PATCH request with JSON body
func (*Agent) Post ¶
func (a *Agent) Post(path string, body io.Reader) *AgentResponse
Post performs a POST request with the given body
func (*Agent) PostForm ¶
func (a *Agent) PostForm(path string, data url.Values) *AgentResponse
PostForm performs a POST request with form data
func (*Agent) PostJSON ¶
func (a *Agent) PostJSON(path string, obj any) *AgentResponse
PostJSON performs a POST request with JSON body
func (*Agent) Put ¶
func (a *Agent) Put(path string, body io.Reader) *AgentResponse
Put performs a PUT request with the given body
func (*Agent) PutJSON ¶
func (a *Agent) PutJSON(path string, obj any) *AgentResponse
PutJSON performs a PUT request with JSON body
type AgentResponse ¶
AgentResponse wraps the response from an agent request
func (*AgentResponse) JSON ¶
func (r *AgentResponse) JSON(obj any) error
JSON unmarshals the body into the given object
func (*AgentResponse) String ¶
func (r *AgentResponse) String() string
String returns the body as a string
type Argument ¶
type Argument struct {
Name string
Description string
Type GraphQLType
DefaultValue any
}
Argument represents a GraphQL argument
type BindingError ¶
BindingError represents a binding error
func (*BindingError) Error ¶
func (e *BindingError) Error() string
type BrotliConfig ¶
type BrotliConfig struct {
Level int // Compression level (0-11, default: 6)
MinLength int // Minimum content length to compress (default: 1024)
ContentTypes []string // Content types to compress
SkipFunc func(*Context) bool // Skip compression for certain requests
}
BrotliConfig defines the config for Brotli middleware
func DefaultBrotliConfig ¶
func DefaultBrotliConfig() BrotliConfig
DefaultBrotliConfig returns the default Brotli config
type CORSConfig ¶
type CORSConfig struct {
AllowOrigins []string
AllowMethods []string
AllowHeaders []string
ExposeHeaders []string
AllowCredentials bool
MaxAge int
}
CORSConfig defines the config for CORS middleware
func DefaultCORSConfig ¶
func DefaultCORSConfig() CORSConfig
DefaultCORSConfig returns the default CORS config
type CompressConfig ¶
type CompressConfig struct {
GzipLevel int // Gzip compression level
BrotliLevel int // Brotli compression level
MinLength int // Minimum content length to compress
ContentTypes []string // Content types to compress
SkipFunc func(*Context) bool // Skip compression for certain requests
}
CompressConfig defines the config for auto compression middleware
func DefaultCompressConfig ¶
func DefaultCompressConfig() CompressConfig
DefaultCompressConfig returns the default compression config
type Context ¶
type Context struct {
Request *http.Request
Writer ResponseWriter
Params Params
// Errors
Errors []error
// contains filtered or unexported fields
}
Context is the request context that carries request-scoped data
func (*Context) AbortWithError ¶
AbortWithError aborts the request with an error
func (*Context) AbortWithJSON ¶
AbortWithJSON aborts with a JSON response
func (*Context) AbortWithStatus ¶
AbortWithStatus aborts with the specified status code
func (*Context) ClientIP ¶
ClientIP returns the client IP address Only trusts X-Forwarded-For and X-Real-IP headers if the request comes from a trusted proxy
func (*Context) ContentType ¶
ContentType returns the Content-Type header
func (*Context) Deadline ¶
Deadline returns the time when work done on behalf of this context should be canceled
func (*Context) DefaultQuery ¶ added in v0.0.5
DefaultQuery is an alias for QueryDefault for compatibility
func (*Context) Done ¶
func (c *Context) Done() <-chan struct{}
Done returns a channel that's closed when work done on behalf of this context should be canceled
func (*Context) FormFile ¶
func (c *Context) FormFile(name string) (*multipart.FileHeader, error)
FormFile returns the first file for the provided form key
func (*Context) IndentedJSON ¶
IndentedJSON renders an indented JSON response
func (*Context) MultipartForm ¶
MultipartForm returns the multipart form
func (*Context) PostFormArray ¶
PostFormArray returns a slice of strings for a given form key
func (*Context) PostFormDefault ¶
PostFormDefault returns the form data value or a default
func (*Context) QueryArray ¶
QueryArray returns a slice of strings for a given query key
func (*Context) QueryDefault ¶
QueryDefault returns the query string parameter value or a default
func (*Context) SetCookie ¶
func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)
SetCookie sets a cookie
func (*Context) ShouldBind ¶
ShouldBind binds the request body to obj, returns error without aborting
func (*Context) ShouldBindJSON ¶
ShouldBindJSON binds the JSON request body to obj
func (*Context) Validate ¶ added in v0.0.5
Validate validates the given struct using the engine's validator
type DefaultBinder ¶
type DefaultBinder struct{}
DefaultBinder is the default implementation of Binder
type DefaultValidator ¶
type DefaultValidator struct {
// contains filtered or unexported fields
}
DefaultValidator is the default validator implementation
func NewValidator ¶
func NewValidator() *DefaultValidator
NewValidator creates a new DefaultValidator
func (*DefaultValidator) RegisterValidation ¶
func (v *DefaultValidator) RegisterValidation(tag string, fn ValidationFunc)
RegisterValidation registers a custom validation function
func (*DefaultValidator) Validate ¶
func (v *DefaultValidator) Validate(obj any) error
Validate validates a struct
type Engine ¶
type Engine struct {
RouterGroup
// Configuration
MaxMultipartMemory int64
MaxRequestBodySize int64 // Maximum request body size (default: 4MB)
Mode Mode
// Extension points
Binder Binder
Validator Validator
Renderer Renderer
ErrorHandler ErrorHandler
// Logger
Logger *Logger
// Router options
RedirectTrailingSlash bool
// contains filtered or unexported fields
}
Engine is the core framework engine
func (*Engine) DisableStats ¶ added in v0.0.3
DisableStats disables system statistics reporting
func (*Engine) GetHTMLTemplate ¶ added in v0.0.2
GetHTMLTemplate returns the current HTML template
func (*Engine) LoadHTMLFS ¶ added in v0.0.2
LoadHTMLFS loads HTML templates from an embed.FS or other fs.FS
func (*Engine) LoadHTMLFSRecursive ¶ added in v0.0.2
LoadHTMLFSRecursive loads HTML templates recursively from an fs.FS
func (*Engine) LoadHTMLFiles ¶ added in v0.0.2
LoadHTMLFiles loads specific HTML template files
func (*Engine) LoadHTMLGlob ¶ added in v0.0.2
LoadHTMLGlob loads HTML templates from a glob pattern Supports multi-level directories with "**" pattern Examples:
- "templates/*.html" - single level
- "templates/**/*.html" - multi-level
- "templates/**/*" - all files in all subdirectories
func (*Engine) OnResponse ¶
OnResponse registers a hook to be called after each response
func (*Engine) OnShutdown ¶
func (e *Engine) OnShutdown(fn func())
OnShutdown registers a hook to be called when the server shuts down
func (*Engine) OnStart ¶
func (e *Engine) OnStart(fn func())
OnStart registers a hook to be called when the server starts
func (*Engine) RunDualStack ¶
RunDualStack starts both HTTP/1.1+2 and HTTP/3 servers
func (*Engine) RunQUICWithConfig ¶
func (e *Engine) RunQUICWithConfig(addr, certFile, keyFile string, config QUICConfig) error
RunQUICWithConfig starts the HTTP/3 server with custom config
func (*Engine) ServeHTTP ¶
func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface
func (*Engine) SetFuncMap ¶ added in v0.0.2
SetFuncMap sets the template function map for the engine
func (*Engine) SetHTMLTemplate ¶ added in v0.0.2
SetHTMLTemplate sets a custom template
func (*Engine) SetStatsConfig ¶ added in v0.0.3
func (e *Engine) SetStatsConfig(config StatsConfig) *Engine
SetStatsConfig sets the stats configuration
func (*Engine) SetStatsInterval ¶ added in v0.0.3
SetStatsInterval sets the interval for stats reporting
func (*Engine) SetTrustedProxies ¶ added in v0.0.5
SetTrustedProxies sets the list of trusted proxy IP addresses or CIDR ranges. Only requests from trusted proxies will have X-Forwarded-For and X-Real-IP headers trusted. Example: e.SetTrustedProxies([]string{"127.0.0.1", "10.0.0.0/8", "192.168.0.0/16"})
type Error ¶
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
Details any `json:"details,omitempty"`
Err error `json:"-"`
}
Error is the framework error type
func (*Error) WithDetails ¶
WithDetails adds details to the error and returns a new Error
func (*Error) WithMessage ¶
WithMessage creates a new Error with a custom message
type ErrorHandler ¶
ErrorHandler is the function type for handling errors
type ErrorHandlerFunc ¶
ErrorHandlerFunc is the error handler function type
func JSONErrorHandler ¶
func JSONErrorHandler(debug bool) ErrorHandlerFunc
JSONErrorHandler returns errors in JSON format with optional debug info
type Executor ¶
type Executor struct {
// contains filtered or unexported fields
}
Executor executes GraphQL operations
func NewExecutorWithLimits ¶ added in v0.0.5
NewExecutorWithLimits creates a new executor with custom limits
func (*Executor) Execute ¶
func (e *Executor) Execute(ctx *Context, req *GraphQLRequest) *GraphQLResponse
Execute executes a GraphQL request
type Field ¶
type Field struct {
Name string
Description string
Type GraphQLType
Args []*Argument
Resolve ResolveFunc
}
Field represents a GraphQL field
type GRPCConfig ¶
type GRPCConfig struct {
// MaxRecvMsgSize is the maximum message size in bytes the server can receive
MaxRecvMsgSize int
// MaxSendMsgSize is the maximum message size in bytes the server can send
MaxSendMsgSize int
// MaxConcurrentStreams limits the number of concurrent streams per connection
MaxConcurrentStreams uint32
// ConnectionTimeout is the timeout for connection establishment
ConnectionTimeout time.Duration
// EnableReflection enables gRPC server reflection
EnableReflection bool
}
GRPCConfig holds configuration for gRPC server
func DefaultGRPCConfig ¶
func DefaultGRPCConfig() *GRPCConfig
DefaultGRPCConfig returns default gRPC configuration
type GRPCContext ¶
type GRPCContext struct {
// contains filtered or unexported fields
}
GRPCContext wraps gRPC context with Rue-like interface
func GetGRPCContext ¶
func GetGRPCContext(ctx context.Context) *GRPCContext
GetGRPCContext retrieves GRPCContext from context
func NewGRPCContext ¶
func NewGRPCContext(ctx context.Context) *GRPCContext
NewGRPCContext creates a new GRPCContext from gRPC context
func (*GRPCContext) Context ¶
func (gc *GRPCContext) Context() context.Context
Context returns the underlying context
func (*GRPCContext) Error ¶
func (gc *GRPCContext) Error(err error)
Error adds an error to the context
func (*GRPCContext) Get ¶
func (gc *GRPCContext) Get(key string) (any, bool)
Get retrieves a value by key
func (*GRPCContext) GetMetadata ¶
func (gc *GRPCContext) GetMetadata(key string) string
GetMetadata retrieves a metadata value
func (*GRPCContext) IsAborted ¶
func (gc *GRPCContext) IsAborted() bool
IsAborted returns whether the context is aborted
func (*GRPCContext) Metadata ¶
func (gc *GRPCContext) Metadata() metadata.MD
Metadata returns the incoming metadata
func (*GRPCContext) MustGet ¶
func (gc *GRPCContext) MustGet(key string) any
MustGet retrieves a value or panics if not found
func (*GRPCContext) Set ¶
func (gc *GRPCContext) Set(key string, value any)
Set stores a key-value pair
type GRPCServer ¶
type GRPCServer struct {
// contains filtered or unexported fields
}
GRPCServer wraps a gRPC server with Rue integration
func NewGRPCServer ¶
func NewGRPCServer(engine *Engine) *GRPCServer
NewGRPCServer creates a new gRPC server integrated with Rue engine
func NewGRPCServerWithConfig ¶
func NewGRPCServerWithConfig(engine *Engine, config *GRPCConfig) *GRPCServer
NewGRPCServerWithConfig creates a new gRPC server with custom configuration
func (*GRPCServer) Build ¶
func (gs *GRPCServer) Build(opts ...grpc.ServerOption) *grpc.Server
Build creates the underlying gRPC server with all interceptors
func (*GRPCServer) GracefulStop ¶
func (gs *GRPCServer) GracefulStop()
GracefulStop gracefully stops the gRPC server
func (*GRPCServer) Run ¶
func (gs *GRPCServer) Run(addr string) error
Run starts the gRPC server on the given address
func (*GRPCServer) Serve ¶
func (gs *GRPCServer) Serve(lis net.Listener) error
Serve starts the gRPC server on the given listener
func (*GRPCServer) Server ¶
func (gs *GRPCServer) Server() *grpc.Server
Server returns the underlying gRPC server
func (*GRPCServer) Use ¶
func (gs *GRPCServer) Use(middleware ...HandlerFunc) *GRPCServer
Use adds Rue middleware as gRPC unary interceptor
func (*GRPCServer) UseStream ¶
func (gs *GRPCServer) UseStream(interceptor grpc.StreamServerInterceptor) *GRPCServer
UseStream adds a gRPC stream interceptor directly
func (*GRPCServer) UseUnary ¶
func (gs *GRPCServer) UseUnary(interceptor grpc.UnaryServerInterceptor) *GRPCServer
UseUnary adds a gRPC unary interceptor directly
type GraphQLConfig ¶
type GraphQLConfig struct {
Schema *Schema
Playground bool
MaxDepth int // Maximum query depth (default: 10, 0 = unlimited)
MaxComplexity int // Maximum query complexity (default: 100, 0 = unlimited)
}
GraphQLConfig defines GraphQL handler configuration
type GraphQLError ¶
type GraphQLError struct {
Message string `json:"message"`
Locations []Location `json:"locations,omitempty"`
Path []any `json:"path,omitempty"`
}
GraphQLError represents a GraphQL error
type GraphQLRequest ¶
type GraphQLRequest struct {
Query string `json:"query"`
OperationName string `json:"operationName,omitempty"`
Variables map[string]any `json:"variables,omitempty"`
}
GraphQLRequest represents a GraphQL request
type GraphQLResponse ¶
type GraphQLResponse struct {
Data any `json:"data,omitempty"`
Errors []GraphQLError `json:"errors,omitempty"`
}
GraphQLResponse represents a GraphQL response
func (*GraphQLResponse) MarshalJSON ¶
func (r *GraphQLResponse) MarshalJSON() ([]byte, error)
MarshalJSON marshals a GraphQL response to JSON
type GraphQLType ¶
GraphQLType represents a GraphQL type
type GzipConfig ¶
type GzipConfig struct {
Level int // Compression level (1-9, default: 6)
MinLength int // Minimum content length to compress (default: 1024)
ContentTypes []string // Content types to compress (default: text/*, application/json, application/xml)
SkipFunc func(*Context) bool // Skip compression for certain requests
}
GzipConfig defines the config for Gzip middleware
func DefaultGzipConfig ¶
func DefaultGzipConfig() GzipConfig
DefaultGzipConfig returns the default Gzip config
type HTMLRenderer ¶ added in v0.0.2
type HTMLRenderer struct {
// contains filtered or unexported fields
}
HTMLRenderer is a template renderer using html/template
func NewHTMLRenderer ¶ added in v0.0.2
func NewHTMLRenderer() *HTMLRenderer
NewHTMLRenderer creates a new HTMLRenderer
type HTTP3Handler ¶
type HTTP3Handler struct {
// contains filtered or unexported fields
}
HTTP3Handler wraps a handler to work with HTTP/3
func (*HTTP3Handler) ServeHTTP ¶
func (h *HTTP3Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler
type HTTP3Server ¶
type HTTP3Server struct {
// contains filtered or unexported fields
}
HTTP3Server wraps the HTTP/3 server
func NewHTTP3Server ¶
func NewHTTP3Server(engine *Engine, config QUICConfig) *HTTP3Server
NewHTTP3Server creates a new HTTP/3 server
func (*HTTP3Server) CloseGracefully ¶
func (s *HTTP3Server) CloseGracefully(timeout time.Duration) error
CloseGracefully closes the server gracefully
func (*HTTP3Server) ListenAndServe ¶
func (s *HTTP3Server) ListenAndServe(addr, certFile, keyFile string) error
ListenAndServe starts the HTTP/3 server
type HandlerFunc ¶
type HandlerFunc func(*Context)
HandlerFunc defines the handler function type
func APIKey ¶
func APIKey(validator func(string) bool) HandlerFunc
APIKey returns an APIKey middleware with the given validator
func APIKeyWithConfig ¶
func APIKeyWithConfig(config APIKeyConfig) HandlerFunc
APIKeyWithConfig returns an APIKey middleware with custom config
func AltSvc ¶
func AltSvc(port int) HandlerFunc
AltSvc returns a middleware that adds Alt-Svc header for HTTP/3
func AltSvcWithMaxAge ¶
func AltSvcWithMaxAge(port int, maxAge int) HandlerFunc
AltSvcWithMaxAge returns a middleware that adds Alt-Svc header with max-age
func BrotliWithConfig ¶
func BrotliWithConfig(config BrotliConfig) HandlerFunc
BrotliWithConfig returns a Brotli middleware with custom config
func CORSWithConfig ¶
func CORSWithConfig(config CORSConfig) HandlerFunc
CORSWithConfig returns a CORS middleware with custom config
func Compress ¶
func Compress() HandlerFunc
Compress returns an auto compression middleware that selects the best encoding
func CompressWithConfig ¶
func CompressWithConfig(config CompressConfig) HandlerFunc
CompressWithConfig returns an auto compression middleware with custom config
func GraphQLWithConfig ¶
func GraphQLWithConfig(config GraphQLConfig) HandlerFunc
GraphQLWithConfig returns a GraphQL handler with custom config
func GzipWithConfig ¶
func GzipWithConfig(config GzipConfig) HandlerFunc
GzipWithConfig returns a Gzip middleware with custom config
func JWTWithConfig ¶
func JWTWithConfig(config JWTConfig) HandlerFunc
JWTWithConfig returns a JWT middleware with custom config
func RateLimiter ¶
func RateLimiter() HandlerFunc
RateLimiter returns a RateLimiter middleware with default config
func RateLimiterWithConfig ¶
func RateLimiterWithConfig(config RateLimiterConfig) HandlerFunc
RateLimiterWithConfig returns a RateLimiter middleware with custom config
func Recovery ¶
func Recovery() HandlerFunc
Recovery returns a Recovery middleware with default config
func RecoveryWithConfig ¶
func RecoveryWithConfig(config RecoveryConfig) HandlerFunc
RecoveryWithConfig returns a Recovery middleware with custom config
func RequestLogger ¶ added in v0.0.2
func RequestLogger() HandlerFunc
RequestLogger returns a request Logger middleware with default config
func RequestLoggerWithConfig ¶ added in v0.0.2
func RequestLoggerWithConfig(config RequestLoggerConfig) HandlerFunc
RequestLoggerWithConfig returns a request Logger middleware with custom config
func SystemStats ¶ added in v0.0.3
func SystemStats() HandlerFunc
SystemStats returns a middleware that enables system statistics reporting This is automatically included in Default() but can be added manually with custom config
func SystemStatsWithConfig ¶ added in v0.0.3
func SystemStatsWithConfig(config StatsConfig) HandlerFunc
SystemStatsWithConfig returns a middleware with custom stats configuration
func WebSocket ¶
func WebSocket(handler *WebSocketHandler) HandlerFunc
WebSocket returns a WebSocket handler middleware
func WebSocketWithConfig ¶
func WebSocketWithConfig(handler *WebSocketHandler, config WebSocketConfig) HandlerFunc
WebSocketWithConfig returns a WebSocket handler with custom config
type HandlersChain ¶
type HandlersChain []HandlerFunc
HandlersChain is a slice of HandlerFunc
func (HandlersChain) Last ¶
func (c HandlersChain) Last() HandlerFunc
Last returns the final handler in the chain, or nil if empty
type ICECandidate ¶
type ICECandidate struct {
Candidate string `json:"candidate"`
SDPMid string `json:"sdpMid"`
SDPMLineIndex int `json:"sdpMLineIndex"`
}
ICECandidate represents an ICE candidate
type JWTClaims ¶
type JWTClaims struct {
Subject string `json:"sub,omitempty"`
Issuer string `json:"iss,omitempty"`
Audience string `json:"aud,omitempty"`
ExpiresAt int64 `json:"exp,omitempty"`
IssuedAt int64 `json:"iat,omitempty"`
NotBefore int64 `json:"nbf,omitempty"`
ID string `json:"jti,omitempty"`
Custom map[string]any `json:"-"`
}
JWTClaims represents JWT claims
type JWTConfig ¶
type JWTConfig struct {
Secret []byte
SigningMethod string // HS256, HS384, HS512
TokenLookup string // "header:Authorization", "query:token", "cookie:jwt"
AuthScheme string // "Bearer"
ContextKey string // Key to store claims in context
ErrorFunc func(*Context, error) // Custom error handler
SkipFunc func(*Context) bool // Skip JWT validation for certain requests
}
JWTConfig defines the config for JWT middleware
func DefaultJWTConfig ¶
func DefaultJWTConfig() JWTConfig
DefaultJWTConfig returns the default JWT config
type LogEntry ¶ added in v0.0.2
type LogEntry struct {
Timestamp string `json:"@timestamp"`
Level string `json:"level"`
Caller string `json:"caller,omitempty"`
Func string `json:"func,omitempty"`
Content string `json:"content,omitempty"`
// HTTP request fields
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
Status int `json:"status,omitempty"`
Latency string `json:"latency,omitempty"`
ClientIP string `json:"client_ip,omitempty"`
// Error fields
Error string `json:"error,omitempty"`
Stack string `json:"stack,omitempty"`
// Custom fields
Fields map[string]any `json:"fields,omitempty"`
}
LogEntry represents a structured log entry
type LogLevel ¶ added in v0.0.2
type LogLevel int
LogLevel represents the severity of a log message
const ( // DebugLevel is for debug messages DebugLevel LogLevel = iota // InfoLevel is for informational messages InfoLevel // WarnLevel is for warning messages WarnLevel // ErrorLevel is for error messages ErrorLevel // FatalLevel is for fatal messages FatalLevel // StatLevel is for statistics messages StatLevel )
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger is a structured logger
func GetDefaultLogger ¶ added in v0.0.2
func GetDefaultLogger() *Logger
GetDefaultLogger returns the default logger
func NewLogger ¶ added in v0.0.2
func NewLogger(opts ...LoggerOption) *Logger
NewLogger creates a new Logger with the given options
func (*Logger) ErrorWithErr ¶ added in v0.0.2
ErrorWithErr logs an error message with an error
type LoggerOption ¶ added in v0.0.2
type LoggerOption func(*Logger)
LoggerOption is a function that configures a Logger
func WithCaller ¶ added in v0.0.2
func WithCaller(enable bool) LoggerOption
WithCaller enables or disables caller information
func WithCallerSkip ¶ added in v0.0.2
func WithCallerSkip(skip int) LoggerOption
WithCallerSkip sets the number of stack frames to skip
func WithColor ¶ added in v0.0.2
func WithColor(enable bool) LoggerOption
WithColor enables or disables colored output
func WithFormat ¶ added in v0.0.2
func WithFormat(format LogFormat) LoggerOption
WithFormat sets the log format
func WithLevel ¶ added in v0.0.2
func WithLevel(level LogLevel) LoggerOption
WithLevel sets the log level
func WithOutput ¶ added in v0.0.2
func WithOutput(w io.Writer) LoggerOption
WithOutput sets the output writer
func WithTimeFormat ¶ added in v0.0.2
func WithTimeFormat(format string) LoggerOption
WithTimeFormat sets the time format
type ModeBuilder ¶ added in v0.0.3
type ModeBuilder struct{}
ModeBuilder provides fluent API for configuring mode settings
func SetMode ¶ added in v0.0.2
func SetMode(mode Mode) *ModeBuilder
SetMode sets the running mode and returns a builder for chaining
func (*ModeBuilder) EnableCaller ¶ added in v0.0.3
func (b *ModeBuilder) EnableCaller(enable bool) *ModeBuilder
EnableCaller sets whether to enable caller info (overrides mode default)
func (*ModeBuilder) EnableColor ¶ added in v0.0.3
func (b *ModeBuilder) EnableColor(enable bool) *ModeBuilder
EnableColor sets whether to enable colored output (overrides mode default)
func (*ModeBuilder) Format ¶ added in v0.0.3
func (b *ModeBuilder) Format(format LogFormat) *ModeBuilder
Format sets a custom log format (overrides mode default)
func (*ModeBuilder) LogLevel ¶ added in v0.0.3
func (b *ModeBuilder) LogLevel(level LogLevel) *ModeBuilder
LogLevel sets a custom log level (overrides mode default)
type ModeConfig ¶ added in v0.0.2
ModeConfig holds the configuration for a mode
func GetModeConfig ¶ added in v0.0.2
func GetModeConfig() ModeConfig
GetModeConfig returns the effective configuration (mode defaults + overrides)
type ObjectType ¶
type ObjectType struct {
// contains filtered or unexported fields
}
ObjectType represents a GraphQL object type
func NewObjectType ¶
func NewObjectType(name, description string) *ObjectType
NewObjectType creates a new object type
func (*ObjectType) AddField ¶
func (o *ObjectType) AddField(field *Field)
AddField adds a field to the object type
func (*ObjectType) Description ¶
func (o *ObjectType) Description() string
func (*ObjectType) Name ¶
func (o *ObjectType) Name() string
type Params ¶
type Params []Param
Params holds path parameters
type QUICConfig ¶
type QUICConfig struct {
// TLS configuration (required for QUIC)
TLSConfig *tls.Config
// QUIC specific settings
MaxIncomingStreams int64
MaxIncomingUniStreams int64
IdleTimeout time.Duration
// 0-RTT settings
Enable0RTT bool
// Alt-Svc header configuration
AltSvcPort int // Port to advertise in Alt-Svc header
}
QUICConfig defines QUIC/HTTP3 configuration
func DefaultQUICConfig ¶
func DefaultQUICConfig() QUICConfig
DefaultQUICConfig returns default QUIC configuration
type RateLimiterConfig ¶
type RateLimiterConfig struct {
Rate float64 // Tokens per second
Burst int // Maximum burst size
KeyFunc func(*Context) string // Function to extract key (default: client IP)
ErrorFunc func(*Context) // Custom error handler
SkipFunc func(*Context) bool // Skip rate limiting for certain requests
CleanupInterval time.Duration // Interval to clean up expired entries (default: 10 minutes)
EntryTTL time.Duration // Time-to-live for rate limiter entries (default: 1 hour)
}
RateLimiterConfig defines the config for RateLimiter middleware
func DefaultRateLimiterConfig ¶
func DefaultRateLimiterConfig() RateLimiterConfig
DefaultRateLimiterConfig returns the default rate limiter config
type RecoveryConfig ¶
RecoveryConfig defines the config for Recovery middleware
func DefaultRecoveryConfig ¶
func DefaultRecoveryConfig() RecoveryConfig
DefaultRecoveryConfig returns the default recovery config
type Request ¶
type Request struct {
// contains filtered or unexported fields
}
Request is a builder for creating requests
type RequestLoggerConfig ¶ added in v0.0.2
type RequestLoggerConfig struct {
Level LogLevel
Format LogFormat
Output io.Writer
SkipPaths []string
EnableCaller bool
TimeFormat string
EnableColor bool
}
RequestLoggerConfig defines the config for request Logger middleware
func DefaultRequestLoggerConfig ¶ added in v0.0.2
func DefaultRequestLoggerConfig() RequestLoggerConfig
DefaultRequestLoggerConfig returns the default request logger config
type ResolveContext ¶
type ResolveContext struct {
Context *Context
Source any
Args map[string]any
Info *ResolveInfo
}
ResolveContext contains context for field resolution
type ResolveFunc ¶
type ResolveFunc func(ctx *ResolveContext) (any, error)
ResolveFunc is the resolver function type
type ResolveInfo ¶
type ResolveInfo struct {
FieldName string
ReturnType GraphQLType
ParentType GraphQLType
}
ResolveInfo contains information about the current resolution
type ResponseWriter ¶
type ResponseWriter interface {
http.ResponseWriter
http.Hijacker
http.Flusher
// Status reports the status code set via WriteHeader
Status() int
// Size reports the total bytes written to the body
Size() int
// Written reports whether headers have been flushed to the network
Written() bool
// WriteString is a convenience method equivalent to Write([]byte(s))
WriteString(s string) (int, error)
// WriteHeaderNow flushes the status line and headers immediately
WriteHeaderNow()
}
ResponseWriter extends http.ResponseWriter with status tracking, size accounting, and protocol upgrade helpers (hijack, flush, push).
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router maps HTTP method + request path to a registered handler chain.
Patterns are '/'-separated. Each pattern segment takes one of four forms:
literal /users/all
capture /users/:id matches exactly one segment; an empty segment
matches only when another '/' follows
prefixed /file_:name literal prefix plus capture of the remainder
trailing /assets/*rest absorbs everything left of the path; must be
the final segment and directly follow a '/';
the captured value keeps its leading '/'
Registration is write-side: all addRoute calls must finish before the router starts serving. Lookups (getValue) are read-only and safe for unlimited concurrent use once registration is done.
Trailing-capture values are handed to handlers verbatim — a file-serving handler downstream owns its own ".." sanitization.
type RouterGroup ¶
type RouterGroup struct {
// contains filtered or unexported fields
}
RouterGroup is used to configure routes with common prefix and middleware
func (*RouterGroup) Any ¶
func (g *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) *RouterGroup
Any registers a handler for all HTTP methods
func (*RouterGroup) CONNECT ¶ added in v0.0.5
func (g *RouterGroup) CONNECT(relativePath string, handlers ...HandlerFunc) *RouterGroup
CONNECT registers a CONNECT handler
func (*RouterGroup) DELETE ¶
func (g *RouterGroup) DELETE(relativePath string, handlers ...HandlerFunc) *RouterGroup
DELETE registers a DELETE handler
func (*RouterGroup) GET ¶
func (g *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) *RouterGroup
GET registers a GET handler
func (*RouterGroup) Group ¶
func (g *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup
Group creates a new router group with the given path prefix
func (*RouterGroup) HEAD ¶
func (g *RouterGroup) HEAD(relativePath string, handlers ...HandlerFunc) *RouterGroup
HEAD registers a HEAD handler
func (*RouterGroup) Handle ¶
func (g *RouterGroup) Handle(method, relativePath string, handlers ...HandlerFunc) *RouterGroup
Handle registers a new request handler with the given path and method
func (*RouterGroup) OPTIONS ¶
func (g *RouterGroup) OPTIONS(relativePath string, handlers ...HandlerFunc) *RouterGroup
OPTIONS registers an OPTIONS handler
func (*RouterGroup) PATCH ¶
func (g *RouterGroup) PATCH(relativePath string, handlers ...HandlerFunc) *RouterGroup
PATCH registers a PATCH handler
func (*RouterGroup) POST ¶
func (g *RouterGroup) POST(relativePath string, handlers ...HandlerFunc) *RouterGroup
POST registers a POST handler
func (*RouterGroup) PUT ¶
func (g *RouterGroup) PUT(relativePath string, handlers ...HandlerFunc) *RouterGroup
PUT registers a PUT handler
func (*RouterGroup) Static ¶
func (g *RouterGroup) Static(relativePath, root string) *RouterGroup
Static serves files from the given file system root
func (*RouterGroup) StaticFS ¶
func (g *RouterGroup) StaticFS(relativePath string, fs http.FileSystem) *RouterGroup
StaticFS serves files from the given file system
func (*RouterGroup) StaticFile ¶
func (g *RouterGroup) StaticFile(relativePath, filepath string) *RouterGroup
StaticFile registers a single route to serve a single file
func (*RouterGroup) TRACE ¶ added in v0.0.5
func (g *RouterGroup) TRACE(relativePath string, handlers ...HandlerFunc) *RouterGroup
TRACE registers a TRACE handler
func (*RouterGroup) Use ¶
func (g *RouterGroup) Use(middleware ...HandlerFunc) *RouterGroup
Use adds middleware to the group
type SDPMessage ¶
SDPMessage represents an SDP offer/answer
type SSEClient ¶
type SSEClient struct {
// contains filtered or unexported fields
}
SSEClient represents an SSE client connection
func SSEWithConfig ¶
SSEWithConfig creates an SSE client with custom config
func (*SSEClient) Done ¶
func (s *SSEClient) Done() <-chan struct{}
Done returns a channel that's closed when the client disconnects
func (*SSEClient) SendComment ¶
SendComment sends a comment (for keep-alive)
func (*SSEClient) SendEventWithID ¶
SendEventWithID sends a named event with ID and data
type SSEConfig ¶
type SSEConfig struct {
RetryInterval int // Retry interval in milliseconds
KeepAlive bool // Send keep-alive comments
KeepAliveTime time.Duration
}
SSEConfig defines SSE configuration
func DefaultSSEConfig ¶
func DefaultSSEConfig() SSEConfig
DefaultSSEConfig returns default SSE configuration
type SSEHub ¶
type SSEHub struct {
// contains filtered or unexported fields
}
SSEHub manages SSE client connections
func (*SSEHub) BroadcastData ¶
BroadcastData sends data to all clients
func (*SSEHub) BroadcastDataToRoom ¶
BroadcastDataToRoom sends data to all clients in a room
func (*SSEHub) BroadcastToRoom ¶
BroadcastToRoom sends an event to all clients in a room
func (*SSEHub) Unregister ¶
Unregister removes a client from the hub
type ScalarType ¶
type ScalarType struct {
// contains filtered or unexported fields
}
ScalarType represents a GraphQL scalar type
func (*ScalarType) Description ¶
func (s *ScalarType) Description() string
func (*ScalarType) Name ¶
func (s *ScalarType) Name() string
type Schema ¶
type Schema struct {
Query *ObjectType
Mutation *ObjectType
}
Schema represents a GraphQL schema
func (*Schema) SetMutation ¶
func (s *Schema) SetMutation(mutation *ObjectType)
SetMutation sets the mutation type
type SignalMessage ¶
type SignalMessage struct {
Type SignalType `json:"type"`
From string `json:"from"`
To string `json:"to,omitempty"`
Room string `json:"room,omitempty"`
Payload any `json:"payload,omitempty"`
}
SignalMessage represents a WebRTC signaling message
type SignalType ¶
type SignalType string
SignalType represents the type of signaling message
const ( SignalOffer SignalType = "offer" SignalAnswer SignalType = "answer" SignalCandidate SignalType = "candidate" SignalJoin SignalType = "join" SignalLeave SignalType = "leave" )
type SignalingPeer ¶
type SignalingPeer struct {
ID string
Conn *WebSocketConn
Room string
}
SignalingPeer represents a peer in the signaling server
type SignalingServer ¶
type SignalingServer struct {
// Callbacks
OnPeerJoin func(peer *SignalingPeer)
OnPeerLeave func(peer *SignalingPeer)
OnMessage func(msg *SignalMessage)
// contains filtered or unexported fields
}
SignalingServer manages WebRTC signaling
func NewSignalingServer ¶
func NewSignalingServer() *SignalingServer
NewSignalingServer creates a new signaling server
func (*SignalingServer) AddPeer ¶
func (s *SignalingServer) AddPeer(id string, conn *WebSocketConn) *SignalingPeer
AddPeer adds a peer to the signaling server
func (*SignalingServer) Broadcast ¶
func (s *SignalingServer) Broadcast(roomID string, msg *SignalMessage, excludePeerID string)
Broadcast sends a message to all peers in a room
func (*SignalingServer) GetPeer ¶
func (s *SignalingServer) GetPeer(id string) *SignalingPeer
GetPeer returns a peer by ID
func (*SignalingServer) GetRoomPeers ¶
func (s *SignalingServer) GetRoomPeers(roomID string) []*SignalingPeer
GetRoomPeers returns all peers in a room
func (*SignalingServer) HandleMessage ¶
func (s *SignalingServer) HandleMessage(peerID string, data []byte) error
HandleMessage processes a signaling message
func (*SignalingServer) JoinRoom ¶
func (s *SignalingServer) JoinRoom(peerID, roomID string)
JoinRoom adds a peer to a room
func (*SignalingServer) LeaveRoom ¶
func (s *SignalingServer) LeaveRoom(peerID string)
LeaveRoom removes a peer from their current room
func (*SignalingServer) PeerCount ¶
func (s *SignalingServer) PeerCount() int
PeerCount returns the number of connected peers
func (*SignalingServer) RemovePeer ¶
func (s *SignalingServer) RemovePeer(id string)
RemovePeer removes a peer from the signaling server
func (*SignalingServer) RoomCount ¶
func (s *SignalingServer) RoomCount() int
RoomCount returns the number of active rooms
func (*SignalingServer) SendTo ¶
func (s *SignalingServer) SendTo(peerID string, msg *SignalMessage) error
SendTo sends a message to a specific peer
func (*SignalingServer) WebSocketHandler ¶
func (s *SignalingServer) WebSocketHandler() *WebSocketHandler
WebSocketHandler returns a WebSocket handler for signaling
type StatsConfig ¶ added in v0.0.3
type StatsConfig struct {
// Interval is the time between stats reports (default: 1 minute)
Interval time.Duration
// Enabled controls whether stats reporting is active (default: true)
Enabled bool
}
StatsConfig holds configuration for system statistics reporting
func DefaultStatsConfig ¶ added in v0.0.3
func DefaultStatsConfig() StatsConfig
DefaultStatsConfig returns the default stats configuration
type ValidationError ¶
type ValidationError struct {
Field string `json:"field"`
Tag string `json:"tag"`
Value any `json:"value,omitempty"`
Message string `json:"message"`
}
ValidationError represents a validation error
func (*ValidationError) Error ¶
func (e *ValidationError) Error() string
type ValidationErrors ¶
type ValidationErrors []ValidationError
ValidationErrors is a collection of validation errors
func (ValidationErrors) Error ¶
func (e ValidationErrors) Error() string
type ValidationFunc ¶
ValidationFunc is a custom validation function
type WebSocketConfig ¶
type WebSocketConfig struct {
ReadBufferSize int
WriteBufferSize int
PingPeriod time.Duration
PongWait time.Duration
MaxMessageSize int64
// CheckOrigin validates the Origin header to prevent Cross-Site WebSocket Hijacking (CSWSH)
// If nil, uses default check that compares Origin host with Host header
CheckOrigin func(c *Context) bool
}
WebSocketConfig defines WebSocket configuration
func DefaultWebSocketConfig ¶
func DefaultWebSocketConfig() WebSocketConfig
DefaultWebSocketConfig returns default WebSocket configuration
type WebSocketConn ¶
type WebSocketConn struct {
// contains filtered or unexported fields
}
WebSocketConn represents a WebSocket connection
func (*WebSocketConn) Close ¶
func (c *WebSocketConn) Close() error
Close closes the WebSocket connection
func (*WebSocketConn) CloseWithCode ¶
func (c *WebSocketConn) CloseWithCode(code int, reason string) error
CloseWithCode closes the connection with a specific code and reason
func (*WebSocketConn) IsClosed ¶
func (c *WebSocketConn) IsClosed() bool
IsClosed returns true if the connection is closed
func (*WebSocketConn) LocalAddr ¶
func (c *WebSocketConn) LocalAddr() net.Addr
LocalAddr returns the local address
func (*WebSocketConn) Ping ¶
func (c *WebSocketConn) Ping(data []byte) error
Ping sends a ping message
func (*WebSocketConn) Pong ¶
func (c *WebSocketConn) Pong(data []byte) error
Pong sends a pong message
func (*WebSocketConn) ReadMessage ¶
func (c *WebSocketConn) ReadMessage() (messageType int, data []byte, err error)
ReadMessage reads a message from the WebSocket connection Supports fragmented messages as per RFC 6455
func (*WebSocketConn) RemoteAddr ¶
func (c *WebSocketConn) RemoteAddr() net.Addr
RemoteAddr returns the remote address
func (*WebSocketConn) Send ¶
func (c *WebSocketConn) Send(message string) error
Send sends a text message
func (*WebSocketConn) SendBinary ¶
func (c *WebSocketConn) SendBinary(data []byte) error
SendBinary sends a binary message
func (*WebSocketConn) Set ¶
func (c *WebSocketConn) Set(key string, value any)
Helper to store data on WebSocketConn
func (*WebSocketConn) WriteMessage ¶
func (c *WebSocketConn) WriteMessage(messageType int, data []byte) error
WriteMessage writes a message to the WebSocket connection
type WebSocketHandler ¶
type WebSocketHandler struct {
OnConnect func(conn *WebSocketConn)
OnMessage func(conn *WebSocketConn, messageType int, data []byte)
OnClose func(conn *WebSocketConn, code int, reason string)
OnError func(conn *WebSocketConn, err error)
OnPing func(conn *WebSocketConn, data []byte)
OnPong func(conn *WebSocketConn, data []byte)
}
WebSocketHandler defines callbacks for WebSocket events
type WebSocketHub ¶
type WebSocketHub struct {
// contains filtered or unexported fields
}
WebSocketHub manages WebSocket connections
func NewWebSocketHub ¶
func NewWebSocketHub() *WebSocketHub
NewWebSocketHub creates a new WebSocket hub
func (*WebSocketHub) Broadcast ¶
func (h *WebSocketHub) Broadcast(message string)
Broadcast sends a message to all connections
func (*WebSocketHub) BroadcastBinary ¶
func (h *WebSocketHub) BroadcastBinary(data []byte)
BroadcastBinary sends binary data to all connections
func (*WebSocketHub) BroadcastBinaryToRoom ¶
func (h *WebSocketHub) BroadcastBinaryToRoom(room string, data []byte)
BroadcastBinaryToRoom sends binary data to all connections in a room
func (*WebSocketHub) BroadcastToRoom ¶
func (h *WebSocketHub) BroadcastToRoom(room, message string)
BroadcastToRoom sends a message to all connections in a room
func (*WebSocketHub) Count ¶
func (h *WebSocketHub) Count() int
Count returns the number of connections
func (*WebSocketHub) Join ¶
func (h *WebSocketHub) Join(conn *WebSocketConn, room string)
Join adds a connection to a room
func (*WebSocketHub) Leave ¶
func (h *WebSocketHub) Leave(conn *WebSocketConn, room string)
Leave removes a connection from a room
func (*WebSocketHub) Register ¶
func (h *WebSocketHub) Register(conn *WebSocketConn)
Register adds a connection to the hub
func (*WebSocketHub) RoomCount ¶
func (h *WebSocketHub) RoomCount(room string) int
RoomCount returns the number of connections in a room
func (*WebSocketHub) Unregister ¶
func (h *WebSocketHub) Unregister(conn *WebSocketConn)
Unregister removes a connection from the hub