Skip to content

Context, Handler, Router, and Middleware #20

@FumingPower3925

Description

@FumingPower3925

Summary

Core application-level abstractions: request context, handler types, router with pattern matching, and middleware chain.

Context

  • Zero-copy contract:
    • Body() returns volatile slice (only valid during handler execution)
    • BodyBytes() returns a copy (safe to store/pass around)
  • Methods: Method(), Path(), Param(name), Query(name), Header(name), SetHeader(), Status(), JSON(), String(), Bytes(), Stream()
  • Port from old_celeris/pkg/celeris/context.go

Handler

type Handler interface {
    Handle(ctx *Context)
}
type HandlerFunc func(ctx *Context)

Router

  • Static routes: /users, /health
  • Parameter routes: /users/:id, /posts/:id/comments/:cid
  • Wildcard routes: /static/*filepath
  • Route groups: server.Group("/api/v1")
  • Method-specific: GET(), POST(), PUT(), DELETE(), PATCH(), HEAD(), OPTIONS()
  • Port from old_celeris/pkg/celeris/router.go

Middleware

  • Chain execution: middleware1 → middleware2 → handler → middleware2 → middleware1
  • ctx.Next() to continue chain, ctx.Abort() to stop
  • Built-in middleware:
    • Logger — request logging with duration
    • Recovery — panic recovery with stack trace
    • CORS — configurable cross-origin headers
    • RequestID — UUID per request via X-Request-ID
    • Compress — gzip/deflate response compression
    • RateLimit — token bucket per-IP rate limiting
    • Health/health endpoint
    • Timeout — per-request timeout with context cancellation
  • Port from old_celeris/pkg/celeris/middleware.go

stdlib Bridge

// Adapt wraps an http.Handler for use with Celeris
func Adapt(h http.Handler) HandlerFunc

Tests

  • Context: all getter/setter methods
  • Context: zero-copy contract (Body() volatile, BodyBytes() safe)
  • Router: static, param, wildcard patterns
  • Router: route groups with prefix
  • Router: method routing
  • Middleware: execution order (pre-handler, post-handler)
  • Middleware: Abort() stops chain
  • Each built-in middleware individually
  • Adapt() bridge with http.Handler

SDD Reference

Sections 11.4, 11.5

Dependencies

Depends on #3, #4

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions