flow

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2026 License: Apache-2.0 Imports: 25 Imported by: 0

README

Flow

Flow is a modular HTTP engine, trie-based router, and middleware pipeline for Go.

Build Status Coverage Status Go Reference Latest Stable Version License

Requirements

  • Go 1.27 or higher

Installation

go get -u github.com/go-think/flow

Quick Start

flow can be used standalone with standard net/http servers by leveraging its Router and Pipeline:

package main

import (
	"fmt"
	"net/http"

	"github.com/go-think/flow"
)

func main() {
	// 1. Initialize router
	r := flow.New()

	// 2. Define routes
	r.Get("/", func() *flow.Response {
		return flow.Text("Hello Flow!")
	})

	r.Get("/ping", func() *flow.Response {
		return flow.Json(map[string]string{
			"message": "pong",
		})
	})

	// Route parameters & dependency injection
	r.Get("/user/{name}", func(req *flow.Request, name string) *flow.Response {
		return flow.Text(fmt.Sprintf("Hello, %s!", name))
	})

	// Compile route trees & rules
	r.Register()

	// 3. Assemble middleware pipeline
	pipeline := flow.NewPipeline()
	pipeline.Pipe(flow.NewRecoverMiddleware(true)) // Panic recovery
	pipeline.Pipe(flow.NewCorsMiddleware())        // CORS handler
	pipeline.Pipe(flow.NewRouteMiddleware(r))      // Router dispatcher

	// 4. Run HTTP server (pipeline implements http.Handler)
	fmt.Println("Server running at http://127.0.0.1:8080")
	if err := http.ListenAndServe(":8080", pipeline); err != nil {
		panic(err)
	}
}

Features


Routing Engine

The routing engine uses prefix-tree (radix tree) matching supporting dynamic parameters, constraints, and groups.

Basic Routing

Register routes by binding path patterns to handler functions:

r.Get("/hello", func() *flow.Response {
	return flow.Text("Hello World")
})

Handlers can return *flow.Response, flow.Response, string, map, struct, or any serializable type. Flow formats the payload and sets the appropriate Content-Type.

Route Verbs

Flow supports standard HTTP verbs and catch-all methods:

r.Get("/users", listUsers)
r.Post("/users", createUser)
r.Put("/users/{id}", updateUser)
r.Delete("/users/{id}", deleteUser)
r.Patch("/users/{id}", patchUser)
r.Options("/users", optionsHandler)

// Match any HTTP verb
r.Any("/any", anyHandler)

// Match custom combination of methods
r.Add([]string{"GET", "POST"}, "/multi", multiHandler)
Route Parameters & Handler Signatures

Route parameters are defined using {param} placeholders (or {param?} for optional parameters). Handlers support flexible parameter binding:

// 1. Bound directly via argument reflection
r.Get("/posts/{post}/comments/{comment}", func(post, comment string) *flow.Response {
	return flow.Json(map[string]string{
		"post_id":    post,
		"comment_id": comment,
	})
})

// 2. Bound alongside *flow.Request
r.Get("/user/{id}", func(req *flow.Request, id string) *flow.Response {
	return flow.Text(fmt.Sprintf("Request URI: %s, User ID: %s", req.Path(), id))
})

// 3. Optional route parameters (using {param?})
// When omitted from URL (e.g. GET /profile), empty string "" is automatically injected
r.Get("/profile/{tab?}", func(tab string) *flow.Response {
	if tab == "" {
		tab = "overview"
	}
	return flow.Text("Tab: " + tab)
})
Parameter Constraints (Where)

Constrain parameter formats using regex rules:

// Match only digits
r.Get("/user/{id}", getUser).WhereNumber("id")

// Match only alphabetic letters
r.Get("/user/{name}", getUser).WhereAlpha("name")

// Match against allowed enum list
r.Get("/order/{status}", getOrder).WhereIn("status", []string{"pending", "paid", "shipped"})

// Custom regular expression
r.Get("/order/{code}", getOrder).Where("code", `^[A-Z]{3}-[0-9]{4}$`)
Route Prefixes & Groups

Organize routes logically and share prefixes or middlewares:

r.Prefix("/admin").Group(func(admin flow.Router) {
	admin.Get("/dashboard", adminDashboard)

	admin.Prefix("/users").Group(func(users flow.Router) {
		users.Get("", listAdminUsers)
		users.Get("/{id}", getAdminUser)
	})
})
Named Routes & URL Generation

Assign names to routes to resolve URLs dynamically:

r.Get("/user/{id}/profile", showProfile).Name("user.profile")

// Compile routes
r.Register()

// Generate URL: "/user/42/profile"
url := r.Url("user.profile", map[string]string{"id": "42"})
Signed URLs

Generate tamper-proof URLs with cryptographic HMAC-SHA256 signatures:

// Generate signed URL valid for 30 minutes
signedUrl := r.SignedUrl("unsubscribe", 30*time.Minute, map[string]string{"user": "123"})

// Validate signature inside handler or middleware
if !r.HasValidSignature(req) {
	return flow.NewResponse().SetCode(http.StatusForbidden).SetContent("Invalid or expired signature")
}
Fallback Route

Define a catch-all handler for unmatched routes:

r.Fallback(func(req *flow.Request) *flow.Response {
	return flow.NewResponse().SetCode(http.StatusNotFound).SetContent("Page Not Found")
})

HTTP Request

Flow encapsulates incoming *http.Request inside *flow.Request with abundant helpers:

Parameter Retrieval & Type Conversion
func Handler(req *flow.Request) *flow.Response {
	// Unified parameter lookup (Query, Form, JSON Body)
	name, _ := req.Input("name")

	// Source-specific access
	pageStr, _ := req.Query("page")
	email, _   := req.Post("email")

	// Type-safe conversions with fallback defaults
	page    := req.Integer("page", 1)
	isAdmin := req.Boolean("is_admin", false)
	price   := req.Float("price", 0.0)

	// Key existence & non-empty checks
	hasName   := req.Has("name")              // True if key exists (including empty string)
	hasAny    := req.HasAny("phone", "email") // True if any of the keys exist
	isFilled  := req.Filled("name")           // True if key exists and trimmed value is non-empty
	isMissing := req.Missing("avatar")        // True if key is not present in request

	// Input whitelisting & blacklisting
	credentials := req.Only("username", "password")
	safeInputs  := req.Except("password", "token")

	// Retrieve all parsed inputs as map[string]string
	all := req.All()

	return flow.Json(all)
}
File Uploads
func UploadHandler(req *flow.Request) *flow.Response {
	file, err := req.File("avatar")
	if err != nil {
		return flow.NewResponse().SetCode(400).SetContent("No file uploaded")
	}

	// Move and persist file to disk
	ok, err := file.Move("./storage/uploads", "avatar.png")
	if err != nil || !ok {
		return flow.NewResponse().SetCode(500).SetContent("Failed to save file")
	}

	return flow.Text("Uploaded avatar.png successfully")
}
Client Inspection & Fingerprint
ip          := req.ClientIP()        // Client IP address (with X-Forwarded-For parsing)
userAgent   := req.UserAgent()       // User-Agent string
fingerprint := req.Fingerprint()     // SHA-256 fingerprint based on client traits
path        := req.Path()            // Request path
isMatch     := req.Is("admin/*")     // Wildcard path matching

HTTP Response

All response factories and builders are provided directly by flow:

Factory Helpers
// JSON response (application/json)
flow.Json(map[string]interface{}{"status": "success", "code": 200})

// Plain text response (text/plain)
flow.Text("Hello World")

// HTML response (text/html)
flow.Html("<h1>Welcome</h1>")

// HTTP Redirect (default 302 Found)
flow.Redirect("/dashboard")

// HTTP Redirect with custom status (e.g. 301 Moved Permanently)
flow.Redirect("/legacy-path", http.StatusMovedPermanently)

// 204 No Content response
flow.NoContent()

// Dynamic auto-detecting response (struct/slice/map -> JSON, other -> Text)
flow.MakeResponse(data)
Custom Status, Headers & Cookies
res := flow.NewResponse().
	SetCode(http.StatusCreated).
	SetContentType("application/json").
	SetContent(`{"created": true}`)

res.Header.Set("X-Custom-Header", "Value")
res.Cookie("session_id", "session-token-value")
Streaming & File Downloads
// File download
flow.Download("/var/data/report.pdf", "report.pdf")

// Server-Sent Events (SSE) or streaming
flow.StreamResponse(func(w io.Writer) bool {
	fmt.Fprintf(w, "data: %s\n\n", time.Now().Format(time.RFC3339))
	time.Sleep(1 * time.Second)
	return true // return false to stop streaming
})

// Stream download
flow.StreamDownload(func(w io.Writer) bool {
	w.Write([]byte("chunk-data..."))
	return false
}, "archive.zip")

Middleware & Pipeline

Flow features an onion-layered Pipeline to execute requests sequentially across middleware chains.

Writing Custom Middlewares

Implement standard middleware using flow.Handler or flow.Closure:

// 1. Using closure function
func AuthMiddleware(req *flow.Request, next flow.Closure) interface{} {
	token := req.Header("Authorization")
	if token == "" {
		return flow.NewResponse().SetCode(http.StatusUnauthorized).SetContent("Unauthorized")
	}
	return next(req)
}

// 2. Using struct implementing flow.Handler
type TimingMiddleware struct{}

func (m *TimingMiddleware) Process(req *flow.Request, next flow.Closure) interface{} {
	start := time.Now()
	res := next(req)
	duration := time.Since(start)
	if response, ok := res.(*flow.Response); ok {
		response.Header.Set("X-Response-Time", duration.String())
	}
	return res
}

Attach middleware to specific routes or groups:

r.Get("/secret", secretHandler).Middleware(AuthMiddleware)
Built-in Middlewares

Flow provides production-ready built-in middlewares:

  • flow.NewRecoverMiddleware(debug bool): Recovers from panics, generates stacktraces, and prevents process crashes.
  • flow.NewCorsMiddleware(config ...flow.CorsConfig): Handles CORS headers and preflight OPTIONS requests.
  • flow.NewCookieMiddleware(cfg ...*flow.CookieConfig): Manages cookie lifecycle, prefix, secure/httpOnly, and domain settings.
  • flow.NewTrimStringsMiddleware(except ...string): Automatically trims whitespace from incoming request inputs.
  • flow.NewValidateSignatureMiddleware(router ...*flow.Route): Verifies signed URLs.
  • flow.NewRouteMiddleware(router flow.Router): Connects the compiled router into the pipeline.
  • flow.NewSessionMiddleware(cfg *flow.Config): Manages session lifecycle automatically with specified or default (nil) configuration.
Pipeline Architecture

flow.Pipeline provides an onion architecture supporting both fluid execution and standard http.Handler integration:

  1. Fluid Pipeline:
result := flow.NewPipeline().
	Send(request).
	Through([]flow.Handler{
		flow.NewRecoverMiddleware(true),
		flow.NewCorsMiddleware(),
	}).
	Then(func(req *flow.Request) any {
		return flow.Text("Executed through pipeline")
	})
  1. HTTP Server Integration (http.Handler):
pipe := flow.NewPipeline()
pipe.Pipe(flow.NewRecoverMiddleware(true))
pipe.Pipe(flow.NewCorsMiddleware())
pipe.Pipe(flow.NewRouteMiddleware(r))

http.ListenAndServe(":8080", pipe)

HTTP Session

Flow provides a robust session system with multi-driver support:

Session Operations & Flash
func SessionDemoHandler(req *flow.Request) *flow.Response {
	session := req.Session()

	// Read & Write session data
	session.Set("user_id", 1001)
	userID := session.Get("user_id")

	// Check existence
	hasUser := session.Has("user_id")

	// Flash data (persisted for the next request only)
	session.Flash("alert", "Profile updated successfully")

	// Re-flash all or specific keys
	session.Reflash()

	// Regenerate ID (session fixation mitigation)
	session.Regenerate()

	// Invalidate & destroy session
	session.Invalidate()

	return flow.Json(map[string]interface{}{
		"user_id":  userID,
		"has_user": hasUser,
	})
}
Storage Drivers

Flow supports pluggable session storage handlers:

  • File Handler (file): Persists serialized session state to disk directory.
  • Cookie Handler (cookie): Stores session state on client cookies.
  • Custom Handlers: Implement the session.SessionHandler interface for external backends (Redis, Memcached, etc.):
    type SessionHandler interface {
        Read(id string) string
        Write(id string, data string)
    }
    

License

Flow is open-sourced software licensed under the Apache 2.0 license.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var HandleException func(err interface{}) *Response

--- Begin recover.go ---

View Source
var ResolveSignatureKey func() string

Functions

func CleanValue

func CleanValue(val interface{}) interface{}

CleanValue recursively trims strings in nested maps and slices.

func FormatContent

func FormatContent(v interface{}) string

func Method

func Method(method ...string) []string

--- Begin utils.go --- Method Convert multiple method strings to an slice

func NewStaticHandle

func NewStaticHandle(prefixAndRoot ...string) http.Handler

NewStaticHandle A Handler responds to a Static HTTP request.

func PrepareResponse

func PrepareResponse(request *Request, rule *Rule, result interface{}) interface{}

PrepareResponse Create a response instance from the given value.

func RunRoute

func RunRoute(request *Request, rule *Rule, params ...[]*parameter) interface{}

--- Begin router_router.go --- RunRoute Return the response for the given rule.

Types

type Closure

type Closure func(req *Request) any

Closure Anonymous function, Used in Middleware Handler

type Compiled

type Compiled struct {
	Regex  string
	Regexp *regexp.Regexp
}

type Config

type Config struct {
	// Default Session Driver
	Driver string

	CookieName string

	// Session Lifetime
	Lifetime time.Duration

	// Session Encryption
	Encrypt bool

	// Session File Location
	Files string
}

--- Begin manager.go ---

func DefaultSessionConfig

func DefaultSessionConfig() *Config

DefaultSessionConfig returns the default session configuration.

type Cookie struct {
	Config *CookieConfig
}

func ParseCookieHandler

func ParseCookieHandler(cfg ...*CookieConfig) *Cookie

ParseCookieHandler returns a Cookie instance with given or default configuration.

func (*Cookie) Set

func (c *Cookie) Set(name interface{}, params ...interface{}) (*http.Cookie, error)

type CookieConfig

type CookieConfig struct {
	Prefix          string
	Path            string        // optional
	Domain          string        // optional
	ExpiresDuration time.Duration // Expiration duration configuration
	RawExpires      string        // for reading cookies only

	MaxAge   int
	Secure   bool
	HttpOnly bool
	Raw      string
	Unparsed []string
}

--- Begin cookie.go ---

func DefaultCookieConfig

func DefaultCookieConfig() *CookieConfig

DefaultCookieConfig returns a new default CookieConfig.

type CookieMiddleware

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

CookieMiddleware manages Cookie configuration for incoming requests and outgoing responses.

func (*CookieMiddleware) Process

func (m *CookieMiddleware) Process(req *Request, next Closure) any

Process configures CookieHandler on request and response.

type CorsConfig

type CorsConfig struct {
	AllowOrigins     []string
	AllowMethods     []string
	AllowHeaders     []string
	ExposeHeaders    []string
	AllowCredentials bool
	MaxAge           int
}

--- Begin cors.go --- CorsConfig defines the configuration options for CORS middleware.

func DefaultCorsConfig

func DefaultCorsConfig() CorsConfig

DefaultCorsConfig returns standard default CORS configuration.

type CorsHandler deprecated

type CorsHandler = CorsMiddleware

Deprecated: Use CorsMiddleware instead.

type CorsMiddleware

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

func (*CorsMiddleware) Process

func (h *CorsMiddleware) Process(req *Request, next Closure) interface{}

type File

type File struct {
	FileHeader *multipart.FileHeader
}

--- Begin file.go ---

func (*File) Move

func (f *File) Move(directory string, name ...string) (bool, error)

type Handler

type Handler interface {
	Process(request *Request, next Closure) any
}

Handler Middleware Handler interface

func NewCookieMiddleware

func NewCookieMiddleware(cfg ...*CookieConfig) Handler

NewCookieMiddleware creates a new CookieMiddleware with the given configuration.

func NewCorsHandler deprecated

func NewCorsHandler(config ...CorsConfig) Handler

Deprecated: Use NewCorsMiddleware instead.

func NewCorsMiddleware

func NewCorsMiddleware(config ...CorsConfig) Handler

NewCorsMiddleware creates a new CORS middleware.

func NewRecoverHandler deprecated

func NewRecoverHandler(debug bool) Handler

Deprecated: Use NewRecoverMiddleware instead.

func NewRecoverMiddleware

func NewRecoverMiddleware(debug bool) Handler

NewRecoverMiddleware creates a new panic recovery middleware.

func NewRouteHandler deprecated

func NewRouteHandler(r Router) Handler

Deprecated: Use NewRouteMiddleware instead.

func NewRouteMiddleware

func NewRouteMiddleware(r Router) Handler

NewRouteMiddleware creates a new route dispatcher middleware.

func NewSessionMiddleware

func NewSessionMiddleware(cfg *Config) Handler

NewSessionMiddleware creates a new session management middleware with the specified configuration.

func NewTrimStringsHandler deprecated

func NewTrimStringsHandler(except ...string) Handler

Deprecated: Use NewTrimStringsMiddleware instead.

func NewTrimStringsMiddleware

func NewTrimStringsMiddleware(except ...string) Handler

NewTrimStringsMiddleware creates a new parameter trimming middleware.

func NewValidateSignatureHandler deprecated

func NewValidateSignatureHandler(r ...Router) Handler

Deprecated: Use NewValidateSignatureMiddleware instead.

func NewValidateSignatureMiddleware

func NewValidateSignatureMiddleware(r ...Router) Handler

NewValidateSignatureMiddleware creates a new URL signature validation middleware.

type HandlerFunc

type HandlerFunc func(request *Request, next Closure) any

HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP middleware.

func (HandlerFunc) Process

func (f HandlerFunc) Process(request *Request, next Closure) any

Process calls f(request, next).

type Manager

type Manager struct {
	Config *Config
	// contains filtered or unexported fields
}

func NewManager

func NewManager(config *Config) *Manager

func (*Manager) Extend

func (m *Manager) Extend(driver string, handler session.SessionHandler) *Manager

Extend registers a custom session driver on this Manager instance.

func (*Manager) SessionSave

func (m *Manager) SessionSave(res *Response, store *session.Store)

func (*Manager) SessionStart

func (m *Manager) SessionStart(req *Request) *session.Store

type Middleware

type Middleware func(request *Request, next Closure) any

--- Begin middleware.go --- Middleware Handle an incoming request.

type Option

type Option func(*Route)

Option defines a functional configuration option for Route.

func WithParameterResolver

func WithParameterResolver(resolver ParameterResolver) Option

WithParameterResolver configures a custom parameter resolver for route handler invocation.

func WithSignatureKey

func WithSignatureKey(key string) Option

WithSignatureKey sets the secret HMAC key for signed URLs.

type Param

type Param struct {
	Key   string
	Value string
}

Param is a single URL parameter, consisting of a key and a value.

type ParameterResolver

type ParameterResolver interface {
	ResolveParameter(paramType reflect.Type, request *Request) (reflect.Value, bool)
}

ParameterResolver defines the interface to resolve route handler parameters by type.

type ParameterResolverFunc

type ParameterResolverFunc func(paramType reflect.Type, request *Request) (reflect.Value, bool)

ParameterResolverFunc is an adapter to allow the use of ordinary functions as ParameterResolver.

func (ParameterResolverFunc) ResolveParameter

func (f ParameterResolverFunc) ResolveParameter(paramType reflect.Type, request *Request) (reflect.Value, bool)

ResolveParameter calls f(paramType, request).

type ParameterizedMiddleware

type ParameterizedMiddleware func(params ...string) Middleware

ParameterizedMiddleware Handle an incoming request with parameters.

type Params

type Params []Param

Params is a Param-slice, returned by the router.

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 Pipeline

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

func NewPipeline

func NewPipeline() *Pipeline

NewPipeline returns a new Pipeline

func (*Pipeline) Pipe

func (p *Pipeline) Pipe(m Handler) *Pipeline

Pipe Push a Middleware Handler to the pipeline

func (*Pipeline) Send

func (p *Pipeline) Send(req *Request) *Pipeline

Send sets the object being sent through the pipeline

func (*Pipeline) ServeHTTP

func (p *Pipeline) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP Implement http.Handler safely

func (*Pipeline) Then

func (p *Pipeline) Then(destination Closure) any

Then runs the pipeline with a final destination callback

func (*Pipeline) ThenReturn

func (p *Pipeline) ThenReturn() any

ThenReturn runs the pipeline and returns the result

func (*Pipeline) Through

func (p *Pipeline) Through(hls []Handler) *Pipeline

Through Batch push Middleware Handlers to the pipeline

type RecoverHandler deprecated

type RecoverHandler = RecoverMiddleware

Deprecated: Use RecoverMiddleware instead.

type RecoverMiddleware

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

func (*RecoverMiddleware) Process

func (h *RecoverMiddleware) Process(req *Request, next Closure) (result interface{})

Process Process the request to a router and return the response.

type Request

type Request struct {
	Request *http.Request

	CookieHandler *Cookie
	// contains filtered or unexported fields
}

--- Begin request.go --- Request HTTP request

func NewRequest

func NewRequest(req *http.Request) *Request

NewRequest create a new HTTP request from *http.Request

func (*Request) All

func (r *Request) All(keys ...string) map[string]string

All get all of the input and query for the request.

func (*Request) AllFiles

func (r *Request) AllFiles() (map[string]*File, error)

AllFiles returns all files from the request.

func (*Request) BearerToken

func (r *Request) BearerToken() string

BearerToken returns the Bearer token from the Authorization header.

func (*Request) Boolean

func (r *Request) Boolean(key string, defaultValue ...bool) bool

Boolean retrieves an input item as a boolean.

func (*Request) ClientIP

func (r *Request) ClientIP() string

ClientIP returns the client IP.

func (*Request) Context

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

Context returns the request's context.Context

func (*Request) Cookie

func (r *Request) Cookie(key string, value ...string) (string, error)

Cookie Retrieve a cookie from the request.

func (*Request) Except

func (r *Request) Except(keys ...string) map[string]string

Except Get all of the input except for a specified array of items.

func (*Request) Exists

func (r *Request) Exists(keys ...string) bool

Exists Determine if the request contains a given input item key (alias of Has).

func (*Request) ExpectsJson

func (r *Request) ExpectsJson() bool

ExpectsJson returns true if the request expects a JSON response.

func (*Request) File

func (r *Request) File(key string) (*File, error)

File returns a file from the request.

func (*Request) Filled

func (r *Request) Filled(keys ...string) bool

Filled Determine if the request contains a non-empty value for an input item.

func (*Request) Fingerprint

func (r *Request) Fingerprint() string

Fingerprint gets a unique fingerprint for the request.

func (*Request) Float

func (r *Request) Float(key string, defaultValue ...float64) float64

Float retrieves an input item as a float64.

func (*Request) FullUrl

func (r *Request) FullUrl() string

FullUrl get the full URL for the request.

func (*Request) FullUrlWithQuery

func (r *Request) FullUrlWithQuery(query map[string]string) string

FullUrlWithQuery appends or replaces query parameters to current full URL.

func (*Request) FullUrlWithoutQuery

func (r *Request) FullUrlWithoutQuery(keys ...string) string

FullUrlWithoutQuery removes specified query parameters from current full URL.

func (*Request) Get

func (r *Request) Get(key string) (value interface{}, exists bool)

Get returns the value for the given key

func (*Request) GetContent

func (r *Request) GetContent() ([]byte, error)

GetContent Returns the request body content.

func (*Request) GetHttpRequest

func (r *Request) GetHttpRequest() *http.Request

GetHttpRequest get Current *http.Request

func (*Request) GetMethod

func (r *Request) GetMethod() string

GetMethod get the request method.

func (*Request) GetPath

func (r *Request) GetPath() string

GetPath get the request path.

func (*Request) GetRouteParam

func (r *Request) GetRouteParam(key string, defaultValue ...string) string

GetRouteParam gets a route parameter

func (*Request) Has

func (r *Request) Has(keys ...string) bool

Has Determine if the request contains a given input item key (including empty strings).

func (*Request) HasAny

func (r *Request) HasAny(keys ...string) bool

HasAny Determine if the request contains any of the given keys.

func (*Request) HasFile

func (r *Request) HasFile(key string) bool

HasFile determines if the uploaded data contains a file.

func (*Request) Header

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

Header returns the value of the given header key.

func (*Request) Input

func (r *Request) Input(key string, value ...string) (string, error)

Input returns a input item from the request.

func (*Request) Integer

func (r *Request) Integer(key string, defaultValue ...int) int

Integer retrieves an input item as an integer.

func (*Request) Is

func (r *Request) Is(patterns ...string) bool

Is determines if the current request path matches given patterns.

func (*Request) IsAjax

func (r *Request) IsAjax() bool

IsAjax returns true if the request is an AJAX request.

func (*Request) IsMethod

func (r *Request) IsMethod(m string) bool

IsMethod checks if the request method is of specified type.

func (*Request) Merge

func (r *Request) Merge(values map[string]string) *Request

Merge merges new input into the current request's user input.

func (*Request) Method

func (r *Request) Method() string

Method get the current method for the request.

func (*Request) Missing

func (r *Request) Missing(keys ...string) bool

Missing Determine if the given input key is completely missing from the request.

func (*Request) Only

func (r *Request) Only(keys ...string) map[string]string

Only get a subset of the items from the input data.

func (*Request) Path

func (r *Request) Path() string

Path get the current path info for the request.

func (*Request) Post

func (r *Request) Post(key string, value ...string) (string, error)

Post returns a post item from the request.

func (*Request) Query

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

Query returns a query string item from the request.

func (*Request) ResponseWriter

func (r *Request) ResponseWriter() http.ResponseWriter

ResponseWriter returns the native http.ResponseWriter associated with this request.

func (*Request) RouteIs

func (r *Request) RouteIs(patterns ...string) bool

RouteIs determines if the current route name matches given patterns.

func (*Request) RouteMiddlewares

func (r *Request) RouteMiddlewares() []interface{}

RouteMiddlewares Returns the route middlewares matched for the request.

func (*Request) RouteParam

func (r *Request) RouteParam(key string, defaultValue ...string) (string, error)

RouteParam returns a route parameter with error if not present

func (*Request) Segment

func (r *Request) Segment(index int, defaultValue ...string) string

Segment gets a 1-indexed segment of the path.

func (*Request) Segments

func (r *Request) Segments() []string

Segments gets all segments of the request path.

func (*Request) Session

func (r *Request) Session() session.Session

Session get the session associated with the request.

func (*Request) Set

func (r *Request) Set(key string, value interface{})

Set store a new key/value pair in this context

func (*Request) SetCookieHandler

func (r *Request) SetCookieHandler(handler *Cookie)

SetCookieHandler sets the Cookie handler for the request.

func (*Request) SetResponseWriter

func (r *Request) SetResponseWriter(w http.ResponseWriter) *Request

SetResponseWriter sets the native http.ResponseWriter for direct writing.

func (*Request) SetRouteMiddlewares

func (r *Request) SetRouteMiddlewares(middlewares []interface{})

SetRouteMiddlewares Sets the route middlewares matched for the request.

func (*Request) SetRouteParam

func (r *Request) SetRouteParam(name, value string)

SetRouteParam sets a route parameter by name

func (*Request) SetSession

func (r *Request) SetSession(s session.Session)

Session set the session associated with the request.

func (*Request) Url

func (r *Request) Url() string

Url get the URL (no query string) for the request.

func (*Request) UserAgent

func (r *Request) UserAgent() string

UserAgent returns the client User-Agent header.

func (*Request) WantsJson

func (r *Request) WantsJson() bool

WantsJson returns true if the request asks for a JSON response.

func (*Request) WithContext

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

WithContext sets the request's context.Context

type Response

type Response struct {
	Request *Request

	CookieHandler *Cookie
	Header        *http.Header
	// contains filtered or unexported fields
}

--- Begin response.go ---

func Download

func Download(filePath string, filename ...string) *Response

Download Create a new HTTP Download Response

func DownloadResponse

func DownloadResponse(filePath string, filename ...string) *Response

DownloadResponse Create a new HTTP Download Response

func ErrorResponse

func ErrorResponse() *Response

NotFoundResponse Create a new HTTP Error Response

func FileResponse

func FileResponse(filepath string) *Response

FileResponse Create a response that serves a file

func HandledResponse

func HandledResponse() *Response

HandledResponse creates a response indicating that output was directly handled.

func Html

func Html(s string) *Response

Html Create a new HTTP Response with HTML data

func Json

func Json(v interface{}) *Response

Json Create a new HTTP Response with JSON data

func MakeResponse

func MakeResponse(v interface{}) *Response

MakeResponse Create a new HTTP Response by auto detecting content type

func NewResponse

func NewResponse() *Response

NewResponse Create a new HTTP Response

func NoContent

func NoContent(status ...int) *Response

NoContent creates a new 204 No Content Response.

func NotFoundResponse

func NotFoundResponse() *Response

NotFoundResponse Create a new HTTP NotFoundResponse

func Redirect

func Redirect(to string, status ...int) *Response

Redirect Create a new HTTP Redirect Response (default 302 Found).

func StreamDownload

func StreamDownload(streamFunc func(w io.Writer) bool, filename string) *Response

StreamDownload creates a new streaming download response.

func StreamResponse

func StreamResponse(streamFunc func(w io.Writer) bool) *Response

StreamResponse creates a new streaming HTTP Response.

func Text

func Text(s string) *Response

Text Create a new HTTP Response with TEXT data

func (*Response) Cookie

func (r *Response) Cookie(name interface{}, params ...interface{}) error

Cookie Add a cookie to the response.

func (*Response) GetCharset

func (r *Response) GetCharset() string

GetContentType get the Charset on the response.

func (*Response) GetCode

func (r *Response) GetCode() int

GetCode get the response status code.

func (*Response) GetContent

func (r *Response) GetContent() string

GetCode get the response content.

func (*Response) GetContentType

func (r *Response) GetContentType() string

GetContentType get the Content-Type on the response.

func (*Response) GetCookies

func (r *Response) GetCookies() map[string]*http.Cookie

GetCookies returns the response cookies map.

func (*Response) IsHandled

func (r *Response) IsHandled() bool

IsHandled returns whether the response was already handled directly.

func (*Response) Send

func (r *Response) Send(w http.ResponseWriter)

Send Sends HTTP headers and content.

func (*Response) SetCharset

func (r *Response) SetCharset(val string) *Response

GetContentType sets the Charset on the response.

func (*Response) SetCode

func (r *Response) SetCode(val int) *Response

SetCode sets the status code on the response.

func (*Response) SetContent

func (r *Response) SetContent(val string) *Response

SetContent sets the content on the response.

func (*Response) SetContentType

func (r *Response) SetContentType(val string) *Response

GetContentType sets the Content-Type on the response.

func (*Response) SetCookieHandler

func (r *Response) SetCookieHandler(handler *Cookie) *Response

SetCookieHandler sets the Cookie handler for the response.

func (*Response) SetFile

func (r *Response) SetFile(filepath string) *Response

SetFile set a file path to be served

func (*Response) SetRequest

func (r *Response) SetRequest(req *Request) *Response

SetRequest bind original request for file serving

func (*Response) SetStream

func (r *Response) SetStream(streamFunc func(w io.Writer) bool) *Response

SetStream sets a streaming callback for the response.

type Route

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

func New

func New(opts ...Option) *Route

New Create a new Route instance with optional configuration options.

func (*Route) Add

func (r *Route) Add(method []string, pattern string, handler interface{}) Router

Add Add a router

func (*Route) AddRule

func (r *Route) AddRule(rule *Rule) *Rule

AddRule Add a Rule to the Router.Rules and Radix Tree

func (*Route) AliasMiddleware

func (r *Route) AliasMiddleware(name string, middleware interface{}) Router

AliasMiddleware registers a route-specific middleware alias.

func (*Route) Any

func (r *Route) Any(pattern string, handler interface{}) Router

Any Register a new rule responding to all verbs.

func (*Route) CurrentRouteName

func (r *Route) CurrentRouteName(req *Request) string

CurrentRouteName returns the current route name for the request.

func (*Route) Delete

func (r *Route) Delete(pattern string, handler interface{}) Router

Delete Register a new DELETE rule with the router.

func (*Route) Dispatch

func (r *Route) Dispatch(request *Request) interface{}

Dispatch executes the request and returns the response.

func (*Route) Dump

func (r *Route) Dump() []byte

func (*Route) Fallback

func (r *Route) Fallback(handler interface{})

Fallback registers a fallback route.

func (*Route) Get

func (r *Route) Get(pattern string, handler interface{}) Router

Get Register a new GET rule with the router.

func (*Route) GetMiddlewareGroup

func (r *Route) GetMiddlewareGroup(name string) []interface{}

GetMiddlewareGroup retrieves a registered middleware group.

func (*Route) GetRouteMiddleware

func (r *Route) GetRouteMiddleware(name string) interface{}

GetRouteMiddleware retrieves a registered middleware alias.

func (*Route) Group

func (r *Route) Group(callback func(group Router))

Group Create a route group

func (*Route) Has

func (r *Route) Has(name string) bool

Has determines if the route collection contains a given named route.

func (*Route) HasValidSignature

func (r *Route) HasValidSignature(req *Request) bool

HasValidSignature checks if the given request has a valid signature.

func (*Route) Head

func (r *Route) Head(pattern string, handler interface{}) Router

Head Register a new Head rule with the router.

func (*Route) Is

func (r *Route) Is(req *Request, patterns ...string) bool

Is determines if the current route's name matches given patterns.

func (*Route) Match

func (r *Route) Match(request *Request) (*Rule, []*parameter, error)

Match Find the first rule matching a given request using Radix Tree with fallback.

func (*Route) MatchRequest

func (r *Route) MatchRequest(request *Request) (*Rule, []*parameter, error)

MatchRequest Dispatch the request to find a matching rule

func (*Route) Middleware

func (r *Route) Middleware(middlewares ...interface{}) Router

Middleware Set the middleware attached to the route.

func (*Route) MiddlewareGroup

func (r *Route) MiddlewareGroup(name string, middlewares ...interface{}) Router

MiddlewareGroup defines a named middleware group.

func (*Route) Name

func (r *Route) Name(name string) Router

Name Set the name attached to the route.

func (*Route) Options

func (r *Route) Options(pattern string, handler interface{}) Router

Options Register a new OPTIONS rule with the router.

func (*Route) Patch

func (r *Route) Patch(pattern string, handler interface{}) Router

Patch Register a new PATCH rule with the router.

func (*Route) Pattern

func (r *Route) Pattern(name string, expression string)

Pattern sets a global regex pattern for a parameter.

func (*Route) Post

func (r *Route) Post(pattern string, handler interface{}) Router

Post Register a new POST rule with the router.

func (*Route) Prefix

func (r *Route) Prefix(prefix string) Router

Prefix Add a prefix to the route URI.

func (*Route) Put

func (r *Route) Put(pattern string, handler interface{}) Router

Put Register a new PUT rule with the router.

func (*Route) Register

func (r *Route) Register()

Register Register route from the collect.

func (*Route) SignedUrl

func (r *Route) SignedUrl(name string, expiration time.Duration, params map[string]string) string

SignedUrl creates a signed URL for a named route.

func (*Route) Static

func (r *Route) Static(path, root string)

Static Register a new Static rule.

func (*Route) Statics

func (r *Route) Statics(statics map[string]string)

Statics Bulk register Static rule.

func (*Route) Url

func (r *Route) Url(name string, params map[string]string) string

Url generates a URL for a named route.

func (*Route) Where

func (r *Route) Where(name string, expression string) Router

Where adds a regex constraint to a route parameter.

func (*Route) WhereAlpha

func (r *Route) WhereAlpha(names ...string) Router

WhereAlpha adds an alphabetic regex constraint to parameters.

func (*Route) WhereIn

func (r *Route) WhereIn(name string, allowed []string) Router

WhereIn adds an allowed values constraint to a parameter.

func (*Route) WhereNumber

func (r *Route) WhereNumber(names ...string) Router

WhereNumber adds a numeric regex constraint to parameters.

type RouteHandler deprecated

type RouteHandler = RouteMiddleware

Deprecated: Use RouteMiddleware instead.

type RouteMiddleware

type RouteMiddleware struct {
	Router Router
}

--- Begin route.go ---

func (*RouteMiddleware) Process

func (h *RouteMiddleware) Process(request *Request, next Closure) interface{}

Process Process the request to a router and return the response.

type RouteRequest

type RouteRequest interface {
	GetMethod() string
	GetPath() string
}

type Router

type Router interface {
	// Add registers a new route.
	Add(method []string, pattern string, handler interface{}) Router
	// Get registers a GET route.
	Get(pattern string, handler interface{}) Router
	// Post registers a POST route.
	Post(pattern string, handler interface{}) Router
	// Put registers a PUT route.
	Put(pattern string, handler interface{}) Router
	// Patch registers a PATCH route.
	Patch(pattern string, handler interface{}) Router
	// Delete registers a DELETE route.
	Delete(pattern string, handler interface{}) Router
	// Options registers an OPTIONS route.
	Options(pattern string, handler interface{}) Router
	// Any registers a route responding to all standard verbs.
	Any(pattern string, handler interface{}) Router
	// Group creates a route group.
	Group(callback func(group Router))
	// Prefix adds a prefix to the current route group.
	Prefix(prefix string) Router
	// Middleware adds middleware to the current route or group.
	Middleware(middlewares ...interface{}) Router
	// Dispatch resolves the request to a handler and executes it.
	Dispatch(request *Request) interface{}
	// Name names the route.
	Name(name string) Router
	// Url generates a URL for a named route.
	Url(name string, params map[string]string) string
	// Fallback registers a fallback route.
	Fallback(handler interface{})
	// Where adds a regex constraint to a route parameter.
	Where(name string, expression string) Router
	// WhereNumber adds a numeric regex constraint to parameters.
	WhereNumber(names ...string) Router
	// WhereAlpha adds an alphabetic regex constraint to parameters.
	WhereAlpha(names ...string) Router
	// WhereIn adds an allowed values constraint to a parameter.
	WhereIn(name string, allowed []string) Router
	// Has determines if the route collection contains a given named route.
	Has(name string) bool
	// CurrentRouteName returns the current route name for the request.
	CurrentRouteName(req *Request) string
	// Is determines if the current route's name matches given patterns.
	Is(req *Request, patterns ...string) bool
	// Register compiles and indexes the collected route rules into the Radix Tree.
	Register()
	// Dump returns a byte slice dump of all registered route rules.
	Dump() []byte

	// SignedUrl creates a signed URL for a named route.
	SignedUrl(name string, expiration time.Duration, params map[string]string) string
	// HasValidSignature determines if the request has a valid signature.
	HasValidSignature(req *Request) bool
	// AliasMiddleware registers a route-specific middleware alias.
	AliasMiddleware(name string, middleware interface{}) Router
	// MiddlewareGroup defines a named middleware group.
	MiddlewareGroup(name string, middlewares ...interface{}) Router
	// GetRouteMiddleware retrieves a registered middleware alias.
	GetRouteMiddleware(name string) interface{}
	// GetMiddlewareGroup retrieves a registered middleware group.
	GetMiddlewareGroup(name string) []interface{}
}

--- Begin router.go --- Router defines the interface for the routing system.

type Rule

type Rule struct {
	Compiled *Compiled
	// contains filtered or unexported fields
}

--- Begin rule.go --- Rule Route rule

func (*Rule) Bind

func (r *Rule) Bind(req *Request, path string, treeParams ...[]*parameter) []*parameter

Bind Bind the router parameters to a given request and return parsed parameters.

func (*Rule) GatherRouteMiddleware

func (r *Rule) GatherRouteMiddleware() []interface{}

GatherRouteMiddleware Get all middleware, including the ones from the controller.

func (*Rule) Matches

func (r *Rule) Matches(method, path string) bool

Matches Determine if the rule matches given request.

func (*Rule) Middleware

func (r *Rule) Middleware(middlewares ...interface{}) *Rule

Middleware Set the middleware attached to the rule.

func (*Rule) Run

func (r *Rule) Run(request *Request, params ...[]*parameter) (result interface{})

Run Run the route action and return the response.

func (*Rule) ValidateParams

func (r *Rule) ValidateParams(params []*parameter) bool

ValidateParams checks if given parameters satisfy where constraints

type SessionMiddleware

type SessionMiddleware struct {
	Manager *Manager
}

--- Begin middleware_session.go ---

func (*SessionMiddleware) Process

func (h *SessionMiddleware) Process(req *Request, next Closure) interface{}

type Terminable

type Terminable interface {
	Terminate(request *Request, response any)
}

Terminable Terminable Middleware interface

type TrimStringsHandler deprecated

type TrimStringsHandler = TrimStringsMiddleware

Deprecated: Use TrimStringsMiddleware instead.

type TrimStringsMiddleware

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

--- Begin trim.go ---

func (*TrimStringsMiddleware) Process

func (h *TrimStringsMiddleware) Process(req *Request, next Closure) interface{}

type ValidateSignatureHandler deprecated

type ValidateSignatureHandler = ValidateSignatureMiddleware

Deprecated: Use ValidateSignatureMiddleware instead.

type ValidateSignatureMiddleware

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

--- Begin validate_signature.go ---

func (*ValidateSignatureMiddleware) Process

func (h *ValidateSignatureMiddleware) Process(req *Request, next Closure) interface{}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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