server

package
v0.0.0-...-5b3c889 Latest Latest
Warning

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

Go to latest
Published: Jan 28, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetBuffer

func GetBuffer(size int) []byte

GetBuffer returns a buffer of at least the requested size

func PutBuffer

func PutBuffer(buf []byte)

PutBuffer returns a buffer to the pool

Types

type BufferPool

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

BufferPool manages reusable byte buffers

type BufferedReader

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

BufferedReader can be used in parser.go to reuse buffers

func NewBufferedReader

func NewBufferedReader() *BufferedReader

NewBufferedReader creates a new buffered reader with pooled buffer

func (*BufferedReader) Buffer

func (br *BufferedReader) Buffer() []byte

Buffer returns the internal buffer

func (*BufferedReader) Close

func (br *BufferedReader) Close()

Close returns the buffer to the pool

type CORSConfig

type CORSConfig struct {
	AllowedOrigins   []string
	AllowedMethods   []string
	AllowedHeaders   []string
	AllowCredentials bool
	MaxAge           time.Duration
}

CORSConfig configures CORS middleware

func DefaultCORSConfig

func DefaultCORSConfig() CORSConfig

DefaultCORSConfig returns a permissive CORS config (for development)

type Config

type Config struct {
	Port               int           // Port to listen on
	ReadTimeout        time.Duration // Max time to read request
	WriteTimeout       time.Duration // Max time to write response
	IdleTimeout        time.Duration // Max time for keep-alive
	MaxHeaderBytes     int           // Max header size
	MaxRequestBodySize int64         // Max request body size
	MaxConns           int           // Max concurrent connections

	// Network-level config
	ReusePort   bool          // SO_REUSEPORT for multi-process
	DeferAccept time.Duration // TCP_DEFER_ACCEPT optimization

	// Request limits (DoS protection)
	MaxRequestsPerConn int           // Max requests per connection
	RequestTimeout     time.Duration // Total time for request including body
}

Config holds server configuration

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns sensible defaults

type Context

type Context struct {
	Request   *request.Request
	Response  *response.Writer
	Params    map[string]string // Path parameters (e.g., /users/:id)
	RequestID string            // ✅ Issue #8: Request ID for tracing
	// contains filtered or unexported fields
}

Context provides a convenient interface for handling requests and responses

func NewContext

func NewContext(req *request.Request, resp *response.Writer, conn net.Conn) *Context

NewContext creates a new context

func (*Context) Body

func (c *Context) Body() []byte

Body returns the request body as bytes

func (*Context) BodyString

func (c *Context) BodyString() string

BodyString returns the request body as a string

func (*Context) Error

func (c *Context) Error(code response.StatusCode, message string) error

Error sends an error response

func (*Context) GetClientIP

func (c *Context) GetClientIP() string

GetClientIP returns the client IP address

func (*Context) HTML

func (c *Context) HTML(code response.StatusCode, html string) error

HTML sends an HTML response

func (*Context) Header

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

Header gets a request header value

func (*Context) Hijack

func (c *Context) Hijack() (net.Conn, error)

✅ Issue #6: Hijack takes over the underlying connection (for WebSockets)

func (*Context) IsHijacked

func (c *Context) IsHijacked() bool

IsHijacked returns true if the connection has been hijacked

func (*Context) IsWebSocketUpgrade

func (c *Context) IsWebSocketUpgrade() bool

IsWebSocketUpgrade checks if this is a WebSocket upgrade request

func (*Context) JSON

func (c *Context) JSON(code response.StatusCode, json string) error

JSON sends a JSON response

func (*Context) Method

func (c *Context) Method() string

Method returns the HTTP method

func (*Context) NoContent

func (c *Context) NoContent() error

NoContent sends a 204 No Content response

func (*Context) Param

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

Param gets a path parameter by name

func (*Context) Path

func (c *Context) Path() string

Path returns the request path

func (*Context) Query

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

Query gets a query parameter (basic implementation)

func (*Context) Redirect

func (c *Context) Redirect(code response.StatusCode, location string) error

Redirect sends a redirect response

func (*Context) SetParams

func (c *Context) SetParams(params map[string]string)

SetParams sets path parameters (called by router)

func (*Context) Status

func (c *Context) Status(code response.StatusCode) error

Status sends just a status code with no body

func (*Context) String

func (c *Context) String(code response.StatusCode, format string, values ...interface{}) error

String is a helper for formatting responses

func (*Context) Text

func (c *Context) Text(code response.StatusCode, text string) error

Text sends a plain text response

type DefaultLogger

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

DefaultLogger is a simple stdout logger

func (*DefaultLogger) Debug

func (l *DefaultLogger) Debug(msg string, fields ...Field)

func (*DefaultLogger) Error

func (l *DefaultLogger) Error(msg string, fields ...Field)

func (*DefaultLogger) Info

func (l *DefaultLogger) Info(msg string, fields ...Field)

func (*DefaultLogger) Warn

func (l *DefaultLogger) Warn(msg string, fields ...Field)

type Field

type Field struct {
	Key   string
	Value interface{}
}

Field represents a structured log field

type Handler

type Handler interface {
	ServeHTTP(ctx *Context)
}

Handler processes HTTP requests

type HandlerFunc

type HandlerFunc func(ctx *Context)

HandlerFunc type adapter

func (HandlerFunc) ServeHTTP

func (f HandlerFunc) ServeHTTP(ctx *Context)

type Logger

type Logger interface {
	Debug(msg string, fields ...Field)
	Info(msg string, fields ...Field)
	Error(msg string, fields ...Field)
	Warn(msg string, fields ...Field)
}

Logger interface for structured logging

type Metrics

type Metrics struct {
	RequestsTotal     atomic.Int64
	ActiveConnections atomic.Int64
	ErrorsTotal       atomic.Int64
	Errors4xx         atomic.Int64
	Errors5xx         atomic.Int64

	// Latency tracking (simplified - use histogram in production)
	TotalLatencyNs atomic.Int64
}

Metrics holds server runtime metrics

func NewMetrics

func NewMetrics() *Metrics

NewMetrics creates a new metrics instance

func (*Metrics) AverageLatency

func (m *Metrics) AverageLatency() time.Duration

AverageLatency returns average request latency

func (*Metrics) RecordRequest

func (m *Metrics) RecordRequest(statusCode int, duration time.Duration)

RecordRequest records a completed request

func (*Metrics) Snapshot

func (m *Metrics) Snapshot() MetricsSnapshot

type MetricsSnapshot

type MetricsSnapshot struct {
	RequestsTotal     int64
	ActiveConnections int64
	ErrorsTotal       int64
	Errors4xx         int64
	Errors5xx         int64
	AverageLatency    time.Duration
}

Snapshot returns a snapshot of current metrics

type Middleware

type Middleware func(Handler) Handler

Middleware wraps a handler

func CORSMiddleware

func CORSMiddleware(config CORSConfig) Middleware

✅ Issue #21: CORS Middleware

func CompressionMiddleware

func CompressionMiddleware() Middleware

CompressionMiddleware adds gzip compression (placeholder) ✅ Issue #11: Compression support (simplified)

func LoggingMiddleware

func LoggingMiddleware(logger Logger) Middleware

LoggingMiddleware logs all requests

func MetricsMiddleware

func MetricsMiddleware(metrics *Metrics) Middleware

MetricsMiddleware records request metrics

func RateLimitMiddleware

func RateLimitMiddleware(limiter *RateLimiter) Middleware

✅ Issue #20: Rate Limiting Middleware

func RecoveryMiddleware

func RecoveryMiddleware(logger Logger) Middleware

RecoveryMiddleware recovers from panics

func RequestIDMiddleware

func RequestIDMiddleware() Middleware

RequestIDMiddleware adds a unique ID to each request

func TimeoutMiddleware

func TimeoutMiddleware(timeout time.Duration) Middleware

TimeoutMiddleware enforces a timeout on request handling

type NullLogger

type NullLogger struct{}

NullLogger discards all logs (for testing)

func (*NullLogger) Debug

func (n *NullLogger) Debug(msg string, fields ...Field)

func (*NullLogger) Error

func (n *NullLogger) Error(msg string, fields ...Field)

func (*NullLogger) Info

func (n *NullLogger) Info(msg string, fields ...Field)

func (*NullLogger) Warn

func (n *NullLogger) Warn(msg string, fields ...Field)

type RateLimiter

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

RateLimiter implements a simple token bucket rate limiter per IP

func NewRateLimiter

func NewRateLimiter(rate int, window time.Duration) *RateLimiter

NewRateLimiter creates a new rate limiter rate: number of requests allowed per window window: time window (e.g., 1 minute)

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(ip string) bool

Allow checks if a request from the given IP should be allowed

type Server

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

func New

func New(config *Config, handler Handler) *Server

New creates a new server with the given configuration and handler

func (*Server) ListenAndServe

func (s *Server) ListenAndServe() error

ListenAndServe starts the server using custom net library

func (*Server) Metrics

func (s *Server) Metrics() *Metrics

Metrics returns server metrics

func (*Server) SetLogger

func (s *Server) SetLogger(logger Logger)

SetLogger sets a custom logger for the server

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server

func (*Server) Stats

func (s *Server) Stats() interface{}

Stats returns listener statistics (if available)

func (*Server) Use

func (s *Server) Use(mw Middleware)

Use adds a middleware to the server

Jump to

Keyboard shortcuts

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