scontext

package
v1.3.8 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2025 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package scontext provides centralized context management for the SRouter framework. It implements a single context wrapper (SRouterContext) that holds all request-scoped values such as user information, trace IDs, client IPs, database transactions, and route metadata. This approach avoids deep context nesting and provides type-safe access to context values through generic functions.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CopySRouterContext added in v1.3.3

func CopySRouterContext[T comparable, U any](dst, src context.Context) context.Context

CopySRouterContext creates a deep copy of the SRouterContext from the source context and adds it to the destination context. This is useful when you need to transfer all SRouter context values to a new context while preserving the destination's underlying context chain (cancellation, deadlines, etc.).

If no SRouterContext exists in the source, the destination context is returned unchanged. If the source contains an SRouterContext, all values (including flags) are deep copied to ensure the destination has its own independent copy. The destination context will automatically have an SRouterContext added if none exists.

T is the User ID type (comparable), U is the User object type (any).

func CopySRouterContextOverlay added in v1.3.3

func CopySRouterContextOverlay[T comparable, U any](dst, src context.Context) context.Context

CopySRouterContextOverlay creates a deep copy of the SRouterContext from the source context and overlays it onto the destination context only if the destination already has an SRouterContext. If the destination does not have an SRouterContext, this function performs no operation and returns the destination unchanged.

If no SRouterContext exists in the source, the destination context is returned unchanged. If both source and destination contain SRouterContexts, the source values (including flags) are deep copied and completely replace the destination's SRouterContext.

This function is useful when you want to update existing SRouter context values but avoid creating new context structures where none existed before.

T is the User ID type (comparable), U is the User object type (any).

func GetCORSInfo added in v1.2.4

func GetCORSInfo[T comparable, U any](ctx context.Context) (allowedOrigin string, credentialsAllowed bool, ok bool)

GetCORSInfo retrieves CORS (Cross-Origin Resource Sharing) details from the context. It returns: - allowedOrigin: The origin that should be set in Access-Control-Allow-Origin header - credentialsAllowed: Whether Access-Control-Allow-Credentials should be "true" - ok: Whether CORS information was found in the context T is the User ID type (comparable), U is the User object type (any).

func GetCORSInfoFromRequest added in v1.2.4

func GetCORSInfoFromRequest[T comparable, U any](r *http.Request) (allowedOrigin string, credentialsAllowed bool, ok bool)

GetCORSInfoFromRequest is a convenience function that extracts CORS details from an http.Request. It is equivalent to calling GetCORSInfo with r.Context(). T is the User ID type (comparable), U is the User object type (any).

func GetCORSRequestedHeaders added in v1.2.9

func GetCORSRequestedHeaders[T comparable, U any](ctx context.Context) (string, bool)

GetCORSRequestedHeaders retrieves the Access-Control-Request-Headers value from the context. This is used internally by the CORS handler to echo back the requested headers when wildcard headers are allowed in the configuration. It returns the headers string and a boolean indicating whether it was found. T is the User ID type (comparable), U is the User object type (any).

func GetCORSRequestedHeadersFromRequest added in v1.2.9

func GetCORSRequestedHeadersFromRequest[T comparable, U any](r *http.Request) (string, bool)

GetCORSRequestedHeadersFromRequest is a convenience function that extracts CORS requested headers from an http.Request. It is equivalent to calling GetCORSRequestedHeaders with r.Context(). T is the User ID type (comparable), U is the User object type (any).

func GetClientIP

func GetClientIP[T comparable, U any](ctx context.Context) (string, bool)

GetClientIP retrieves the client IP address from the context. It returns the IP address and a boolean indicating whether it was found. If no client IP is set, it returns an empty string and false. T is the User ID type (comparable), U is the User object type (any).

func GetClientIPFromRequest

func GetClientIPFromRequest[T comparable, U any](r *http.Request) (string, bool)

GetClientIPFromRequest is a convenience function that extracts the client IP from an http.Request. It is equivalent to calling GetClientIP with r.Context(). T is the User ID type (comparable), U is the User object type (any).

func GetFlag

func GetFlag[T comparable, U any](ctx context.Context, name string) (bool, bool)

GetFlag retrieves a boolean flag from the context. It returns the flag value and a boolean indicating whether the flag exists. If the flag doesn't exist, it returns false, false. T is the User ID type (comparable), U is the User object type (any).

func GetFlagFromRequest

func GetFlagFromRequest[T comparable, U any](r *http.Request, name string) (bool, bool)

GetFlagFromRequest is a convenience function that extracts a flag from an http.Request. It is equivalent to calling GetFlag with r.Context() and the flag name. T is the User ID type (comparable), U is the User object type (any).

func GetHandlerError added in v1.3.2

func GetHandlerError[T comparable, U any](ctx context.Context) (error, bool)

GetHandlerError retrieves the handler error from the context if one was set. This is useful for middleware that needs to react to errors returned by route handlers, such as transaction middleware that might rollback on errors. T is the User ID type (comparable), U is the User object type (any).

func GetHandlerErrorFromRequest added in v1.3.2

func GetHandlerErrorFromRequest[T comparable, U any](r *http.Request) (error, bool)

GetHandlerErrorFromRequest is a convenience function that extracts the handler error from an http.Request. It is equivalent to calling GetHandlerError with r.Context(). T is the User ID type (comparable), U is the User object type (any).

func GetPathParamsFromContext added in v1.2.2

func GetPathParamsFromContext[T comparable, U any](ctx context.Context) (httprouter.Params, bool)

GetPathParamsFromContext retrieves the path parameters from the context. Path parameters are extracted by httprouter from the URL path (e.g., :id in "/users/:id"). It returns the parameters and a boolean indicating whether they were found. T is the User ID type (comparable), U is the User object type (any).

func GetPathParamsFromRequest added in v1.2.2

func GetPathParamsFromRequest[T comparable, U any](r *http.Request) (httprouter.Params, bool)

GetPathParamsFromRequest is a convenience function that extracts path parameters from an http.Request. It is equivalent to calling GetPathParamsFromContext with r.Context(). T is the User ID type (comparable), U is the User object type (any).

func GetRouteTemplateFromContext added in v1.2.2

func GetRouteTemplateFromContext[T comparable, U any](ctx context.Context) (string, bool)

GetRouteTemplateFromContext retrieves the route template from the context. The route template is the original path pattern (e.g., "/users/:id") before parameter substitution. It returns the template and a boolean indicating whether it was found. This is useful for metrics and logging where you want consistent route identifiers. T is the User ID type (comparable), U is the User object type (any).

func GetRouteTemplateFromRequest added in v1.2.2

func GetRouteTemplateFromRequest[T comparable, U any](r *http.Request) (string, bool)

GetRouteTemplateFromRequest is a convenience function that extracts the route template from an http.Request. It is equivalent to calling GetRouteTemplateFromContext with r.Context(). T is the User ID type (comparable), U is the User object type (any).

func GetTraceIDFromContext

func GetTraceIDFromContext[T comparable, U any](ctx context.Context) string

GetTraceIDFromContext retrieves the trace ID from the context. It returns the trace ID if set, or an empty string if not found. This function never returns an error; absence is indicated by an empty string. T is the User ID type (comparable), U is the User object type (any).

func GetTraceIDFromRequest

func GetTraceIDFromRequest[T comparable, U any](r *http.Request) string

GetTraceIDFromRequest is a convenience function that extracts the trace ID from an http.Request. It is equivalent to calling GetTraceIDFromContext with r.Context(). Returns an empty string if no trace ID is set. T is the User ID type (comparable), U is the User object type (any).

func GetUser

func GetUser[T comparable, U any](ctx context.Context) (*U, bool)

GetUser retrieves the user object from the context. It returns a pointer to the user object and a boolean indicating whether it was found. If no user is set, it returns nil and false. T is the User ID type (comparable), U is the User object type (any).

func GetUserAgent added in v1.2.13

func GetUserAgent[T comparable, U any](ctx context.Context) (string, bool)

GetUserAgent retrieves the User-Agent string from the context. It returns the User-Agent and a boolean indicating whether it was found. If no User-Agent is set, it returns an empty string and false. T is the User ID type (comparable), U is the User object type (any).

func GetUserAgentFromRequest added in v1.2.13

func GetUserAgentFromRequest[T comparable, U any](r *http.Request) (string, bool)

GetUserAgentFromRequest is a convenience function that extracts the User-Agent from an http.Request. It is equivalent to calling GetUserAgent with r.Context(). T is the User ID type (comparable), U is the User object type (any).

func GetUserFromRequest

func GetUserFromRequest[T comparable, U any](r *http.Request) (*U, bool)

GetUserFromRequest is a convenience function that extracts the user object from an http.Request. It is equivalent to calling GetUser with r.Context(). T is the User ID type (comparable), U is the User object type (any).

func GetUserID

func GetUserID[T comparable, U any](ctx context.Context) (T, bool)

GetUserID retrieves the user ID from the context. It returns the user ID and a boolean indicating whether it was found. If no user ID is set, it returns the zero value of T and false. T is the User ID type (comparable), U is the User object type (any).

func GetUserIDFromRequest

func GetUserIDFromRequest[T comparable, U any](r *http.Request) (T, bool)

GetUserIDFromRequest is a convenience function that extracts the user ID from an http.Request. It is equivalent to calling GetUserID with r.Context(). T is the User ID type (comparable), U is the User object type (any).

func WithCORSInfo added in v1.2.4

func WithCORSInfo[T comparable, U any](ctx context.Context, allowedOrigin string, credentialsAllowed bool) context.Context

WithCORSInfo adds CORS (Cross-Origin Resource Sharing) information to the context. This is used internally by the CORS middleware to store the allowed origin and whether credentials are allowed for the current request. These values are used when generating error responses to ensure CORS headers are properly set. T is the User ID type (comparable), U is the User object type (any).

func WithCORSRequestedHeaders added in v1.2.9

func WithCORSRequestedHeaders[T comparable, U any](ctx context.Context, requestedHeaders string) context.Context

WithCORSRequestedHeaders stores the Access-Control-Request-Headers value from a CORS preflight request. This is used internally when the CORS configuration allows wildcard headers (*), so the exact requested headers can be echoed back in the Access-Control-Allow-Headers response. T is the User ID type (comparable), U is the User object type (any).

func WithClientIP

func WithClientIP[T comparable, U any](ctx context.Context, ip string) context.Context

WithClientIP adds the client IP address to the context. The IP is typically extracted by the router based on IPConfig settings, considering headers like X-Forwarded-For, X-Real-IP, or RemoteAddr. T is the User ID type (comparable), U is the User object type (any).

func WithFlag

func WithFlag[T comparable, U any](ctx context.Context, name string, value bool) context.Context

WithFlag adds a boolean flag to the context. Flags are used to store custom boolean values that don't warrant their own field. The flag name should be descriptive and unique within the application. T is the User ID type (comparable), U is the User object type (any).

func WithHandlerError added in v1.3.2

func WithHandlerError[T comparable, U any](ctx context.Context, err error) context.Context

WithHandlerError sets the handler error in the context. This is typically used by the framework to store errors returned by generic route handlers, making them available to middleware. T is the User ID type (comparable), U is the User object type (any).

func WithRouteInfo added in v1.2.2

func WithRouteInfo[T comparable, U any](ctx context.Context, params httprouter.Params, routeTemplate string) context.Context

WithRouteInfo adds route information to the context. This includes path parameters extracted by httprouter and the route template string. This function is called internally by the router when a route is matched. The route template is the original path pattern (e.g., "/users/:id") used for metrics and logging. T is the User ID type (comparable), U is the User object type (any).

func WithSRouterContext

func WithSRouterContext[T comparable, U any](ctx context.Context, rc *SRouterContext[T, U]) context.Context

WithSRouterContext adds or replaces the SRouterContext in a context.Context. It returns a new context containing the provided SRouterContext. This is typically used internally by the framework. T is the User ID type (comparable), U is the User object type (any).

func WithTraceID

func WithTraceID[T comparable, U any](ctx context.Context, traceID string) context.Context

WithTraceID adds a trace ID to the context. The trace ID is used for distributed tracing and request correlation. If a trace ID is already set, this function will not overwrite it, preserving trace IDs propagated from upstream services. T is the User ID type (comparable), U is the User object type (any).

func WithTransaction

func WithTransaction[T comparable, U any](ctx context.Context, tx DatabaseTransaction) context.Context

WithTransaction adds a database transaction to the context. This is typically used by database middleware to make a transaction available to handlers for transactional operations. The transaction should implement the DatabaseTransaction interface. T is the User ID type (comparable), U is the User object type (any).

func WithUser

func WithUser[T comparable, U any](ctx context.Context, user *U) context.Context

WithUser adds a user object to the context. The user object is typically set by authentication middleware that returns full user details. T is the User ID type (comparable), U is the User object type (any).

func WithUserAgent added in v1.2.13

func WithUserAgent[T comparable, U any](ctx context.Context, ua string) context.Context

WithUserAgent adds the User-Agent string to the context. The User-Agent is typically extracted from the request headers by the router. T is the User ID type (comparable), U is the User object type (any).

func WithUserID

func WithUserID[T comparable, U any](ctx context.Context, userID T) context.Context

WithUserID adds a user ID to the context. The user ID is typically set by authentication middleware after validating credentials. T is the User ID type (comparable), U is the User object type (any).

Types

type DatabaseTransaction

type DatabaseTransaction interface {
	Commit() error
	Rollback() error
	SavePoint(name string) error
	RollbackTo(name string) error
	GetDB() *gorm.DB
}

DatabaseTransaction defines an interface for essential transaction control methods. This allows mocking transaction behavior for testing purposes. Note: Moved from middleware/db.go to avoid import cycle if db needed context. Consider if this interface truly belongs here or in a db-specific package. For now, placing here to resolve cycle.

func GetTransaction

func GetTransaction[T comparable, U any](ctx context.Context) (DatabaseTransaction, bool)

GetTransaction retrieves a database transaction from the context. It returns the transaction and a boolean indicating whether it was found. If no transaction is set, it returns nil and false. T is the User ID type (comparable), U is the User object type (any).

func GetTransactionFromRequest

func GetTransactionFromRequest[T comparable, U any](r *http.Request) (DatabaseTransaction, bool)

GetTransactionFromRequest is a convenience function that extracts a database transaction from an http.Request. It is equivalent to calling GetTransaction with r.Context(). T is the User ID type (comparable), U is the User object type (any).

type SRouterContext

type SRouterContext[T comparable, U any] struct {
	UserID T
	User   *U

	TraceID string

	ClientIP string

	// UserAgent holds the user agent string from the request.
	UserAgent string

	Transaction DatabaseTransaction

	// Route information
	RouteTemplate string
	PathParams    httprouter.Params

	// CORS information determined by middleware
	AllowedOrigin      string
	CredentialsAllowed bool
	RequestedHeaders   string // Stores the requested headers from CORS preflight requests

	// HandlerError stores any error returned by the route handler
	HandlerError error

	UserIDSet             bool
	UserSet               bool
	ClientIPSet           bool
	UserAgentSet          bool
	TraceIDSet            bool
	TransactionSet        bool
	RouteTemplateSet      bool
	AllowedOriginSet      bool
	CredentialsAllowedSet bool
	RequestedHeadersSet   bool // Flag for RequestedHeaders
	// HandlerErrorSet is used to distinguish between an unset error and an explicitly set nil error.
	HandlerErrorSet bool

	Flags map[string]bool
}

SRouterContext holds all values that SRouter adds to request contexts. It provides a centralized storage for all request-scoped data, avoiding the need for multiple context.WithValue calls and deep context nesting. T is the User ID type (comparable), U is the User object type (any).

func EnsureSRouterContext

func EnsureSRouterContext[T comparable, U any](ctx context.Context) (*SRouterContext[T, U], context.Context)

EnsureSRouterContext retrieves an existing SRouterContext or creates a new one if none exists. It returns both the SRouterContext and the potentially updated context. This is used internally by With* functions to ensure a context exists before setting values. T is the User ID type (comparable), U is the User object type (any).

func GetSRouterContext

func GetSRouterContext[T comparable, U any](ctx context.Context) (*SRouterContext[T, U], bool)

GetSRouterContext retrieves the SRouterContext from a standard context.Context. It returns the context and a boolean indicating whether it was found. If no SRouterContext exists, it returns nil and false. T is the User ID type (comparable), U is the User object type (any).

func NewSRouterContext

func NewSRouterContext[T comparable, U any]() *SRouterContext[T, U]

NewSRouterContext creates a new SRouterContext instance with initialized fields. It returns a pointer to a new context with an empty Flags map ready for use. T is the User ID type (comparable), U is the User object type (any).

Jump to

Keyboard shortcuts

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