edge

package
v1.5.2 Latest Latest
Warning

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

Go to latest
Published: Aug 19, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package edge provides request-preprocessing middleware for Nimbus.

Despite the name, this runs inside your application (it is Nimbus middleware), not on a CDN. It sits in front of your routes and can short- circuit, redirect, rewrite, or decorate requests before they reach your handlers — useful for geo routing, A/B tests, maintenance windows, security headers, basic auth, CORS, simple rate limiting, and response caching. It reads CDN geo headers (CF-IPCountry, X-Vercel-IP-Country, …) when a real CDN sits in front of your app.

For deploying to an actual edge/serverless runtime, see the `serverless` package (AWS Lambda).

Usage:

rt := edge.New(edge.Config{MaxExecTime: 50 * time.Millisecond})
rt.Handle("/geo", func(req *edge.Request) *edge.Response {
    if req.Geo.Country == "DE" {
        return edge.Redirect("/de"+req.Path, 302)
    }
    return edge.Next() // continue to the normal handler
})

app.Use(rt.Plugin())            // registers the middleware + /_edge/metrics
// or, without the plugin:
// app.Router.Use(rt.Middleware())

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ABVariant

type ABVariant struct {
	Name   string
	Path   string
	Weight int
}

ABVariant defines an A/B test variant.

type Cache

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

Cache provides a simple in-memory key-value cache for edge functions.

func NewCache

func NewCache(maxSize int) *Cache

NewCache creates a new edge cache.

func (*Cache) Delete

func (c *Cache) Delete(key string)

Delete removes a value from cache.

func (*Cache) Get

func (c *Cache) Get(key string) ([]byte, bool)

Get retrieves a value from cache.

func (*Cache) Set

func (c *Cache) Set(key string, value []byte, ttl time.Duration)

Set stores a value in cache with TTL.

type Config

type Config struct {
	// MaxExecTime bounds how long the runtime waits for a handler (default 50ms).
	// A timeout-scoped context is passed to the handler via req.Context(); note
	// that Go cannot forcibly stop a goroutine, so a handler that ignores its
	// context keeps running in the background after a timeout.
	MaxExecTime time.Duration

	// MaxBodyBytes caps how many request-body bytes the runtime reads and
	// exposes on req.Body (default 4MB). The full body is still forwarded to
	// downstream handlers.
	MaxBodyBytes int64

	// CacheDefault TTL for route caching when none is given (default 60s).
	CacheDefault time.Duration

	// Fallback behavior when a handler panics or times out (default FallbackNext).
	Fallback FallbackMode

	// OnError is called for handler panics and timeouts.
	OnError func(path string, err error)

	// Prefix is prepended to every registered edge path (default "").
	Prefix string
}

Config for the edge middleware runtime.

type EdgePlugin

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

EdgePlugin wires the runtime into a Nimbus app: it applies the middleware and mounts a /_edge/metrics endpoint.

func (*EdgePlugin) Boot

func (ep *EdgePlugin) Boot(*nimbus.App) error

func (*EdgePlugin) Name

func (ep *EdgePlugin) Name() string

func (*EdgePlugin) Register

func (ep *EdgePlugin) Register(app *nimbus.App) error

Register applies the edge middleware to the application router.

func (*EdgePlugin) RegisterRoutes

func (ep *EdgePlugin) RegisterRoutes(r *router.Router)

RegisterRoutes mounts the metrics endpoint.

func (*EdgePlugin) Version

func (ep *EdgePlugin) Version() string

type FallbackMode

type FallbackMode int

FallbackMode determines behavior on handler failure.

const (
	// FallbackNext passes the request through to the normal handler.
	FallbackNext FallbackMode = iota
	// FallbackError returns a 502 Bad Gateway.
	FallbackError
	// FallbackCached returns the last successful response for the route, if any.
	FallbackCached
)

type GeoInfo

type GeoInfo struct {
	Country    string  `json:"country"`
	Region     string  `json:"region"`
	City       string  `json:"city"`
	Latitude   float64 `json:"latitude"`
	Longitude  float64 `json:"longitude"`
	Timezone   string  `json:"timezone"`
	ISP        string  `json:"isp"`
	Datacenter string  `json:"datacenter"`
}

GeoInfo provides geographic information derived from CDN headers.

type HandlerFunc

type HandlerFunc func(req *Request) *Response

HandlerFunc is the signature for edge handlers.

func ABTest

func ABTest(variants []ABVariant) HandlerFunc

ABTest creates an edge function for A/B testing.

func BasicAuth

func BasicAuth(realm string, credentials map[string]string) HandlerFunc

BasicAuth creates an edge-level basic authentication check.

func CORSHeaders

func CORSHeaders(origins []string, methods []string, headers []string) HandlerFunc

CORSHeaders creates an edge function that handles CORS preflight.

func GeoRouter

func GeoRouter(routes map[string]string, fallback string) HandlerFunc

GeoRouter creates an edge function that routes based on country.

func Maintenance

func Maintenance(html string, allowedIPs ...string) HandlerFunc

Maintenance creates an edge function that returns a maintenance page.

func RateLimit

func RateLimit(maxRequests int, window time.Duration) HandlerFunc

RateLimit creates a simple edge-level rate limiter.

func SecurityHeaders

func SecurityHeaders() HandlerFunc

SecurityHeaders adds common security headers at the edge.

type Request

type Request struct {
	Method    string            `json:"method"`
	Path      string            `json:"path"`
	Query     map[string]string `json:"query"`
	Headers   map[string]string `json:"headers"`
	Body      []byte            `json:"body,omitempty"`
	IP        string            `json:"ip"`
	Geo       GeoInfo           `json:"geo"`
	StartTime time.Time         `json:"-"`
	// contains filtered or unexported fields
}

Request is a lightweight view of an HTTP request for edge handlers.

func (*Request) Context

func (r *Request) Context() context.Context

Context returns the request context (timeout-scoped to MaxExecTime).

func (*Request) Header

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

Header returns a request header value (canonicalized).

func (*Request) ParseJSON

func (r *Request) ParseJSON(v any) error

ParseJSON decodes the request body into v.

func (*Request) QueryParam

func (r *Request) QueryParam(key string) string

QueryParam returns a query parameter value.

type Response

type Response struct {
	Status  int               `json:"status"`
	Headers map[string]string `json:"headers"`
	Body    []byte            `json:"body,omitempty"`
	BodyStr string            `json:"-"`
	// contains filtered or unexported fields
}

Response is an edge handler's response.

func Cached

func Cached(resp *Response, ttl time.Duration) *Response

Cached creates a response that should be cached.

func HTML

func HTML(status int, html string) *Response

HTML creates an HTML response.

func JSON

func JSON(status int, data any) *Response

JSON creates a JSON response.

func Next

func Next() *Response

Next continues to the normal handler.

func Redirect

func Redirect(url string, status int) *Response

Redirect creates a redirect response.

func Respond

func Respond(status int, body string) *Response

Respond creates a plain-text response.

func Rewrite

func Rewrite(url string) *Response

Rewrite rewrites the request URL path without a client-visible redirect.

func (*Response) IsNext

func (r *Response) IsNext() bool

IsNext reports whether the request should continue to the normal handler.

func (*Response) SetHeader

func (r *Response) SetHeader(key, value string) *Response

SetHeader sets a response header.

type Runtime

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

Runtime holds registered edge handlers and metrics.

func New

func New(cfgs ...Config) *Runtime

New creates an edge middleware runtime.

func (*Runtime) Handle

func (rt *Runtime) Handle(path string, handler HandlerFunc) *edgeRouteBuilder

Handle registers an edge handler for a path (supports a trailing "*" wildcard).

func (*Runtime) Metrics

func (rt *Runtime) Metrics() map[string]any

Metrics returns a snapshot of runtime counters.

func (*Runtime) Middleware

func (rt *Runtime) Middleware() router.Middleware

Middleware returns the Nimbus middleware that runs matching edge handlers.

func (*Runtime) Plugin

func (rt *Runtime) Plugin() *EdgePlugin

Plugin returns the runtime as a Nimbus plugin. Register with app.Use(rt.Plugin()).

Jump to

Keyboard shortcuts

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