edge

package
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 16, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package edge provides an edge function runtime for Nimbus.

Edge functions run lightweight request handlers at the network edge, enabling ultra-low latency responses for tasks like A/B tests, geolocation routing, auth token validation, response transforms, and dynamic headers — without round-tripping to the origin server.

Usage:

edgeRT := edge.New(edge.Config{
    MaxExecTime:   50 * time.Millisecond,
    MaxMemory:     4 * 1024 * 1024, // 4MB
    AllowNetFetch: true,
})

edgeRT.Handle("/geo", func(req *edge.Request) *edge.Response {
    country := req.Header("CF-IPCountry")
    if country == "DE" {
        return edge.Redirect("/de" + req.Path, 302)
    }
    return edge.Next() // pass to origin
})

app.RegisterPlugin(edgeRT.Plugin())

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 per function invocation (default: 50ms).
	MaxExecTime time.Duration

	// MaxMemory per function in bytes (default: 4MB).
	MaxMemory int64

	// AllowNetFetch enables outbound HTTP from edge functions.
	AllowNetFetch bool

	// Logger for edge function logs.
	Logger *log.Logger

	// CacheDefault TTL for edge.Cache operations (default: 60s).
	CacheDefault time.Duration

	// Fallback when an edge function panics or times out.
	Fallback FallbackMode

	// OnError callback for edge function errors.
	OnError func(path string, err error)

	// Prefix for edge routes (default: "").
	Prefix string
}

Config for the edge function runtime.

type EdgePlugin

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

EdgePlugin wraps the runtime as a Nimbus plugin.

func (*EdgePlugin) Boot

func (ep *EdgePlugin) Boot(app interface{}) error

func (*EdgePlugin) Middleware

func (ep *EdgePlugin) Middleware() []router.Middleware

Middleware returns the edge middleware for use as HasMiddleware plugin.

func (*EdgePlugin) Name

func (ep *EdgePlugin) Name() string

func (*EdgePlugin) Register

func (ep *EdgePlugin) Register(app interface{}) error

func (*EdgePlugin) RegisterRoutes

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

RegisterRoutes adds the edge metrics endpoint.

func (*EdgePlugin) Version

func (ep *EdgePlugin) Version() string

type FallbackMode

type FallbackMode int

FallbackMode determines behavior on edge function failure.

const (
	// FallbackNext passes the request to the origin server.
	FallbackNext FallbackMode = iota
	// FallbackError returns a 502 Bad Gateway.
	FallbackError
	// FallbackCached returns the last cached response if available.
	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 about the request.

type HandlerFunc

type HandlerFunc func(req *Request) *Response

HandlerFunc is the signature for edge functions.

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 representation of an HTTP request for edge functions.

func (*Request) Context

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

Context returns the request context.

func (*Request) Header

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

Header returns a request header value.

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 the edge function 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 signals that the request should pass through to the origin server.

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 response with the given status and body.

func Rewrite

func Rewrite(url string) *Response

Rewrite rewrites the request URL without a redirect.

func (*Response) IsNext

func (r *Response) IsNext() bool

IsNext returns true if the request should be passed to the origin.

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 is the edge function runtime.

func New

func New(cfgs ...Config) *Runtime

New creates a new edge function runtime.

func (*Runtime) Handle

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

Handle registers an edge function for a path.

func (*Runtime) Metrics

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

Metrics returns runtime metrics.

func (*Runtime) Middleware

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

Middleware returns a Nimbus middleware that runs edge functions.

func (*Runtime) Plugin

func (rt *Runtime) Plugin() *EdgePlugin

Plugin returns the edge runtime as a Nimbus plugin.

Jump to

Keyboard shortcuts

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