rue

package module
v0.0.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 23, 2026 License: MIT Imports: 45 Imported by: 0

README

Rue

A high-performance, feature-rich web framework for Go with minimal dependencies.

Features

  • High-Performance Router: Segment-trie routing with ~6.5ns static route matching
  • Middleware Support: Logger, Recovery, CORS, Rate Limiter, JWT, API Key
  • Compression: Gzip and Brotli with automatic content negotiation
  • Data Binding: JSON, XML, Form, Query, Header binding with validation
  • WebSocket: Full RFC 6455 implementation with Hub for broadcasting
  • SSE: Server-Sent Events support
  • GraphQL: Built-in GraphQL handler with Playground
  • WebRTC: Signaling server for peer-to-peer connections
  • QUIC/HTTP3: HTTP/3 support via quic-go
  • Testing: Built-in Agent for integration testing

Installation

go get github.com/ch-hash-lab/rue

Quick Start

package main

import (
    "net/http"
    "github.com/ch-hash-lab/rue"
)

func main() {
    // Create engine with default middleware (Logger + Recovery)
    r := rue.Default()

    // Simple route
    r.GET("/", func(c *rue.Context) {
        c.JSON(http.StatusOK, rue.H{"message": "Hello, Rue!"})
    })

    // Path parameters
    r.GET("/users/:id", func(c *rue.Context) {
        id := c.Param("id")
        c.JSON(http.StatusOK, rue.H{"user_id": id})
    })

    // Query parameters
    r.GET("/search", func(c *rue.Context) {
        q := c.Query("q")
        page := c.DefaultQuery("page", "1")
        c.JSON(http.StatusOK, rue.H{"query": q, "page": page})
    })

    r.Run(":8080")
}

Routing

Basic Routes
r.GET("/path", handler)
r.POST("/path", handler)
r.PUT("/path", handler)
r.DELETE("/path", handler)
r.PATCH("/path", handler)
r.HEAD("/path", handler)
r.OPTIONS("/path", handler)
r.Any("/path", handler)  // All methods
Route Groups
api := r.Group("/api")
{
    api.GET("/users", listUsers)

    v1 := api.Group("/v1")
    v1.Use(authMiddleware)
    {
        v1.GET("/posts", listPosts)
        v1.POST("/posts", createPost)
    }
}
Path Parameters
// Named parameter
r.GET("/users/:id", func(c *rue.Context) {
    id := c.Param("id")  // /users/123 -> id = "123"
})

// Wildcard parameter
r.GET("/files/*filepath", func(c *rue.Context) {
    path := c.Param("filepath")  // /files/docs/readme.md -> filepath = "docs/readme.md"
})

Request Handling

Data Binding
type CreateUser struct {
    Name  string `json:"name" validate:"required"`
    Email string `json:"email" validate:"required,email"`
    Age   int    `json:"age" validate:"min=18,max=120"`
}

r.POST("/users", func(c *rue.Context) {
    var user CreateUser

    // Bind and validate
    if err := c.BindJSON(&user); err != nil {
        c.AbortWithStatus(http.StatusBadRequest)
        return
    }

    if err := c.Validate(&user); err != nil {
        c.JSON(http.StatusBadRequest, rue.H{"errors": err})
        return
    }

    c.JSON(http.StatusCreated, user)
})
Validation Rules
  • required - Field must not be empty
  • min=N - Minimum value/length
  • max=N - Maximum value/length
  • len=N - Exact length
  • email - Valid email format
  • url - Valid URL format
  • regex=pattern - Match regex pattern
  • oneof=a b c - Value must be one of listed options
Response Methods
c.JSON(http.StatusOK, obj)           // JSON response
c.XML(http.StatusOK, obj)            // XML response
c.String(http.StatusOK, "fmt", args) // Formatted string (printf-style)
c.Text(http.StatusOK, "text")        // Plain text
c.Data(http.StatusOK, "text/html", []byte("<h1>Hi</h1>"))
c.File("path/to/file")
c.Stream(http.StatusOK, "application/octet-stream", reader)
c.Redirect(http.StatusFound, "/new-path")

Middleware

Built-in Middleware
// Logger - logs requests
r.Use(rue.RequestLogger())
r.Use(rue.LoggerWithConfig(rue.LoggerConfig{
    SkipPaths: []string{"/health"},
}))

// Recovery - recovers from panics
r.Use(rue.Recovery())

// CORS
r.Use(rue.CORS())
r.Use(rue.CORSWithConfig(rue.CORSConfig{
    AllowOrigins:     []string{"https://example.com"},
    AllowMethods:     []string{"GET", "POST"},
    AllowCredentials: true,
}))

// Rate Limiter
r.Use(rue.RateLimiter(10, 20))  // 10 req/sec, burst 20
r.Use(rue.RateLimiterWithConfig(rue.RateLimiterConfig{
    Rate:  100,
    Burst: 200,
    KeyFunc: func(c *rue.Context) string {
        return c.ClientIP()
    },
}))

// Compression
r.Use(rue.Gzip())      // Gzip only
r.Use(rue.Brotli())    // Brotli only
r.Use(rue.Compress())  // Auto-select (prefers Brotli)
JWT Authentication
secret := []byte("your-secret-key")

// Generate token
claims := &rue.JWTClaims{
    Subject:   "user123",
    ExpiresAt: time.Now().Add(24 * time.Hour).Unix(),
    Custom: map[string]any{
        "role": "admin",
    },
}
token, _ := rue.GenerateToken(claims, secret)

// Protect routes
r.Use(rue.JWT(secret))

r.GET("/protected", func(c *rue.Context) {
    claims, _ := c.Get("jwt_claims")
    c.JSON(http.StatusOK, claims)
})
API Key Authentication
r.Use(rue.APIKey(func(key string) bool {
    return key == "valid-api-key"
}))

// Or with config
r.Use(rue.APIKeyWithConfig(rue.APIKeyConfig{
    KeyLookup: "query:api_key",  // or "header:X-API-Key"
    Validator: func(key string) bool {
        return validateKey(key)
    },
}))
Custom Middleware
func MyMiddleware() rue.HandlerFunc {
    return func(c *rue.Context) {
        // Before request
        start := time.Now()

        c.Next()  // Process request

        // After request
        latency := time.Since(start)
        log.Printf("Request took %v", latency)
    }
}

WebSocket

r.GET("/ws", func(c *rue.Context) {
    handler := &rue.WebSocketHandler{
        OnConnect: func(conn *rue.WebSocketConn) {
            log.Println("Client connected")
        },
        OnMessage: func(conn *rue.WebSocketConn, msgType int, data []byte) {
            conn.Send(msgType, data)  // Echo
        },
        OnClose: func(conn *rue.WebSocketConn) {
            log.Println("Client disconnected")
        },
    }
    handler.Handle(c)
})

// With Hub for broadcasting
hub := rue.NewWebSocketHub()
go hub.Run()

r.GET("/ws", func(c *rue.Context) {
    handler := &rue.WebSocketHandler{
        Hub: hub,
        OnMessage: func(conn *rue.WebSocketConn, msgType int, data []byte) {
            hub.Broadcast(msgType, data)  // Send to all
        },
    }
    handler.Handle(c)
})

Server-Sent Events (SSE)

r.GET("/events", func(c *rue.Context) {
    client := rue.NewSSEClient(c)
    defer client.Close()

    for i := 0; i < 10; i++ {
        client.SendEvent("update", fmt.Sprintf("Event %d", i))
        time.Sleep(time.Second)
    }
})

GraphQL

schema := &rue.GraphQLSchema{
    Query: &rue.ObjectType{
        Name: "Query",
        Fields: map[string]*rue.Field{
            "hello": {
                Type: rue.StringType,
                Resolve: func(ctx *rue.ResolveContext) (any, error) {
                    return "Hello, World!", nil
                },
            },
            "user": {
                Type: userType,
                Args: map[string]*rue.Argument{
                    "id": {Type: rue.StringType},
                },
                Resolve: func(ctx *rue.ResolveContext) (any, error) {
                    id := ctx.Args["id"].(string)
                    return getUser(id), nil
                },
            },
        },
    },
}

handler := rue.NewGraphQLHandler(schema)
r.POST("/graphql", handler.Handle)
r.GET("/graphql", handler.Playground)  // GraphQL Playground UI

WebRTC Signaling

signaling := rue.NewSignalingServer()

r.GET("/webrtc", func(c *rue.Context) {
    signaling.Handle(c)
})

// Client sends JSON messages:
// {"type": "join", "room": "room1"}
// {"type": "offer", "sdp": "..."}
// {"type": "answer", "sdp": "..."}
// {"type": "candidate", "candidate": "..."}

QUIC/HTTP3

// Run HTTP/3 server
r.RunQUIC(":443", "cert.pem", "key.pem")

// With custom config
config := &rue.QUICConfig{
    MaxIncomingStreams: 100,
    IdleTimeout:        30 * time.Second,
    Enable0RTT:         true,
}
r.RunQUICWithConfig(":443", "cert.pem", "key.pem", config)

// Alt-Svc middleware (advertise HTTP/3 on HTTP/1.1 or HTTP/2)
r.Use(rue.AltSvc(":443"))

gRPC Integration

Rue provides seamless gRPC integration with middleware support.

import (
    "google.golang.org/grpc"
    "github.com/ch-hash-lab/rue"
)

// Create gRPC server with Rue engine
engine := rue.New()
gs := rue.NewGRPCServer(engine)

// Add Rue middleware as gRPC interceptors
gs.Use(func(c *rue.Context) {
    // This middleware runs for every gRPC call
    c.Set("request_id", generateID())
})

// Add native gRPC interceptors
gs.UseUnary(rue.GRPCLogger())
gs.UseUnary(rue.GRPCRecovery())

// Build and register services
server := gs.Build()
pb.RegisterMyServiceServer(server, &myService{})

// Run server
gs.Run(":50051")
gRPC Authentication
// JWT-style authentication for gRPC
authFunc := func(ctx context.Context) (context.Context, error) {
    md, ok := metadata.FromIncomingContext(ctx)
    if !ok {
        return nil, status.Error(codes.Unauthenticated, "no metadata")
    }

    tokens := md.Get("authorization")
    if len(tokens) == 0 {
        return nil, status.Error(codes.Unauthenticated, "no token")
    }

    // Validate token and add user to context
    user, err := validateToken(tokens[0])
    if err != nil {
        return nil, status.Error(codes.Unauthenticated, "invalid token")
    }

    return context.WithValue(ctx, "user", user), nil
}

gs.UseUnary(rue.GRPCAuth(authFunc))
gs.UseStream(rue.GRPCStreamAuth(authFunc))
Accessing Context in gRPC Handlers
func (s *myService) MyMethod(ctx context.Context, req *pb.Request) (*pb.Response, error) {
    // Get Rue's GRPCContext
    gc := rue.GetGRPCContext(ctx)
    if gc != nil {
        // Access values set by middleware
        requestID, _ := gc.Get("request_id")

        // Access metadata
        auth := gc.GetMetadata("authorization")
    }

    return &pb.Response{}, nil
}

Testing with Agent

func TestAPI(t *testing.T) {
    r := rue.New()
    r.GET("/users/:id", getUser)

    agent := rue.NewAgent(r)

    // Simple GET
    resp := agent.Get("/users/123")
    if resp.StatusCode != http.StatusOK {
        t.Errorf("Expected 200, got %d", resp.StatusCode)
    }

    // POST with JSON
    resp = agent.PostJSON("/users", map[string]string{
        "name": "John",
    })

    // With headers
    agent.SetHeader("Authorization", "Bearer token")
    resp = agent.Get("/protected")

    // Request builder
    resp = agent.NewRequest("POST", "/search").
        Query("q", "test").
        Header("X-Custom", "value").
        JSON(map[string]string{"filter": "active"}).
        Send()

    // Parse response
    var result map[string]any
    resp.JSON(&result)
}

Error Handling

// Predefined errors
rue.ErrBadRequest          // 400
rue.ErrUnauthorized        // 401
rue.ErrForbidden           // 403
rue.ErrNotFound            // 404
rue.ErrInternalServerError // 500

// Custom error
err := rue.NewError(http.StatusConflict, "Resource already exists")
err = err.WithDetails(map[string]string{"field": "email"})

// In handler
r.GET("/resource", func(c *rue.Context) {
    if notFound {
        c.AbortWithError(http.StatusNotFound, rue.ErrNotFound)
        return
    }
})

// Custom error handler
r.ErrorHandler = func(c *rue.Context, err error) {
    // Custom error handling logic
}

Lifecycle Hooks

r.OnRequest(func(c *rue.Context) {
    // Called before each request
})

r.OnResponse(func(c *rue.Context) {
    // Called after each request
})

r.OnStart(func() {
    log.Println("Server starting...")
})

r.OnShutdown(func() {
    log.Println("Server shutting down...")
})

Graceful Shutdown

r := rue.Default()
// ... setup routes

go func() {
    if err := r.Run(":8080"); err != nil {
        log.Fatal(err)
    }
}()

// Wait for interrupt signal
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit

// Graceful shutdown with timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
r.Shutdown(ctx)

Security Configuration

Trusted Proxies

By default, Rue does not trust any proxy headers (X-Forwarded-For, X-Real-IP). If your application is behind a reverse proxy, configure trusted proxies:

r := rue.New()

// Trust localhost and private networks
r.SetTrustedProxies([]string{
    "127.0.0.1",
    "10.0.0.0/8",
    "172.16.0.0/12",
    "192.168.0.0/16",
})
Request Body Size Limit

Rue limits request body size to 4MB by default to prevent DoS attacks:

r := rue.New()
r.MaxRequestBodySize = 10 << 20  // 10MB
Trailing Slash Redirect

Enable automatic redirect between /path and /path/:

r := rue.New()
r.RedirectTrailingSlash = true

HTML Templates

r := rue.New()

// Set custom template functions
r.SetFuncMap(template.FuncMap{
    "formatDate": func(t time.Time) string {
        return t.Format("2006-01-02")
    },
})

// Load templates from glob pattern
r.LoadHTMLGlob("templates/*.html")

// Or load from multiple levels with **
r.LoadHTMLGlob("templates/**/*.html")

// Or load specific files
r.LoadHTMLFiles("templates/index.html", "templates/about.html")

// Render template
r.GET("/", func(c *rue.Context) {
    c.HTML(http.StatusOK, "index.html", rue.H{
        "title": "Home",
        "user":  user,
    })
})

Benchmarks

BenchmarkRouter_StaticRoute-8       181342215    6.640 ns/op     0 B/op    0 allocs/op
BenchmarkRouter_ParamRoute-8         38045265   31.88 ns/op     32 B/op    1 allocs/op
BenchmarkRouter_ManyRoutes-8         24370306   48.98 ns/op     64 B/op    1 allocs/op
BenchmarkEngine_SimpleRoute-8         2905870  420.9 ns/op    1064 B/op   11 allocs/op
BenchmarkEngine_JSONResponse-8        1240557  982.0 ns/op    1632 B/op   16 allocs/op
BenchmarkGzip-8                         27502   42767 ns/op   30131 B/op   16 allocs/op
BenchmarkBrotli-8                       60792   19511 ns/op   30360 B/op   15 allocs/op

Dependencies

Originality

All code in this repository (v0.0.7+) is original work. The routing engine uses a segment-trie design with run-compressed literal chains, iterative backtracking, and method-switch dispatch — an independent architecture developed from first principles. Historical versions (v0.0.1–v0.0.6) contained code derived from gin and httprouter; see NOTICE for attribution.

License

MIT License

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

View Source
const (
	// Frame types
	TextMessage   = 1
	BinaryMessage = 2
	CloseMessage  = 8
	PingMessage   = 9
	PongMessage   = 10
)

WebSocket constants

View Source
const (
	// Environment variable name for mode
	EnvRueMode = "RUE_MODE"
)

Variables

View Source
var (
	ErrBadRequest          = NewError(http.StatusBadRequest, "Bad Request")
	ErrUnauthorized        = NewError(http.StatusUnauthorized, "Unauthorized")
	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")
	ErrServiceUnavailable  = NewError(http.StatusServiceUnavailable, "Service Unavailable")
	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

View Source
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

View Source
var (
	ErrWebSocketUpgrade     = errors.New("websocket: upgrade failed")
	ErrWebSocketClosed      = errors.New("websocket: connection closed")
	ErrWebSocketInvalidData = errors.New("websocket: invalid data")
)

WebSocket errors

View Source
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

View Source
var ErrRequestBodyTooLarge = errors.New("request body too large")

ErrRequestBodyTooLarge is returned when request body exceeds MaxRequestBodySize

View Source
var ErrWebSocketOriginNotAllowed = errors.New("websocket: origin not allowed")

ErrWebSocketOriginNotAllowed is returned when Origin validation fails

Functions

func DefaultErrorHandler

func DefaultErrorHandler(c *Context, err error)

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

func GenerateToken(claims *JWTClaims, secret []byte) (string, error)

GenerateToken generates a JWT token with the given claims

func GenerateTokenWithMethod

func GenerateTokenWithMethod(claims *JWTClaims, secret []byte, method string) (string, error)

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 LogDebug added in v0.0.2

func LogDebug(msg string)

Package-level logging functions

func LogDebugf added in v0.0.2

func LogDebugf(format string, args ...any)

func LogError added in v0.0.2

func LogError(msg string)

func LogErrorWithErr added in v0.0.2

func LogErrorWithErr(msg string, err error)

func LogErrorf added in v0.0.2

func LogErrorf(format string, args ...any)

func LogFatal added in v0.0.2

func LogFatal(msg string)

func LogFatalf added in v0.0.2

func LogFatalf(format string, args ...any)

func LogInfo added in v0.0.2

func LogInfo(msg string)

func LogInfof added in v0.0.2

func LogInfof(format string, args ...any)

func LogStat added in v0.0.2

func LogStat(msg string)

func LogStatf added in v0.0.2

func LogStatf(format string, args ...any)

func LogWarn added in v0.0.2

func LogWarn(msg string)

func LogWarnf added in v0.0.2

func LogWarnf(format string, args ...any)

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 NewAgent

func NewAgent(engine *Engine) *Agent

NewAgent creates a new Agent for testing

func (*Agent) AddHeader

func (a *Agent) AddHeader(key, value string) *Agent

AddHeader adds a header value

func (*Agent) ClearCookies

func (a *Agent) ClearCookies() *Agent

ClearCookies clears all cookies

func (*Agent) ClearHeaders

func (a *Agent) ClearHeaders() *Agent

ClearHeaders clears all headers

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) Get

func (a *Agent) Get(path string) *AgentResponse

Get performs a GET request

func (*Agent) Head

func (a *Agent) Head(path string) *AgentResponse

Head performs a HEAD request

func (*Agent) NewRequest

func (a *Agent) NewRequest(method, path string) *Request

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

func (*Agent) SetCookie

func (a *Agent) SetCookie(cookie *http.Cookie) *Agent

SetCookie sets a cookie for all requests

func (*Agent) SetHeader

func (a *Agent) SetHeader(key, value string) *Agent

SetHeader sets a header for all requests

type AgentResponse

type AgentResponse struct {
	StatusCode int
	Headers    http.Header
	Body       []byte
	Cookies    []*http.Cookie
}

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 Binder

type Binder interface {
	Bind(c *Context, obj any) error
}

Binder is the interface for request data binding

type BindingError

type BindingError struct {
	Field  string `json:"field"`
	Reason string `json:"reason"`
}

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) Abort

func (c *Context) Abort()

Abort prevents pending handlers from being called

func (*Context) AbortWithError

func (c *Context) AbortWithError(code int, err error)

AbortWithError aborts the request with an error

func (*Context) AbortWithJSON

func (c *Context) AbortWithJSON(code int, obj any)

AbortWithJSON aborts with a JSON response

func (*Context) AbortWithStatus

func (c *Context) AbortWithStatus(code int)

AbortWithStatus aborts with the specified status code

func (*Context) Bind

func (c *Context) Bind(obj any) error

Bind binds the request body to obj based on Content-Type

func (*Context) BindJSON

func (c *Context) BindJSON(obj any) error

BindJSON binds the JSON request body to obj

func (*Context) BindQuery

func (c *Context) BindQuery(obj any) error

BindQuery binds the query string to obj

func (*Context) ClientIP

func (c *Context) ClientIP() string

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

func (c *Context) ContentType() string

ContentType returns the Content-Type header

func (*Context) Context

func (c *Context) Context() context.Context

Context returns the request's context

func (*Context) Cookie

func (c *Context) Cookie(name string) (string, error)

Cookie returns the named cookie

func (*Context) Data

func (c *Context) Data(code int, contentType string, data []byte) error

Data writes raw bytes to the response

func (*Context) Deadline

func (c *Context) Deadline() (deadline time.Time, ok bool)

Deadline returns the time when work done on behalf of this context should be canceled

func (*Context) DefaultQuery added in v0.0.5

func (c *Context) DefaultQuery(key, defaultValue string) string

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) Err

func (c *Context) Err() error

Err returns the error value

func (*Context) Error

func (c *Context) Error(err error)

Error adds an error to the context

func (*Context) File

func (c *Context) File(filepath string)

File serves a file

func (*Context) FormFile

func (c *Context) FormFile(name string) (*multipart.FileHeader, error)

FormFile returns the first file for the provided form key

func (*Context) FullPath

func (c *Context) FullPath() string

FullPath returns the matched route full path

func (*Context) Get

func (c *Context) Get(key string) (any, bool)

Get retrieves a value from the context

func (*Context) GetBool

func (c *Context) GetBool(key string) bool

GetBool retrieves a bool value from the context

func (*Context) GetInt

func (c *Context) GetInt(key string) int

GetInt retrieves an int value from the context

func (*Context) GetString

func (c *Context) GetString(key string) string

GetString retrieves a string value from the context

func (*Context) HTML

func (c *Context) HTML(code int, name string, data any) error

HTML renders an HTML response using the engine's renderer

func (*Context) Header

func (c *Context) Header(key string) string

Header returns the request header value

func (*Context) IndentedJSON

func (c *Context) IndentedJSON(code int, obj any) error

IndentedJSON renders an indented JSON response

func (*Context) IsAborted

func (c *Context) IsAborted() bool

IsAborted returns true if the context was aborted

func (*Context) JSON

func (c *Context) JSON(code int, obj any) error

JSON renders a JSON response

func (*Context) MultipartForm

func (c *Context) MultipartForm() (*multipart.Form, error)

MultipartForm returns the multipart form

func (*Context) MustGet

func (c *Context) MustGet(key string) any

MustGet retrieves a value from the context, panics if not found

func (*Context) Next

func (c *Context) Next()

Next executes the pending handlers in the chain

func (*Context) Param

func (c *Context) Param(key string) string

Param returns the value of the URL param

func (*Context) PostForm

func (c *Context) PostForm(key string) string

PostForm returns the form data value

func (*Context) PostFormArray

func (c *Context) PostFormArray(key string) []string

PostFormArray returns a slice of strings for a given form key

func (*Context) PostFormDefault

func (c *Context) PostFormDefault(key, defaultValue string) string

PostFormDefault returns the form data value or a default

func (*Context) Query

func (c *Context) Query(key string) string

Query returns the query string parameter value

func (*Context) QueryArray

func (c *Context) QueryArray(key string) []string

QueryArray returns a slice of strings for a given query key

func (*Context) QueryDefault

func (c *Context) QueryDefault(key, defaultValue string) string

QueryDefault returns the query string parameter value or a default

func (*Context) QueryMap

func (c *Context) QueryMap(key string) map[string]string

QueryMap returns a map for a given query key

func (*Context) Redirect

func (c *Context) Redirect(code int, location string)

Redirect redirects the request

func (*Context) Set

func (c *Context) Set(key string, value any)

Set stores a key-value pair in the context

func (*Context) SetCookie

func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool)

SetCookie sets a cookie

func (*Context) SetHeader

func (c *Context) SetHeader(key, value string)

SetHeader sets a response header

func (*Context) ShouldBind

func (c *Context) ShouldBind(obj any) error

ShouldBind binds the request body to obj, returns error without aborting

func (*Context) ShouldBindJSON

func (c *Context) ShouldBindJSON(obj any) error

ShouldBindJSON binds the JSON request body to obj

func (*Context) Status

func (c *Context) Status(code int) *Context

Status sets the HTTP response status code

func (*Context) Stream

func (c *Context) Stream(code int, contentType string, reader io.Reader) error

Stream sends a streaming response

func (*Context) String

func (c *Context) String(code int, format string, values ...any) error

String renders a string response with optional format arguments

func (*Context) Text

func (c *Context) Text(code int, text string) error

Text renders a plain text response (no formatting)

func (*Context) Validate added in v0.0.5

func (c *Context) Validate(obj any) error

Validate validates the given struct using the engine's validator

func (*Context) Value

func (c *Context) Value(key any) any

Value returns the value associated with this context for key

func (*Context) XML

func (c *Context) XML(code int, obj any) error

XML renders an XML response

type DefaultBinder

type DefaultBinder struct{}

DefaultBinder is the default implementation of Binder

func (*DefaultBinder) Bind

func (b *DefaultBinder) Bind(c *Context, obj any) error

Bind binds the request data to obj based on Content-Type

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 Delims added in v0.0.2

type Delims struct {
	Left  string
	Right string
}

Delims represents template delimiters

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 Default

func Default() *Engine

Default creates an Engine with Logger and Recovery middleware

func New

func New() *Engine

New creates a new Engine instance without any middleware

func (*Engine) Delims added in v0.0.2

func (e *Engine) Delims(left, right string) *Engine

Delims sets the template delimiters for the engine

func (*Engine) DisableStats added in v0.0.3

func (e *Engine) DisableStats() *Engine

DisableStats disables system statistics reporting

func (*Engine) GetHTMLTemplate added in v0.0.2

func (e *Engine) GetHTMLTemplate() *template.Template

GetHTMLTemplate returns the current HTML template

func (*Engine) LoadHTMLFS added in v0.0.2

func (e *Engine) LoadHTMLFS(fsys fs.FS, patterns ...string) error

LoadHTMLFS loads HTML templates from an embed.FS or other fs.FS

func (*Engine) LoadHTMLFSRecursive added in v0.0.2

func (e *Engine) LoadHTMLFSRecursive(fsys fs.FS, root string, filePattern string) error

LoadHTMLFSRecursive loads HTML templates recursively from an fs.FS

func (*Engine) LoadHTMLFiles added in v0.0.2

func (e *Engine) LoadHTMLFiles(files ...string) error

LoadHTMLFiles loads specific HTML template files

func (*Engine) LoadHTMLGlob added in v0.0.2

func (e *Engine) LoadHTMLGlob(pattern string) error

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) OnRequest

func (e *Engine) OnRequest(fn func(*Context))

OnRequest registers a hook to be called for each request

func (*Engine) OnResponse

func (e *Engine) OnResponse(fn func(*Context))

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) Run

func (e *Engine) Run(addr string) error

Run starts the HTTP server

func (*Engine) RunDualStack

func (e *Engine) RunDualStack(httpAddr, http3Addr, certFile, keyFile string) error

RunDualStack starts both HTTP/1.1+2 and HTTP/3 servers

func (*Engine) RunQUIC

func (e *Engine) RunQUIC(addr, certFile, keyFile string) error

RunQUIC starts the HTTP/3 server on the engine

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) RunTLS

func (e *Engine) RunTLS(addr, certFile, keyFile string) error

RunTLS starts the HTTPS server

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

func (e *Engine) SetFuncMap(funcMap template.FuncMap)

SetFuncMap sets the template function map for the engine

func (*Engine) SetHTMLTemplate added in v0.0.2

func (e *Engine) SetHTMLTemplate(tmpl *template.Template)

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

func (e *Engine) SetStatsInterval(interval time.Duration) *Engine

SetStatsInterval sets the interval for stats reporting

func (*Engine) SetTrustedProxies added in v0.0.5

func (e *Engine) SetTrustedProxies(proxies []string) error

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"})

func (*Engine) Shutdown

func (e *Engine) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server

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 NewError

func NewError(code int, message string) *Error

NewError creates a new Error

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface

func (*Error) Is

func (e *Error) Is(target error) bool

Is implements errors.Is interface for error comparison

func (*Error) StatusCode

func (e *Error) StatusCode() int

StatusCode returns the HTTP status code

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the wrapped error

func (*Error) WithDetails

func (e *Error) WithDetails(details any) *Error

WithDetails adds details to the error and returns a new Error

func (*Error) WithError

func (e *Error) WithError(err error) *Error

WithError wraps an error and returns a new Error

func (*Error) WithMessage

func (e *Error) WithMessage(message string) *Error

WithMessage creates a new Error with a custom message

type ErrorHandler

type ErrorHandler func(*Context, error)

ErrorHandler is the function type for handling errors

type ErrorHandlerFunc

type ErrorHandlerFunc func(c *Context, err error)

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 NewExecutor

func NewExecutor(schema *Schema) *Executor

NewExecutor creates a new executor

func NewExecutorWithLimits added in v0.0.5

func NewExecutorWithLimits(schema *Schema, maxDepth, maxComplexity int) *Executor

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) Abort

func (gc *GRPCContext) Abort()

Abort marks the context as aborted

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) Errors

func (gc *GRPCContext) Errors() []error

Errors returns all errors

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) Stop

func (gs *GRPCServer) Stop()

Stop immediately stops the 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

type GraphQLType interface {
	Name() string
	Description() string
}

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 H

type H map[string]any

H is a convenience alias for map[string]any, used for structured responses

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

func (*HTMLRenderer) Render added in v0.0.2

func (r *HTMLRenderer) Render(w io.Writer, name string, data any) error

Render implements the Renderer interface

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) Close

func (s *HTTP3Server) Close() error

Close closes the 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 Brotli

func Brotli() HandlerFunc

Brotli returns a Brotli middleware with default config

func BrotliWithConfig

func BrotliWithConfig(config BrotliConfig) HandlerFunc

BrotliWithConfig returns a Brotli middleware with custom config

func CORS

func CORS() HandlerFunc

CORS returns a CORS middleware with default 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 GraphQL

func GraphQL(schema *Schema) HandlerFunc

GraphQL returns a GraphQL handler

func GraphQLWithConfig

func GraphQLWithConfig(config GraphQLConfig) HandlerFunc

GraphQLWithConfig returns a GraphQL handler with custom config

func Gzip

func Gzip() HandlerFunc

Gzip returns a Gzip middleware with default config

func GzipWithConfig

func GzipWithConfig(config GzipConfig) HandlerFunc

GzipWithConfig returns a Gzip middleware with custom config

func JWT

func JWT(secret []byte) HandlerFunc

JWT returns a JWT middleware with the given secret

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

func ParseToken

func ParseToken(tokenString string, secret []byte) (*JWTClaims, error)

ParseToken parses and validates a JWT token

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 Location

type Location struct {
	Line   int `json:"line"`
	Column int `json:"column"`
}

Location represents a location in the query

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 LogFormat added in v0.0.2

type LogFormat int

LogFormat represents the output format of logs

const (
	// TextFormat outputs logs in human-readable text format
	TextFormat LogFormat = iota
	// JSONFormat outputs logs in JSON format
	JSONFormat
)

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
)

func (LogLevel) Color added in v0.0.2

func (l LogLevel) Color() string

Color returns the ANSI color code for the log level

func (LogLevel) String added in v0.0.2

func (l LogLevel) String() string

String returns the string representation of the log level

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) Debug added in v0.0.2

func (l *Logger) Debug(msg string)

Debug logs a debug message

func (*Logger) Debugf added in v0.0.2

func (l *Logger) Debugf(format string, args ...any)

Debugf logs a formatted debug message

func (*Logger) Error added in v0.0.2

func (l *Logger) Error(msg string)

Error logs an error message

func (*Logger) ErrorWithErr added in v0.0.2

func (l *Logger) ErrorWithErr(msg string, err error)

ErrorWithErr logs an error message with an error

func (*Logger) Errorf added in v0.0.2

func (l *Logger) Errorf(format string, args ...any)

Errorf logs a formatted error message

func (*Logger) Fatal added in v0.0.2

func (l *Logger) Fatal(msg string)

Fatal logs a fatal message and exits

func (*Logger) Fatalf added in v0.0.2

func (l *Logger) Fatalf(format string, args ...any)

Fatalf logs a formatted fatal message and exits

func (*Logger) Info added in v0.0.2

func (l *Logger) Info(msg string)

Info logs an info message

func (*Logger) Infof added in v0.0.2

func (l *Logger) Infof(format string, args ...any)

Infof logs a formatted info message

func (*Logger) SetFormat added in v0.0.2

func (l *Logger) SetFormat(format LogFormat)

SetFormat sets the log format

func (*Logger) SetLevel added in v0.0.2

func (l *Logger) SetLevel(level LogLevel)

SetLevel sets the log level

func (*Logger) Stat added in v0.0.2

func (l *Logger) Stat(msg string)

Stat logs a statistics message

func (*Logger) Statf added in v0.0.2

func (l *Logger) Statf(format string, args ...any)

Statf logs a formatted statistics message

func (*Logger) Warn added in v0.0.2

func (l *Logger) Warn(msg string)

Warn logs a warning message

func (*Logger) Warnf added in v0.0.2

func (l *Logger) Warnf(format string, args ...any)

Warnf logs a formatted warning message

func (*Logger) WithFields added in v0.0.2

func (l *Logger) WithFields(fields map[string]any) *Logger

WithFields returns a new logger with the given fields

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 Mode added in v0.0.2

type Mode string

Mode represents the running mode of the framework

const (
	// DevMode is development mode with verbose logging
	DevMode Mode = "dev"
	// PrdMode is production mode with optimized settings
	PrdMode Mode = "prd"
)

func GetMode added in v0.0.2

func GetMode() Mode

GetMode returns the current running mode

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

type ModeConfig struct {
	LogLevel     LogLevel
	LogFormat    LogFormat
	EnableCaller bool
	EnableColor  bool
}

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 Operation

type Operation struct {
	Type       string // "query" or "mutation"
	Name       string
	Selections []Selection
}

Operation represents a GraphQL operation

type Param

type Param struct {
	Key   string
	Value string
}

Param is a single path parameter

type Params

type Params []Param

Params holds path parameters

func (Params) ByName

func (ps Params) ByName(name string) string

ByName returns the value of the first Param which key matches the given name

func (Params) Get

func (ps Params) Get(name string) (string, bool)

Get returns the value of the first Param which key matches the given name

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

type RecoveryConfig struct {
	StackSize  int
	StackAll   bool
	PrintStack bool
	Output     io.Writer
}

RecoveryConfig defines the config for Recovery middleware

func DefaultRecoveryConfig

func DefaultRecoveryConfig() RecoveryConfig

DefaultRecoveryConfig returns the default recovery config

type Renderer

type Renderer interface {
	Render(w io.Writer, name string, data any) error
}

Renderer is the interface for response rendering

type Request

type Request struct {
	// contains filtered or unexported fields
}

Request is a builder for creating requests

func (*Request) Body

func (r *Request) Body(body io.Reader) *Request

Body sets the request body

func (*Request) Form

func (r *Request) Form(data url.Values) *Request

Form sets the body as form data

func (*Request) Header

func (r *Request) Header(key, value string) *Request

Header sets a header

func (*Request) JSON

func (r *Request) JSON(obj any) *Request

JSON sets the body as JSON

func (*Request) Query

func (r *Request) Query(key, value string) *Request

Query sets a query parameter

func (*Request) Send

func (r *Request) Send() *AgentResponse

Send executes the request

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

type SDPMessage struct {
	Type string `json:"type"` // "offer" or "answer"
	SDP  string `json:"sdp"`
}

SDPMessage represents an SDP offer/answer

type SSEClient

type SSEClient struct {
	// contains filtered or unexported fields
}

SSEClient represents an SSE client connection

func SSE

func SSE(c *Context) (*SSEClient, error)

SSE creates an SSE client from the context

func SSEWithConfig

func SSEWithConfig(c *Context, config SSEConfig) (*SSEClient, error)

SSEWithConfig creates an SSE client with custom config

func (*SSEClient) Close

func (s *SSEClient) Close()

Close closes the SSE connection

func (*SSEClient) Done

func (s *SSEClient) Done() <-chan struct{}

Done returns a channel that's closed when the client disconnects

func (*SSEClient) IsClosed

func (s *SSEClient) IsClosed() bool

IsClosed returns true if the connection is closed

func (*SSEClient) Send

func (s *SSEClient) Send(event *SSEEvent) error

Send sends an SSE event

func (*SSEClient) SendComment

func (s *SSEClient) SendComment(comment string) error

SendComment sends a comment (for keep-alive)

func (*SSEClient) SendData

func (s *SSEClient) SendData(data string) error

SendData sends a simple data event

func (*SSEClient) SendEvent

func (s *SSEClient) SendEvent(event, data string) error

SendEvent sends a named event with data

func (*SSEClient) SendEventWithID

func (s *SSEClient) SendEventWithID(id, event, data string) error

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 SSEEvent

type SSEEvent struct {
	ID      string
	Event   string
	Data    string
	Retry   int
	Comment string
}

SSEEvent represents a Server-Sent Event

type SSEHub

type SSEHub struct {
	// contains filtered or unexported fields
}

SSEHub manages SSE client connections

func NewSSEHub

func NewSSEHub() *SSEHub

NewSSEHub creates a new SSE hub

func (*SSEHub) Broadcast

func (h *SSEHub) Broadcast(event *SSEEvent)

Broadcast sends an event to all clients

func (*SSEHub) BroadcastData

func (h *SSEHub) BroadcastData(data string)

BroadcastData sends data to all clients

func (*SSEHub) BroadcastDataToRoom

func (h *SSEHub) BroadcastDataToRoom(room, data string)

BroadcastDataToRoom sends data to all clients in a room

func (*SSEHub) BroadcastToRoom

func (h *SSEHub) BroadcastToRoom(room string, event *SSEEvent)

BroadcastToRoom sends an event to all clients in a room

func (*SSEHub) Count

func (h *SSEHub) Count() int

Count returns the number of clients

func (*SSEHub) Join

func (h *SSEHub) Join(client *SSEClient, room string)

Join adds a client to a room

func (*SSEHub) Leave

func (h *SSEHub) Leave(client *SSEClient, room string)

Leave removes a client from a room

func (*SSEHub) Register

func (h *SSEHub) Register(client *SSEClient)

Register adds a client to the hub

func (*SSEHub) RoomCount

func (h *SSEHub) RoomCount(room string) int

RoomCount returns the number of clients in a room

func (*SSEHub) Unregister

func (h *SSEHub) Unregister(client *SSEClient)

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 NewSchema

func NewSchema() *Schema

NewSchema creates a new GraphQL schema

func (*Schema) SetMutation

func (s *Schema) SetMutation(mutation *ObjectType)

SetMutation sets the mutation type

func (*Schema) SetQuery

func (s *Schema) SetQuery(query *ObjectType)

SetQuery sets the query type

type Selection

type Selection struct {
	Name       string
	Alias      string
	Args       map[string]any
	Selections []Selection
}

Selection represents a field selection

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

type ValidationFunc func(field reflect.Value, param string) bool

ValidationFunc is a custom validation function

type Validator

type Validator interface {
	Validate(obj any) error
}

Validator is the interface for data validation

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) Get

func (c *WebSocketConn) Get(key string) (any, bool)

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

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL