internal

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2025 License: MIT Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// SpanContextKey is used to store spans in request context
	SpanContextKey contextKey = "_span"

	// ParamsContextKey is used to store route parameters in context
	ParamsContextKey contextKey = "params"
)

Context keys used throughout the application

View Source
const (
	DefaultHTTPPort   = "80"
	HeaderXHTTPMethod = "X-Http-Method"

	StatusNoContent = 204
	StatusNotFound  = 404

	LoggerPrefix = "[host-http] "
)

Variables

View Source
var (
	GlobalTracerManager *TracerManager = NewTraceManager()

	NetHTTPHostModuleInstance = NetHTTPHostModule{}

	NetHTTPHostLogger *slog.Logger = slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
		Level: slog.LevelInfo,
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey {
				a.Value = slog.StringValue(a.Value.Time().Format("2006/01/02 15:04:05"))
			}
			return a
		},
	})).With("component", "host-http")
)
View Source
var BytesBufferPool = sync.Pool{
	New: func() any {
		return bytes.NewBuffer(make([]byte, 0, 1024))
	},
}

BytesBufferPool manages reusable byte buffers for response writing

View Source
var DefaultCORSConfig = CORSConfig{
	AllowOrigin:      "*",
	AllowCredentials: false,
	AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH", "HEAD"},
	AllowHeaders: []string{
		"Accept", "Content-Type", "Content-Length", "Accept-Encoding",
		"Authorization", "X-Requested-With", "Origin", "Cache-Control",

		"X-Token", "X-Token-Status", "X-Token-Expires-In", "X-Debug-Seed",
		"X-Http-Method", "X-Http-Method-Override",
	},
	ExposeHeaders: []string{
		"X-Token", "X-Token-Status", "X-Token-Expires-In", "X-Debug-Seed",
	},
	MaxAge: 86400,
}

DefaultCORSConfig provides sensible CORS defaults based on bpcslothub usage

View Source
var JSON = jsonAPI{
	// contains filtered or unexported fields
}

JSON provides a high-performance JSON encoder/decoder Currently using standard library, will be replaced with jsoniter

View Source
var RequestContextPool = sync.Pool{
	New: func() any {
		return &RequestContext{

			paramNames:  make([]string, 0, 8),
			paramValues: make([]string, 0, 8),
			maxParams:   8,

			Params:      make(map[string]string, 8),
			Headers:     make(map[string]string, 16),
			QueryCache:  make(map[string]string, 8),
			FormCache:   make(map[string]string, 8),
			CookieCache: make(map[string]*http.Cookie, 4),
		}
	},
}

RequestContextPool manages reusable request contexts

View Source
var ResponseWriterPool = sync.Pool{
	New: func() any {
		return &PooledResponseWriter{}
	},
}

ResponseWriterPool manages enhanced response writers with buffering

View Source
var StringSlicePool = sync.Pool{
	New: func() any {
		return make([]string, 0, 8)
	},
}

StringSlicePool manages reusable string slices for parameter parsing

Functions

func AcquireBuffer

func AcquireBuffer() *bytes.Buffer

AcquireBuffer gets a buffer from the pool

func AcquireStringSlice

func AcquireStringSlice() []string

AcquireStringSlice gets a string slice from the pool

func NewBindingError

func NewBindingError(sourceParam string, values []string, message any, internalError error) error

NewBindingError creates new instance of binding error

func ReleaseBuffer

func ReleaseBuffer(buf *bytes.Buffer)

ReleaseBuffer returns a buffer to the pool

func ReleaseRequestContext

func ReleaseRequestContext(ctx *RequestContext)

ReleaseRequestContext returns a request context to the pool

func ReleaseResponseWriter

func ReleaseResponseWriter(w *PooledResponseWriter)

ReleaseResponseWriter returns a response writer to the pool

func ReleaseStringSlice

func ReleaseStringSlice(slice []string)

ReleaseStringSlice returns a string slice to the pool

func SetParams

func SetParams(r *http.Request, params Params) *http.Request

SetParams sets parameters in request context

Types

type BindingError

type BindingError struct {
	Internal error    `json:"-"`
	Field    string   `json:"field"`
	Message  string   `json:"message"`
	Values   []string `json:"-"`
	Code     int      `json:"-"`
}

BindingError represents an error that occurred while binding request data

func (*BindingError) Error

func (be *BindingError) Error() string

Error returns error message

type CORSConfig

type CORSConfig struct {
	AllowOrigin      string
	AllowMethods     []string
	AllowHeaders     []string
	ExposeHeaders    []string
	MaxAge           int
	AllowCredentials bool
}

CORSConfig holds CORS configuration - learning from bpcslothub

type Default404Handler

type Default404Handler struct {
	JSONError any
	// contains filtered or unexported fields
}

Default404Handler provides a smart 404 handler that returns JSON or HTML based on request

func NewDefault404Handler

func NewDefault404Handler() *Default404Handler

NewDefault404Handler creates a new 404 handler with sensible defaults

func (*Default404Handler) AsRequestHandler

func (h *Default404Handler) AsRequestHandler() RequestHandler

AsRequestHandler returns a RequestHandler function

func (*Default404Handler) ServeHTTP

func (h *Default404Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles 404 responses with content type detection

type ErrorHandler

type ErrorHandler func(w http.ResponseWriter, r *http.Request, err any)

Handler function types.

type MapRouter

type MapRouter map[RoutePath]RouteComponent

MapRouter is a simple HTTP router backed by a map (legacy implementation)

func (MapRouter) Add

func (r MapRouter) Add(method, path string, handler RequestHandler, handlerComponentID string)

Add adds a route

func (MapRouter) FindHandlerComponentID

func (r MapRouter) FindHandlerComponentID(method, path string) string

FindHandlerComponentID returns the handler component ID

func (MapRouter) Get

func (r MapRouter) Get(method, path string) RequestHandler

Get returns the handler

func (MapRouter) Has

func (r MapRouter) Has(path RoutePath) bool

Has reports whether the route exists

func (MapRouter) Lookup

func (r MapRouter) Lookup(method, path string) RequestHandler

Lookup is an alias of Get (keeps fasthttp parity).

func (MapRouter) Remove

func (r MapRouter) Remove(method, path string)

Remove removes a route

type Middleware

type Middleware interface {
	Invoke(w http.ResponseWriter, r *http.Request, next RequestHandler)
}

Middleware provides a simplified middleware interface with single Invoke method like host-fasthttp

type NetHTTPHost

type NetHTTPHost struct {
	Listener net.Listener

	Server *http.Server

	Version       string
	ListenAddress string

	EnableCompress bool
	// contains filtered or unexported fields
}

NetHTTPHost is a Host implementation based on the standard library net/http.

func AsNetHTTPHost

func AsNetHTTPHost(h host.Host) *NetHTTPHost

AsNetHTTPHost converts host.Host to NetHTTPHost.

func (*NetHTTPHost) GetHostRegistrar

func (h *NetHTTPHost) GetHostRegistrar() *NetHTTPHostRegistrar

GetHostRegistrar returns the host registrar for route registration.

func (*NetHTTPHost) GetRequestWorker

func (h *NetHTTPHost) GetRequestWorker() *RequestWorker

GetRequestWorker returns the request worker instance for advanced middleware configuration. This method provides access to pre-middleware and regular middleware configuration.

func (*NetHTTPHost) Logger

func (h *NetHTTPHost) Logger() *log.Logger

Logger returns the logger.

func (*NetHTTPHost) SetCorsEnabled

func (h *NetHTTPHost) SetCorsEnabled(enabled bool)

SetCorsEnabled sets whether CORS is enabled.

func (*NetHTTPHost) SetCustomCorsHeaders

func (h *NetHTTPHost) SetCustomCorsHeaders(headers []string)

SetCustomCorsHeaders sets custom CORS headers.

func (*NetHTTPHost) SetEnableCompress

func (h *NetHTTPHost) SetEnableCompress(enable bool)

SetEnableCompress sets compression.

func (*NetHTTPHost) SetErrorHandler

func (h *NetHTTPHost) SetErrorHandler(handler ErrorHandler)

SetErrorHandler sets the error handler.

func (*NetHTTPHost) SetListenAddress

func (h *NetHTTPHost) SetListenAddress(addr string)

SetListenAddress sets the listen address.

func (*NetHTTPHost) SetLogger

func (h *NetHTTPHost) SetLogger(logger *log.Logger)

SetLogger sets the logger.

func (*NetHTTPHost) SetOnErrorEventHandler

func (h *NetHTTPHost) SetOnErrorEventHandler(handler host.HostOnErrorEventHandler)

SetOnErrorEventHandler sets the error event handler.

func (*NetHTTPHost) SetVersion

func (h *NetHTTPHost) SetVersion(version string)

SetVersion sets the version.

func (*NetHTTPHost) Start

func (h *NetHTTPHost) Start(ctx context.Context)

Start starts the HTTP server.

func (*NetHTTPHost) Stop

func (h *NetHTTPHost) Stop(ctx context.Context) error

Stop stops the HTTP server.

type NetHTTPHostModule

type NetHTTPHostModule struct{}

func (NetHTTPHostModule) ConfigureLogger

func (NetHTTPHostModule) ConfigureLogger(logflags int, w io.Writer)

ConfigureLogger implements host.HostModule.

func (NetHTTPHostModule) DescribeHostType

func (NetHTTPHostModule) DescribeHostType() reflect.Type

DescribeHostType implements host.HostModule.

func (NetHTTPHostModule) Init

func (NetHTTPHostModule) Init(h host.Host, app *host.AppModule)

Init implements host.HostModule.

func (NetHTTPHostModule) InitComplete

func (NetHTTPHostModule) InitComplete(h host.Host, app *host.AppModule)

InitComplete implements host.HostModule.

type NetHTTPHostRegistrar

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

NetHTTPHostRegistrar registers routes

func NewNetHTTPHostRegistrar

func NewNetHTTPHostRegistrar(router Router) *NetHTTPHostRegistrar

NewNetHTTPHostRegistrar creates a registrar

func (*NetHTTPHostRegistrar) AddRoute

func (r *NetHTTPHostRegistrar) AddRoute(method, path string, handler RequestHandler, componentID string)

AddRoute adds a route

func (*NetHTTPHostRegistrar) RemoveRoute

func (r *NetHTTPHostRegistrar) RemoveRoute(method, path string)

RemoveRoute removes a route

func (*NetHTTPHostRegistrar) SetCorsHeader

func (r *NetHTTPHostRegistrar) SetCorsHeader(enabled bool)

SetCorsHeader toggles CORS.

func (*NetHTTPHostRegistrar) SetCorsHeaders

func (r *NetHTTPHostRegistrar) SetCorsHeaders(headers []string)

SetCorsHeaders sets custom CORS headers

func (*NetHTTPHostRegistrar) SetRequestManager

func (r *NetHTTPHostRegistrar) SetRequestManager(manager any)

SetRequestManager sets the RequestManager and registers routes

type NotFoundTemplateData

type NotFoundTemplateData struct {
	StatusCode      string
	Title           string
	Message         string
	Method          string
	Path            string
	JSONMessage     string
	ShowJSONExample bool
}

NotFoundTemplateData holds data for the 404 HTML template

type OnHostErrorHandler

type OnHostErrorHandler func(err error) (disposed bool)

Handler function types.

type Params

type Params map[string]string

Params holds URL parameter values

func ExtractParams

func ExtractParams(r *http.Request) Params

ExtractParams extracts parameters from request

type PooledResponseWriter

type PooledResponseWriter struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

PooledResponseWriter wraps http.ResponseWriter with buffering capabilities Enhanced with Echo-inspired Before/After hooks

func AcquireResponseWriter

func AcquireResponseWriter() *PooledResponseWriter

AcquireResponseWriter gets a response writer from the pool

func (*PooledResponseWriter) After

func (w *PooledResponseWriter) After(fn func())

After registers a function which is called just after the response is written

func (*PooledResponseWriter) Before

func (w *PooledResponseWriter) Before(fn func())

Before registers a function which is called just before the response is written

func (*PooledResponseWriter) Committed

func (w *PooledResponseWriter) Committed() bool

Committed returns whether the response has been committed

func (*PooledResponseWriter) EnableBuffering

func (w *PooledResponseWriter) EnableBuffering()

EnableBuffering enables response buffering for optimization

func (*PooledResponseWriter) Flush

func (w *PooledResponseWriter) Flush() error

Flush writes buffered content to the underlying writer

func (*PooledResponseWriter) Reset

func (w *PooledResponseWriter) Reset(writer http.ResponseWriter)

Reset clears the response writer for reuse

func (*PooledResponseWriter) Size

func (w *PooledResponseWriter) Size() int64

Size returns the number of bytes written

func (*PooledResponseWriter) Status

func (w *PooledResponseWriter) Status() int

Status returns the HTTP status code

func (*PooledResponseWriter) Unwrap

Unwrap returns the original http.ResponseWriter (for Go 1.20+ ResponseController)

func (*PooledResponseWriter) Write

func (w *PooledResponseWriter) Write(data []byte) (int, error)

Write implements http.ResponseWriter with hook support

func (*PooledResponseWriter) WriteHeader

func (w *PooledResponseWriter) WriteHeader(statusCode int)

WriteHeader implements http.ResponseWriter with Echo-inspired hook support

type PostArgs

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

PostArgs wraps POST form parameters.

func (*PostArgs) Peek

func (p *PostArgs) Peek(key string) []byte

Peek returns the first POST form value for the given key as bytes. Returns nil if the key is not found or empty.

type QueryArgs

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

QueryArgs wraps query parameters.

func (*QueryArgs) GetUint

func (q *QueryArgs) GetUint(key string) (uint, error)

GetUint parses the value for the given key as unsigned integer. Returns 0 if key is not found, or parsing error if value is invalid.

func (*QueryArgs) Peek

func (q *QueryArgs) Peek(key string) []byte

Peek returns the first value for the given key as bytes. Returns nil if the key is not found or empty.

func (*QueryArgs) String

func (q *QueryArgs) String() string

String returns the encoded query string.

type RadixRouter

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

RadixRouter implements a high-performance router with parameter support Supports patterns like: - /api/v1/:groupId/action - /api/v1/*/summary - /api/v1/:groupId/sessions/:sessionId

func NewRadixRouter

func NewRadixRouter() *RadixRouter

NewRadixRouter creates a new radix tree router

func (*RadixRouter) Add

func (r *RadixRouter) Add(method, pattern string, handler RequestHandler, componentID string)

Add adds a route with parameter support

func (*RadixRouter) FindHandlerComponentID

func (r *RadixRouter) FindHandlerComponentID(method, path string) string

FindHandlerComponentID returns the component ID for a route

func (*RadixRouter) Get

func (r *RadixRouter) Get(method, path string) RequestHandler

Get returns handler by method and path (legacy compatibility)

func (*RadixRouter) Has

func (r *RadixRouter) Has(routePath RoutePath) bool

Has checks if a route exists

func (*RadixRouter) Lookup

func (r *RadixRouter) Lookup(method, path string) RequestHandler

Lookup returns handler by method and path (Router interface compatibility)

func (*RadixRouter) LookupWithParams

func (r *RadixRouter) LookupWithParams(method, path string) (RequestHandler, Params)

LookupWithParams finds a handler and extracts parameters

func (*RadixRouter) Remove

func (r *RadixRouter) Remove(method, path string)

Remove removes a route

type Recover

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

Recover captures panic values.

func NewRecover

func NewRecover() *Recover

NewRecover creates a new Recover.

func (*Recover) Get

func (r *Recover) Get() any

Get returns the recovered value.

func (*Recover) Set

func (r *Recover) Set(value any)

Set sets the recovered value.

type Request

type Request = http.Request

Standard library type aliases.

type RequestContext

type RequestContext struct {
	Writer    http.ResponseWriter
	FormCache map[string]string

	Params      map[string]string
	Headers     map[string]string
	QueryCache  map[string]string
	Request     *http.Request
	CookieCache map[string]*http.Cookie
	Handlers    []RequestHandler

	Index   int8
	Aborted bool
	// contains filtered or unexported fields
}

RequestContext represents an enhanced request context with caching Inspired by Echo framework's parameter optimization

func AcquireRequestContext

func AcquireRequestContext() *RequestContext

AcquireRequestContext gets a request context from the pool

func (*RequestContext) GetCookie

func (ctx *RequestContext) GetCookie(name string) (*http.Cookie, error)

GetCookie retrieves a cookie with caching

func (*RequestContext) GetForm

func (ctx *RequestContext) GetForm(key string) string

GetForm retrieves a form parameter with caching

func (*RequestContext) GetHeader

func (ctx *RequestContext) GetHeader(key string) string

GetHeader retrieves a header with caching

func (*RequestContext) GetParam

func (ctx *RequestContext) GetParam(key string) string

GetParam retrieves a URL parameter with caching First tries optimized slice access, then falls back to map

func (*RequestContext) GetQuery

func (ctx *RequestContext) GetQuery(key string) string

GetQuery retrieves a query parameter with caching

func (*RequestContext) ParamNames

func (ctx *RequestContext) ParamNames() []string

ParamNames returns all parameter names (Echo compatibility)

func (*RequestContext) ParamValues

func (ctx *RequestContext) ParamValues() []string

ParamValues returns all parameter values (Echo compatibility)

func (*RequestContext) Reset

func (ctx *RequestContext) Reset()

Reset clears the context for reuse

func (*RequestContext) SetParam

func (ctx *RequestContext) SetParam(key, value string)

SetParam sets a URL parameter in the cache

func (*RequestContext) SetParamSlice

func (ctx *RequestContext) SetParamSlice(names, values []string)

SetParamSlice sets parameters using Echo-style optimized slices

type RequestContextResponseHelpers

type RequestContextResponseHelpers struct {
	*RequestContext
}

RequestContextResponseHelpers extends RequestContext with response helper methods

func NewResponseHelpers

func NewResponseHelpers(ctx *RequestContext) *RequestContextResponseHelpers

NewResponseHelpers creates response helpers wrapper

func ResponseHelpers

func ResponseHelpers(ctx *RequestContext) *RequestContextResponseHelpers

ResponseHelpers creates response helpers from RequestContext for backward compatibility

func (*RequestContextResponseHelpers) Attachment

func (h *RequestContextResponseHelpers) Attachment(filePath, fileName string) error

Attachment sends file as attachment

func (*RequestContextResponseHelpers) Binary

func (h *RequestContextResponseHelpers) Binary(code int, contentType string, data []byte) error

Binary sends binary data response

func (*RequestContextResponseHelpers) File

func (h *RequestContextResponseHelpers) File(filePath string) error

File sends file as response

func (*RequestContextResponseHelpers) HTML

func (h *RequestContextResponseHelpers) HTML(code int, html string) error

HTML sends an HTML response with status code

func (*RequestContextResponseHelpers) HTMLBlob

func (h *RequestContextResponseHelpers) HTMLBlob(code int, b []byte) error

HTMLBlob sends an HTML blob response with status code

func (*RequestContextResponseHelpers) Inline

func (h *RequestContextResponseHelpers) Inline(filePath, fileName string) error

Inline sends file inline

func (*RequestContextResponseHelpers) JSON

func (h *RequestContextResponseHelpers) JSON(code int, i any) error

JSON sends a JSON response with status code

func (*RequestContextResponseHelpers) JSONBlob

func (h *RequestContextResponseHelpers) JSONBlob(code int, b []byte) error

JSONBlob sends a JSON blob response with status code

func (*RequestContextResponseHelpers) JSONError

func (h *RequestContextResponseHelpers) JSONError(code int, message string) error

JSONError sends error JSON response

func (*RequestContextResponseHelpers) JSONErrorWithDetails

func (h *RequestContextResponseHelpers) JSONErrorWithDetails(code int, message string, details any) error

JSONErrorWithDetails sends detailed error JSON response

func (*RequestContextResponseHelpers) JSONP

func (h *RequestContextResponseHelpers) JSONP(code int, callback string, i any) error

JSONP sends a JSONP response with status code

func (*RequestContextResponseHelpers) JSONPBlob

func (h *RequestContextResponseHelpers) JSONPBlob(code int, callback string, b []byte) error

JSONPBlob sends a JSONP blob response with status code

func (*RequestContextResponseHelpers) JSONPretty

func (h *RequestContextResponseHelpers) JSONPretty(code int, i any, indent string) error

JSONPretty sends a pretty-formatted JSON response with status code

func (*RequestContextResponseHelpers) JSONSuccess

func (h *RequestContextResponseHelpers) JSONSuccess(data any) error

JSONSuccess sends successful JSON response

func (*RequestContextResponseHelpers) JSONWithOptions

func (h *RequestContextResponseHelpers) JSONWithOptions(code int, i any, indent string) error

JSONWithOptions sends JSON response with formatting options

func (*RequestContextResponseHelpers) NoContent

func (h *RequestContextResponseHelpers) NoContent(code int) error

NoContent sends a response with no body and status code 204

func (*RequestContextResponseHelpers) Redirect

func (h *RequestContextResponseHelpers) Redirect(code int, url string) error

Redirect sends a redirect response

func (*RequestContextResponseHelpers) SetCookie

func (h *RequestContextResponseHelpers) SetCookie(cookie *http.Cookie)

SetCookie sets response cookie

func (*RequestContextResponseHelpers) SetHeader

func (h *RequestContextResponseHelpers) SetHeader(key, value string)

SetHeader sets response header

func (*RequestContextResponseHelpers) Stream

func (h *RequestContextResponseHelpers) Stream(code int, contentType string, r func(http.ResponseWriter) error) error

Stream sends streaming response

func (*RequestContextResponseHelpers) String

func (h *RequestContextResponseHelpers) String(code int, s string) error

String sends a string response with status code

func (*RequestContextResponseHelpers) StringBlob

func (h *RequestContextResponseHelpers) StringBlob(code int, b []byte) error

StringBlob sends a string blob response with status code

func (*RequestContextResponseHelpers) XML

func (h *RequestContextResponseHelpers) XML(code int, i any) error

XML sends an XML response with status code

func (*RequestContextResponseHelpers) XMLBlob

func (h *RequestContextResponseHelpers) XMLBlob(code int, b []byte) error

XMLBlob sends an XML blob response with status code

func (*RequestContextResponseHelpers) XMLPretty

func (h *RequestContextResponseHelpers) XMLPretty(code int, i any, indent string) error

XMLPretty sends a pretty-formatted XML response with status code

func (*RequestContextResponseHelpers) XMLWithOptions

func (h *RequestContextResponseHelpers) XMLWithOptions(code int, i any, indent string) error

XMLWithOptions sends XML response with formatting options

type RequestCtx

type RequestCtx = *http.Request

Standard library type aliases.

type RequestHandleModule

type RequestHandleModule interface {
	CanSetSuccessor() bool
	SetSuccessor(successor RequestHandleModule)
	ProcessRequest(w http.ResponseWriter, r *http.Request, state RequestState, recover *Recover)
	OnInitComplete()
	OnStart(ctx context.Context) error
	OnStop(ctx context.Context) error
}

RequestHandleModule provides a legacy interface for backward compatibility during transition

type RequestHandleService

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

RequestHandleService orchestrates request handlers.

func NewRequestHandleService

func NewRequestHandleService() *RequestHandleService

NewRequestHandleService creates the service.

func (*RequestHandleService) AddModule

func (s *RequestHandleService) AddModule(module RequestHandleModule)

AddModule adds a processing module.

func (*RequestHandleService) OnInitComplete

func (s *RequestHandleService) OnInitComplete()

OnInitComplete runs after initialization.

func (*RequestHandleService) OnStart

func (s *RequestHandleService) OnStart(ctx context.Context) error

OnStart starts modules.

func (*RequestHandleService) OnStop

func (s *RequestHandleService) OnStop(ctx context.Context) error

OnStop stops modules.

func (*RequestHandleService) ProcessRequest

func (s *RequestHandleService) ProcessRequest(
	w http.ResponseWriter,
	r *http.Request,
	state RequestState,
	recover *Recover,
)

ProcessRequest processes a request.

type RequestHandler

type RequestHandler = func(http.ResponseWriter, *http.Request)

Standard library type aliases.

type RequestState

type RequestState int

RequestState represents the request processing stage.

const (
	RequestStateBegin RequestState = iota
	RequestStateProcessing
	RequestStateEnd
)

type RequestTracerService

type RequestTracerService struct {
	TracerManager *TracerManager
}

RequestTracerService provides comprehensive tracing with Bofry/trace v0.3.1

func NewRequestTracerService

func NewRequestTracerService(tracerManager *TracerManager) *RequestTracerService

NewRequestTracerService creates the service

func (*RequestTracerService) AddSpanAttributes

func (s *RequestTracerService) AddSpanAttributes(span *trace.SeveritySpan, attributes map[string]any)

AddSpanAttributes adds custom attributes to the span using severity tags

func (*RequestTracerService) FinishSpan

func (s *RequestTracerService) FinishSpan(span *trace.SeveritySpan, statusCode int, err error)

FinishSpan ends the span with comprehensive status and timing information

func (*RequestTracerService) StartSpan

func (s *RequestTracerService) StartSpan(
	r *http.Request,
	w http.ResponseWriter,
	operationName string,
) *trace.SeveritySpan

StartSpan starts a comprehensive tracing span using SeveritySpan with trace v0.3.1 best practices. It follows the Extract -> Start -> Open pattern for proper trace propagation.

type RequestWorker

type RequestWorker struct {
	Router                  Router
	UnhandledRequestHandler RequestHandler
	RequestTracerService    *RequestTracerService
	RouteResolveService     *RouteResolveService
	OnHostErrorProc         OnHostErrorHandler
	ErrorHandler            ErrorHandler
	RequestHandleService    *RequestHandleService
	RewriteHandler          RewriteHandler
	CORSConfig              *CORSConfig
	CustomCorsHeaders       []string
	PreMiddlewares          []Middleware
	Middlewares             []Middleware
	EnableCorsHeader        bool
}

RequestWorker handles HTTP requests using standard library interfaces

func GetGlobalRequestWorker

func GetGlobalRequestWorker() *RequestWorker

GetGlobalRequestWorker returns the globally registered RequestWorker instance

func (*RequestWorker) AddMiddleware

func (w *RequestWorker) AddMiddleware(middleware Middleware)

AddMiddleware adds a regular middleware (executed after routing)

func (*RequestWorker) AddPreMiddleware

func (w *RequestWorker) AddPreMiddleware(middleware Middleware)

AddPreMiddleware adds a pre-middleware (executed before routing)

func (*RequestWorker) GetCORSConfig

func (w *RequestWorker) GetCORSConfig() *CORSConfig

GetCORSConfig returns current CORS configuration

func (*RequestWorker) ServeHTTP

func (w *RequestWorker) ServeHTTP(wr http.ResponseWriter, r *http.Request)

ServeHTTP handles HTTP requests - main processing entry point Optimized with object pooling for better performance

func (*RequestWorker) SetCORSConfig

func (w *RequestWorker) SetCORSConfig(config *CORSConfig)

SetCORSConfig sets custom CORS configuration

type ResponseWriter

type ResponseWriter = http.ResponseWriter

Standard library type aliases.

type RewriteHandler

type RewriteHandler func(r *http.Request, path *RoutePath) *RoutePath

Handler function types.

type RouteComponent

type RouteComponent struct {
	RequestHandler     RequestHandler
	HandlerComponentID string
}

RouteComponent holds the request handler and component ID.

type RoutePath

type RoutePath struct {
	Method string
	Path   string
}

RoutePath represents an HTTP method and path.

func (RoutePath) Equal

func (r RoutePath) Equal(other RoutePath) bool

Equal reports whether two paths are equal.

func (RoutePath) String

func (r RoutePath) String() string

String returns the string form.

type RouteResolveModule

type RouteResolveModule interface {
	RouteResolver

	CanSetSuccessor() bool
	SetSuccessor(successor RouteResolver)
}

Routing interfaces.

type RouteResolveService

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

RouteResolveService resolves the HTTP method and path.

func NewRouteResolveService

func NewRouteResolveService() *RouteResolveService

NewRouteResolveService creates a resolver service.

func (*RouteResolveService) AddModule

func (s *RouteResolveService) AddModule(module RouteResolveModule)

AddModule adds a resolver module.

func (*RouteResolveService) ResolveHTTPMethod

func (s *RouteResolveService) ResolveHTTPMethod(r *http.Request) string

ResolveHTTPMethod resolves the HTTP method.

func (*RouteResolveService) ResolveHTTPPath

func (s *RouteResolveService) ResolveHTTPPath(r *http.Request) string

ResolveHTTPPath resolves the HTTP path.

type RouteResolver

type RouteResolver interface {
	ResolveHTTPMethod(r *http.Request) string
	ResolveHTTPPath(r *http.Request) string
}

Routing interfaces.

type Router

type Router interface {
	Add(method, path string, handler RequestHandler, handlerComponentID string)
	Remove(method, path string)
	Get(method, path string) RequestHandler
	Lookup(method, path string) RequestHandler
	Has(path RoutePath) bool
	FindHandlerComponentID(method, path string) string
}

Router interface for HTTP routing with parameter support

func NewMapRouter

func NewMapRouter() Router

NewMapRouter creates a simple map-based router (for backward compatibility)

func NewRouter

func NewRouter() Router

NewRouter creates a new high-performance router with parameter support

type Server

type Server = http.Server

Standard library type aliases.

type StdRequestHandleModule

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

StdRequestHandleModule is the default request handler module

func NewStdRequestHandleModule

func NewStdRequestHandleModule(worker *RequestWorker) *StdRequestHandleModule

NewStdRequestHandleModule creates a new standard request handle module

func (*StdRequestHandleModule) CanSetSuccessor

func (m *StdRequestHandleModule) CanSetSuccessor() bool

CanSetSuccessor implements RequestHandleModule

func (*StdRequestHandleModule) OnInitComplete

func (m *StdRequestHandleModule) OnInitComplete()

OnInitComplete implements RequestHandleModule

func (*StdRequestHandleModule) OnStart

func (m *StdRequestHandleModule) OnStart(ctx context.Context) error

OnStart implements RequestHandleModule

func (*StdRequestHandleModule) OnStop

OnStop implements RequestHandleModule

func (*StdRequestHandleModule) ProcessRequest

func (m *StdRequestHandleModule) ProcessRequest(
	w http.ResponseWriter, r *http.Request, state RequestState, recover *Recover,
)

ProcessRequest implements RequestHandleModule

func (*StdRequestHandleModule) SetSuccessor

func (m *StdRequestHandleModule) SetSuccessor(successor RequestHandleModule)

SetSuccessor implements RequestHandleModule

type StdRouteResolveModule

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

StdRouteResolveModule is the default resolver.

func (*StdRouteResolveModule) CanSetSuccessor

func (m *StdRouteResolveModule) CanSetSuccessor() bool

CanSetSuccessor reports support for a successor.

func (*StdRouteResolveModule) ResolveHTTPMethod

func (m *StdRouteResolveModule) ResolveHTTPMethod(r *http.Request) string

ResolveHTTPMethod supports the X-Http-Method override.

func (*StdRouteResolveModule) ResolveHTTPPath

func (m *StdRouteResolveModule) ResolveHTTPPath(r *http.Request) string

ResolveHTTPPath resolves the HTTP path.

func (*StdRouteResolveModule) SetSuccessor

func (m *StdRouteResolveModule) SetSuccessor(successor RouteResolver)

SetSuccessor sets the successor.

type TracerManager

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

TracerManager coordinates tracing with Bofry/trace v0.3.0 integration

func NewTraceManager

func NewTraceManager() *TracerManager

NewTraceManager creates a tracer manager with default configuration

func (*TracerManager) GetPropagator

func (tm *TracerManager) GetPropagator() propagation.TextMapPropagator

GetPropagator returns the text map propagator

func (*TracerManager) GetSeverityTracer

func (tm *TracerManager) GetSeverityTracer() *trace.SeverityTracer

GetSeverityTracer returns the Bofry/trace SeverityTracer

func (*TracerManager) Initialize

func (tm *TracerManager) Initialize(ctx context.Context) error

Initialize sets up tracing with Bofry/trace v0.3.0

func (*TracerManager) IsEnabled

func (tm *TracerManager) IsEnabled() bool

IsEnabled returns whether tracing is enabled

func (*TracerManager) Shutdown

func (tm *TracerManager) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the tracer provider

func (*TracerManager) UpdateConfig

func (tm *TracerManager) UpdateConfig(config TracingConfig) error

UpdateConfig updates the tracing configuration

type TracingConfig

type TracingConfig struct {
	ServiceName    string
	ServiceVersion string
	JaegerEndpoint string
	SamplingRate   float64
	Enabled        bool
}

TracingConfig holds tracing configuration

type URI

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

URI wraps url.URL providing fasthttp-compatible API.

func (*URI) Path

func (u *URI) Path() []byte

Path returns the request path as bytes.

func (*URI) QueryString

func (u *URI) QueryString() []byte

QueryString returns the raw query string as bytes.

func (*URI) String

func (u *URI) String() string

String returns the complete URI as string.

type ValueBinder

type ValueBinder struct {
	// ValueFunc is used to get single parameter value from request
	ValueFunc func(sourceParam string) string
	// ValuesFunc is used to get all values for parameter from request
	ValuesFunc func(sourceParam string) []string
	// ErrorFunc is used to create errors
	ErrorFunc func(sourceParam string, values []string, message any, internalError error) error
	// contains filtered or unexported fields
}

ValueBinder provides utility methods for binding query or path parameters to various Go built-in types Provides type-safe parameter binding with error handling

func FormFieldBinder

func FormFieldBinder(ctx *RequestContext) *ValueBinder

FormFieldBinder creates form field value binder

func PathParamsBinder

func PathParamsBinder(ctx *RequestContext) *ValueBinder

PathParamsBinder creates path parameter value binder

func QueryParamsBinder

func QueryParamsBinder(ctx *RequestContext) *ValueBinder

QueryParamsBinder creates query parameter value binder

func (*ValueBinder) BindError

func (b *ValueBinder) BindError() error

BindError returns first bind error and resets error slice

func (*ValueBinder) BindErrors

func (b *ValueBinder) BindErrors() []error

BindErrors returns all bind errors and resets error slice

func (*ValueBinder) BindWithDelimiter

func (b *ValueBinder) BindWithDelimiter(name string, dest *[]string, delimiter string) *ValueBinder

BindWithDelimiter binds parameter with delimiter splitting

func (*ValueBinder) Bool

func (b *ValueBinder) Bool(name string, dest *bool) *ValueBinder

Bool binds parameter to bool destination

func (*ValueBinder) CustomFunc

func (b *ValueBinder) CustomFunc(name string, customFunc func(values []string) []error) *ValueBinder

CustomFunc executes custom binding function

func (*ValueBinder) FailFast

func (b *ValueBinder) FailFast(failFast bool) *ValueBinder

FailFast sets the binder to fail fast on first error

func (*ValueBinder) Float64

func (b *ValueBinder) Float64(name string, dest *float64) *ValueBinder

Float64 binds parameter to float64 destination

func (*ValueBinder) HasErrors

func (b *ValueBinder) HasErrors() bool

HasErrors returns true if binder has accumulated errors

func (*ValueBinder) Int

func (b *ValueBinder) Int(name string, dest *int) *ValueBinder

Int binds parameter to int destination

func (*ValueBinder) Int64

func (b *ValueBinder) Int64(name string, dest *int64) *ValueBinder

Int64 binds parameter to int64 destination

func (*ValueBinder) MustInt

func (b *ValueBinder) MustInt(name string, dest *int) *ValueBinder

MustInt binds parameter to int destination (required)

func (*ValueBinder) MustInt64

func (b *ValueBinder) MustInt64(name string, dest *int64) *ValueBinder

MustInt64 binds parameter to int64 destination (required)

func (*ValueBinder) MustString

func (b *ValueBinder) MustString(name string, dest *string) *ValueBinder

MustString binds parameter to string destination (required)

func (*ValueBinder) String

func (b *ValueBinder) String(name string, dest *string) *ValueBinder

String binds parameter to string destination

func (*ValueBinder) Strings

func (b *ValueBinder) Strings(name string, dest *[]string) *ValueBinder

Strings binds parameter to string slice destination

func (*ValueBinder) Time

func (b *ValueBinder) Time(name string, dest *time.Time, layout string) *ValueBinder

Time binds parameter to time.Time destination

func (*ValueBinder) UnixTime

func (b *ValueBinder) UnixTime(name string, dest *time.Time) *ValueBinder

UnixTime binds unix timestamp parameter to time.Time destination

type WriterFlusher

type WriterFlusher interface {
	io.Writer
	Flush() error
}

WriterFlusher combines io.Writer and http.Flusher interfaces

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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