Documentation
¶
Index ¶
- Constants
- Variables
- func Any2Error(as ...interface{}) []error
- func Error2Any(errs ...error) []interface{}
- func ToFatal(err error) error
- func ToNormal(err error) error
- type Action
- type CallbackData
- type CallbackManager
- type EmptyStruct
- type Encoder
- type EncoderError
- type EncoderRegistry
- type ErrorFilterSet
- type ErrorList
- type Event
- type EventStreamEncoder
- type Finalizer
- type FormURLEncodedEncoder
- type HTTPProtocol
- type JSONEncoder
- type Logger
- type MsgPackEncoder
- type Preset
- type Protocol
- type ProtocolHandler
- type Renderer
- func (r *Renderer) Binary(contentType string, data []byte) error
- func (r *Renderer) Data(msg string, data interface{}) error
- func (r *Renderer) Error(errs ...error) error
- func (r *Renderer) ErrorInfo(message string, info interface{}, errs ...error) error
- func (r *Renderer) ErrorMsg(message string, errs ...error) error
- func (r *Renderer) Errorf(format string, args ...interface{}) error
- func (r *Renderer) Fatal(errs ...error) error
- func (r *Renderer) FatalInfo(message string, info interface{}, errs ...error) error
- func (r *Renderer) FatalMsg(message string, errs ...error) error
- func (r *Renderer) Fatalf(format string, args ...interface{}) error
- func (r *Renderer) Form(req *http.Request, v interface{}) error
- func (r *Renderer) Handler(fn func(r *Renderer) error) http.HandlerFunc
- func (r *Renderer) Image(contentType string, img image.Image) error
- func (r *Renderer) Info(msg string, info interface{}) error
- func (r *Renderer) JSON(req *http.Request, v interface{}) error
- func (r *Renderer) Log(err error)
- func (r *Renderer) Logf(format string, args ...interface{})
- func (r *Renderer) Msg(msg string) error
- func (r *Renderer) MsgPack(req *http.Request, v interface{}) error
- func (r *Renderer) Msgf(format string, args ...interface{}) error
- func (r *Renderer) Pending(msg string, info interface{}) error
- func (r *Renderer) Push(w Writer, d Response) error
- func (r *Renderer) Pusher(contentType string, data io.Reader) error
- func (r *Renderer) Raw(data interface{}) error
- func (r *Renderer) Reader() *hauler.Hauler
- func (r *Renderer) Relay(data interface{}) error
- func (r *Renderer) Request(req *http.Request, v interface{}) error
- func (r *Renderer) Response(msg string, info interface{}, data interface{}) error
- func (r *Renderer) Rest(data interface{}) error
- func (r *Renderer) Send(msg string, info interface{}) error
- func (r *Renderer) Stream(callback func(*Renderer) (interface{}, error)) error
- func (r *Renderer) Titled(title, msg string, info interface{}) error
- func (r *Renderer) UseEncoder(e Encoder) *Renderer
- func (r *Renderer) Warning(errs ...error) error
- func (r *Renderer) Warningf(format string, args ...interface{}) error
- func (r *Renderer) WithAction(actions ...Action) *Renderer
- func (r *Renderer) WithActions(actions []Action) *Renderer
- func (r *Renderer) WithCallback(cb ...func(data CallbackData)) *Renderer
- func (r *Renderer) WithContentType(contentType string) *Renderer
- func (r *Renderer) WithContext(ctx context.Context) *Renderer
- func (r *Renderer) WithConvertFilter(filters ...func(error) error) *Renderer
- func (r *Renderer) WithErrorHeader(key string) *Renderer
- func (r *Renderer) WithFilter(efs ErrorFilterSet) *Renderer
- func (r *Renderer) WithFinalizer(f Finalizer) *Renderer
- func (r *Renderer) WithHeader(key, value string) *Renderer
- func (r *Renderer) WithHeaders(kv ...string) *Renderer
- func (r *Renderer) WithHeadersEnabled(enabled bool) *Renderer
- func (r *Renderer) WithID(id string) *Renderer
- func (r *Renderer) WithIDGeneration(enabled State) *Renderer
- func (r *Renderer) WithLogger(l Logger) *Renderer
- func (r *Renderer) WithMeta(key string, value interface{}) *Renderer
- func (r *Renderer) WithMetaKV(kvs ...interface{}) *Renderer
- func (r *Renderer) WithProtocol(p Protocol) *Renderer
- func (r *Renderer) WithRedactFilter(filters ...func(error) bool) *Renderer
- func (r *Renderer) WithShowError(show State) error
- func (r *Renderer) WithShowSystem(show SystemShow) *Renderer
- func (r *Renderer) WithSingle(name, description string) *Renderer
- func (r *Renderer) WithSkipFilter(filters ...func(error) bool) *Renderer
- func (r *Renderer) WithStatus(code int) *Renderer
- func (r *Renderer) WithSystem(show SystemShow, sys System) *Renderer
- func (r *Renderer) WithTag(tags ...string) *Renderer
- func (r *Renderer) WithTitle(t string) *Renderer
- func (r *Renderer) WithWriter(w Writer) *Renderer
- func (r *Renderer) XML(req *http.Request, v interface{}) error
- type Response
- type Setting
- type State
- type Streamer
- type System
- type SystemShow
- type TCPProtocol
- type TextEncoder
- type Writer
- type XMLEncoder
Constants ¶
const ( StatusError = "-error" // Indicates a non-fatal error StatusPending = "?pending" // Indicates an operation is in progress StatusSuccessful = "+ok" // Indicates a successful operation StatusFatal = "*fatal" // Indicates a critical error StatusWarning = "*warning" // Indicates a non-critical warning StatusUnknown = "*unknown" // Indicates an undefined or unknown state )
Status constants define standardized response states for Renderer responses. They are used in the Response struct to indicate the outcome of an operation.
const ( HeaderPrefix = "X-Beam" // Prefix for custom Beam headers HeaderContentType = "Content-Type" // Standard HTTP Content-Type header HeaderNameDuration = "Duration" // Duration of the operation HeaderNameTimestamp = "Timestamp" // Timestamp of the response HeaderNameApp = "App" // Application name HeaderNameServer = "Server" // Server identifier HeaderNameVersion = "Version" // Application version HeaderNameBuild = "Build" // Build identifier HeaderNamePlay = "Play" // Play mode or context )
Header constants define standard HTTP header names and prefixes for metadata. They are used by Renderer to set response headers like Content-Type and Duration.
const ( Unknown = 0 // Default state for an operation No = -1 // Operation failed Yes = 1 // Operation succeeded )
Operation status constants indicate the success or failure of operations. They are used to represent the outcome of internal operations.
const ( ContentTypeJSON = "application/json" ContentTypeMsgPack = "application/msgpack" ContentTypeXML = "application/xml" ContentTypeText = "text/plain" ContentTypeBinary = "application/octet-stream" ContentTypeFormURLEncoded = "application/x-www-form-urlencoded" ContentTypeEventStream = "text/event-stream" ContentTypePNG = "image/png" ContentTypeJPEG = "image/jpeg" ContentTypeGIF = "image/gif" ContentTypeWebP = "image/webp" )
const Empty = ""
Empty is a constant representing an empty string. It serves as a default or placeholder for uninitialized or unset fields in Beam components.
Variables ¶
var ( ErrHidden = errors.New("hidden") // Suppresses error details in responses ErrSkip = errors.New("skip") // Bypasses operations without failure )
Predefined errors for special handling in Renderer. They control response behavior by suppressing or bypassing errors.
var ErrContextCanceled = errors.New("context canceled")
ErrContextCanceled is a predefined error for context cancellation. Signals that a context was canceled during operation. Used by Renderer to handle canceled requests.
Functions ¶
func Any2Error ¶
func Any2Error(as ...interface{}) []error
Any2Error converts a slice of interfaces to a slice of errors. It filters out non-error values and nil errors, retaining only valid errors. Returns a new slice containing non-nil error values.
func Error2Any ¶
func Error2Any(errs ...error) []interface{}
Error2Any converts a slice of errors to a slice of interfaces. It transforms errors into a format suitable for variadic functions expecting interface{}. Returns a new slice containing the errors as interface{} values.
Types ¶
type Action ¶
type Action struct {
Name string `json:"name"` // Unique identifier for the action
Description string `json:"description,omitempty"` // Human-readable description
Method string `json:"method,omitempty"` // HTTP method (GET, POST, etc)
Href string `json:"href,omitempty"` // URL or URI template
Parameters map[string]interface{} `json:"parameters,omitempty"` // Required parameters
Headers map[string]string `json:"headers,omitempty"` // Required headers
Required bool `json:"required,omitempty"`
}
Action represents a possible next step the client can take
type CallbackData ¶
type CallbackData struct {
ID string `json:"id"`
Status string `json:"status"` // Uses Status* constants
Title string `json:"title,omitempty"`
Tags []string `json:"tags,omitempty"`
Message string `json:"message,omitempty"`
Output string `json:"output,omitempty"`
Err error `json:"-"` // Not marshaled, for internal use
}
CallbackData carries information to callback functions. Holds response metadata like ID, status, and errors. Used by CallbackManager to pass data to callbacks.
func (CallbackData) Error ¶
func (c CallbackData) Error() error
Error returns the error associated with the callback data. Returns the Err field of the CallbackData struct. Implements the error interface for CallbackData.
func (CallbackData) IsError ¶
func (c CallbackData) IsError() bool
IsError checks if the callback data represents an error state. Returns true if the status is StatusError or StatusFatal. Used to determine if a callback indicates an error.
type CallbackManager ¶
type CallbackManager struct {
// contains filtered or unexported fields
}
CallbackManager handles callback registration and triggering. Manages a slice of callback functions for response events. Used by Renderer to notify callbacks of response status.
func NewCallbackManager ¶
func NewCallbackManager() *CallbackManager
NewCallbackManager creates a new CallbackManager. Initializes an empty CallbackManager for callback registration. Returns a *CallbackManager ready for use.
func (*CallbackManager) AddCallback ¶
func (cm *CallbackManager) AddCallback(cb ...func(data CallbackData)) *CallbackManager
AddCallback registers one or more callbacks. Takes callback functions that accept CallbackData. Appends callbacks to the manager and returns it for chaining.
func (*CallbackManager) Clone ¶
func (cm *CallbackManager) Clone() *CallbackManager
Clone creates a copy of the CallbackManager. Duplicates the callbacks slice for thread-safe operations. Returns a new *CallbackManager with copied callbacks.
func (*CallbackManager) Trigger ¶
func (cm *CallbackManager) Trigger(id, status, msg string, err error)
Trigger calls all registered callbacks with the provided data. Takes ID, status, message, and optional error for callbacks. Executes each callback with constructed CallbackData.
type EmptyStruct ¶
type EmptyStruct struct{}
EmptyStruct is a zero-memory struct used as a placeholder. It represents an empty or null value in response fields like Info or Data.
type Encoder ¶
type Encoder interface {
Marshal(v interface{}) ([]byte, error)
Unmarshal(data []byte, v interface{}) error
ContentType() string
}
Encoder defines the interface for encoding data.
type EncoderError ¶
EncoderError represents an encoding failure with fallback data
func (*EncoderError) Error ¶
func (e *EncoderError) Error() string
Error returns a string representation of the encoding error. Combines the content type and original error message. Implements the error interface for EncoderError. Returns a formatted string for error reporting.
func (*EncoderError) GenerateFallback ¶
func (e *EncoderError) GenerateFallback() []byte
GenerateFallback generates the appropriate fallback based on content type. Selects the appropriate error response based on content type. Supports JSON, XML, Text, and MsgPack formats. Returns the fallback data as bytes.
func (*EncoderError) JSONErrorResponse ¶
func (e *EncoderError) JSONErrorResponse() []byte
JSONErrorResponse generates a JSON-formatted error response. Creates a JSON object with "error" and "message" fields. Uses a pooled buffer for encoding to reduce allocations. Returns the encoded JSON bytes, falling back to direct marshal if needed.
func (*EncoderError) TextErrorResponse ¶
func (e *EncoderError) TextErrorResponse() []byte
TextErrorResponse generates a text-formatted error response. Formats a plain text message with the encoding error. Uses a pooled buffer to minimize memory allocations. Returns the formatted text as bytes.
func (*EncoderError) Unwrap ¶
func (e *EncoderError) Unwrap() error
Unwrap returns the original error causing the encoding failure. Provides access to the underlying error for unwrapping. Implements the Unwrap method for error handling. Returns the OriginalError field.
func (*EncoderError) XMLErrorResponse ¶
func (e *EncoderError) XMLErrorResponse() []byte
XMLErrorResponse generates an XML-formatted error response. Creates an XML structure with an "error" tag and message. Uses a pooled buffer for encoding to reduce allocations. Returns the encoded XML bytes, falling back to direct marshal if needed.
type EncoderRegistry ¶
type EncoderRegistry struct {
// contains filtered or unexported fields
}
EncoderRegistry manages content-type to encoder mappings.
func NewEncoderRegistry ¶
func NewEncoderRegistry() *EncoderRegistry
NewEncoderRegistry initializes an EncoderRegistry with default encoders. Creates a new registry with thread-safe encoder mappings. Registers JSON, MsgPack, XML, Text, FormURLEncoded, and EventStream encoders. Returns a pointer to the initialized EncoderRegistry.
func (*EncoderRegistry) Encode ¶
func (er *EncoderRegistry) Encode(contentType string, v interface{}) ([]byte, error)
Encode marshals data using the encoder for the given content type. Takes a content type and data to encode. Returns the encoded bytes or an error if the encoder is not found. Delegates to the appropriate encoder's Marshal method.
func (*EncoderRegistry) EncodeWithFallback ¶
func (er *EncoderRegistry) EncodeWithFallback(contentType string, v interface{}) ([]byte, error)
EncodeWithFallback marshals data with fallback on error. Takes a content type and data to encode. Returns encoded bytes or fallback data with an EncoderError if encoding fails. Uses the encoder's Marshal method with fallback handling.
func (*EncoderRegistry) Get ¶
func (er *EncoderRegistry) Get(contentType string) (Encoder, bool)
Get retrieves an encoder by content type. Takes a content type string (e.g., "application/json"). Returns the associated Encoder and a boolean indicating if found. Thread-safe using a read lock for concurrent access.
func (*EncoderRegistry) Register ¶
func (er *EncoderRegistry) Register(e Encoder)
Register adds an encoder to the registry. Takes an Encoder implementation to register for its content type. Thread-safe using a mutex to protect concurrent access. Associates the encoder with its ContentType in the encoders map.
type ErrorFilterSet ¶
type ErrorFilterSet struct {
Skip []func(error) bool // Determines errors to omit from non-fatal responses
Redact []func(error) bool // Determines errors to mask in responses
Convert []func(error) error // Transforms errors, e.g., to change severity
}
ErrorFilterSet holds functions to filter, redact, or convert errors before inclusion in responses.
type ErrorList ¶
type ErrorList []error
ErrorList is a custom type for a list of errors that implements JSON marshalling. Represents a slice of errors for response serialization. Used in Response to include multiple errors.
func (ErrorList) MarshalJSON ¶
MarshalJSON implements custom JSON marshaling for ErrorList. Converts each error to its string representation. Returns JSON-encoded error strings or an error if marshaling fails.
func (*ErrorList) UnmarshalJSON ¶
UnmarshalJSON implements custom JSON unmarshaling for ErrorList. Converts JSON string array to a slice of errors. Returns an error if unmarshaling fails.
type Event ¶
type Event struct {
ID string `json:"id,omitempty"`
Type string `type:"type,omitempty"`
Data interface{} `json:"data"`
Retry int `json:"retry,omitempty"`
}
Event represents a Server-Sent Events (SSE) event.
type EventStreamEncoder ¶
type EventStreamEncoder struct{}
EventStreamEncoder encodes Server-Sent Events (SSE).
func (*EventStreamEncoder) ContentType ¶
func (e *EventStreamEncoder) ContentType() string
ContentType returns the SSE content type. Returns the constant "text/event-stream". Used by EncoderRegistry to map this encoder. No side effects or parameters.
func (*EventStreamEncoder) Marshal ¶
func (e *EventStreamEncoder) Marshal(v interface{}) ([]byte, error)
Marshal encodes an SSE event to its string representation. Takes an Event struct with ID, Type, Data, and Retry fields. Returns the encoded SSE bytes without extra newlines or an error if encoding fails. Uses pooled buffers for both the event and its JSON data field to minimize allocations.
func (*EventStreamEncoder) Stream ¶
func (e *EventStreamEncoder) Stream(w Writer, callback func() (interface{}, error)) error
Stream sends SSE events incrementally using a callback. Takes a Writer and a callback that produces Event data. Writes encoded events to the Writer, flushing if supported. Returns an error if encoding or writing fails.
func (*EventStreamEncoder) Unmarshal ¶
func (e *EventStreamEncoder) Unmarshal(data []byte, v interface{}) error
Unmarshal is a no-op for SSE events. Takes a byte slice and a target variable (ignored). Always returns nil, as decoding is not supported. No side effects or buffer usage.
type Finalizer ¶
Finalizer defines a function to handle errors after rendering. Takes a Writer and an error to process. Used by Renderer to finalize error responses.
type FormURLEncodedEncoder ¶
type FormURLEncodedEncoder struct{}
func (*FormURLEncodedEncoder) ContentType ¶
func (e *FormURLEncodedEncoder) ContentType() string
ContentType returns the form-urlencoded content type. Returns the constant "application/x-www-form-urlencoded". Used by EncoderRegistry to map this encoder. No side effects or parameters.
func (*FormURLEncodedEncoder) Marshal ¶
func (e *FormURLEncodedEncoder) Marshal(v interface{}) ([]byte, error)
Marshal encodes a map to URL-encoded form data using a pooled buffer. Takes a map[string]interface{} to encode as form data. Returns the encoded bytes or an error if the input is not a map. Uses a pooled buffer to reduce memory allocations.
func (*FormURLEncodedEncoder) Unmarshal ¶
func (e *FormURLEncodedEncoder) Unmarshal(data []byte, v interface{}) error
Unmarshal is a no-op for form-encoded data. Takes a byte slice and a target variable (ignored). Always returns nil, as decoding is not supported. No side effects or buffer usage.
type HTTPProtocol ¶
type HTTPProtocol struct{}
HTTPProtocol implements the HTTP protocol. Provides HTTP-specific header application for responses. Writes status codes to http.ResponseWriter.
func (*HTTPProtocol) ApplyHeaders ¶
func (p *HTTPProtocol) ApplyHeaders(w Writer, code int) error
ApplyHeaders applies HTTP-specific headers and status code. Takes a Writer and HTTP status code to write the status. Returns an error if the Writer is not an http.ResponseWriter.
type JSONEncoder ¶
type JSONEncoder struct{}
func (*JSONEncoder) ContentType ¶
func (e *JSONEncoder) ContentType() string
ContentType returns the JSON content type. Returns the constant "application/json". Used by EncoderRegistry to map this encoder. No side effects or parameters.
func (*JSONEncoder) Marshal ¶
func (e *JSONEncoder) Marshal(v interface{}) ([]byte, error)
Marshal encodes data to JSON format using a pooled buffer. Takes any JSON-serializable data as input. Returns the encoded JSON bytes without trailing newline or an error if encoding fails. Uses a pooled buffer to reduce memory allocations.
func (*JSONEncoder) Unmarshal ¶
func (e *JSONEncoder) Unmarshal(data []byte, v interface{}) error
Unmarshal decodes JSON data into the provided pointer. Takes a byte slice and a pointer to the target variable. Returns an error if decoding fails. Uses standard json.Unmarshal without buffer pooling.
type Logger ¶
type Logger interface {
// Error logs a non-fatal error with structured context.
Error(err error, fields ...interface{})
// Fatal logs a fatal error with structured context.
// The implementation may or may not exit the application,
// but it should be treated as the highest severity.
Fatal(err error, fields ...interface{})
}
Logger is an interface for logging errors. Defines a method to log an error and indicate success. Used by Renderer to log errors during response handling.
type MsgPackEncoder ¶
type MsgPackEncoder struct{}
func (*MsgPackEncoder) ContentType ¶
func (e *MsgPackEncoder) ContentType() string
ContentType returns the MsgPack content type. Returns the constant "application/msgpack". Used by EncoderRegistry to map this encoder. No side effects or parameters.
func (*MsgPackEncoder) Marshal ¶
func (e *MsgPackEncoder) Marshal(v interface{}) ([]byte, error)
Marshal encodes data to MsgPack format using a pooled buffer. Takes any MsgPack-serializable data as input. Returns the encoded MsgPack bytes or an error if encoding fails. Uses a pooled buffer to reduce memory allocations.
func (*MsgPackEncoder) Unmarshal ¶
func (e *MsgPackEncoder) Unmarshal(data []byte, v interface{}) error
Unmarshal decodes MsgPack data into the provided pointer. Takes a byte slice and a pointer to the target variable. Returns an error if decoding fails. Uses standard msgpack.Unmarshal without buffer pooling.
type Preset ¶
Preset defines a preset for custom content types. Specifies content type and associated headers. Used in Setting to customize response headers.
type Protocol ¶
Protocol defines protocol-specific behavior. Specifies a method to apply headers to a Writer. Implemented by HTTPProtocol, TCPProtocol, and custom protocols.
type ProtocolHandler ¶
type ProtocolHandler struct {
// contains filtered or unexported fields
}
ProtocolHandler manages protocol-specific behavior. Wraps a Protocol to handle header application. Used by Renderer to apply protocol-specific headers.
func NewProtocolHandler ¶
func NewProtocolHandler(p Protocol) *ProtocolHandler
NewProtocolHandler creates a new ProtocolHandler. Takes a Protocol to manage header application. Returns a *ProtocolHandler with the specified protocol.
func (*ProtocolHandler) ApplyHeaders ¶
func (ph *ProtocolHandler) ApplyHeaders(w Writer, code int) error
ApplyHeaders applies protocol-specific headers to the writer. Takes a Writer and HTTP status code to apply headers. Returns an error if the protocol is nil or header application fails.
type Renderer ¶
type Renderer struct {
// contains filtered or unexported fields
}
Renderer is the core Beam renderer for constructing and sending responses. Manages response configuration, encoding, and output with support for multiple formats. Thread-safe through immutable cloning for concurrent modifications.
func NewRenderer ¶
NewRenderer creates a new Renderer with the provided settings and default content type. Initializes fields with default JSON content type and error filters. Returns a pointer to the initialized Renderer.
func (*Renderer) Binary ¶
Binary sends binary data with the specified content type and headers. Writes the provided byte slice with appropriate headers. Returns an error if header application or writing fails.
func (*Renderer) Data ¶
Data sends a successful HTTP response with a message and optional data. It constructs a Response with StatusSuccessful, the provided message, and data. Returns an error if the writer is nil or sending the response fails.
func (*Renderer) Error ¶
Error sends an error HTTP response with a default message and optional errors. It constructs a Response with StatusError and filtered errors, if any. Skips sending if all errors are filtered and no custom message is intended. Returns an error if the writer is nil or sending the response fails.
func (*Renderer) ErrorInfo ¶
ErrorInfo sends an error HTTP response with a custom message, info data, and optional errors. It constructs a Response with StatusError, the provided message, info, and filtered errors. Skips sending if all errors are filtered and no custom message is intended. Returns an error if the writer is nil or sending the response fails.
func (*Renderer) ErrorMsg ¶
ErrorMsg sends an error HTTP response with a custom message and optional errors. It constructs a Response with StatusError, the provided message, and filtered errors. Skips sending if all errors are filtered and no custom message is intended. Returns an error if the writer is nil or sending the response fails.
func (*Renderer) Errorf ¶
Errorf sends an error HTTP response with a formatted message and optional errors. It formats the message using fmt.Sprintf, filtering errors for the response. Skips sending if all errors are filtered and no custom message is intended. Returns an error if the writer is nil or sending the response fails.
func (*Renderer) Fatal ¶
Fatal sends a fatal error HTTP response with a default message and optional errors. It constructs a Response with StatusFatal and filtered errors, logging errors if a logger is present. Always sends the response, using HTTP status 500 (Internal Server Error). Returns an error if sending the response fails.
func (*Renderer) FatalInfo ¶
FatalInfo sends a fatal error HTTP response with a custom message, info data, and optional errors. It constructs a Response with StatusFatal, the provided message, info, and filtered errors, logging errors if a logger is present. Always sends the response, using HTTP status 500 (Internal Server Error). Returns an error if sending the response fails.
func (*Renderer) FatalMsg ¶
FatalMsg sends a fatal error HTTP response with a custom message and optional errors. It constructs a Response with StatusFatal, the provided message, and filtered errors, logging errors if a logger is present. Always sends the response, using HTTP status 500 (Internal Server Error). Returns an error if sending the response fails.
func (*Renderer) Fatalf ¶
Fatalf sends a fatal error HTTP response with a formatted message and optional errors. It formats the message using fmt.Sprintf and constructs a Response with StatusFatal and filtered errors, logging errors if a logger is present. Always sends the response, using HTTP status 500 (Internal Server Error). Returns an error if sending the response fails.
func (*Renderer) Form ¶
Form reads and parses a form-urlencoded request body into the provided value. Verifies the Content-Type is form-urlencoded and delegates to Request. Returns an error if the request is nil, content type is invalid, or parsing fails.
func (*Renderer) Handler ¶
func (r *Renderer) Handler(fn func(r *Renderer) error) http.HandlerFunc
Handler wraps a function into an HTTP handler, handling errors with Fatal. Takes a function that processes the Renderer and returns an error. Returns an http.HandlerFunc for use in HTTP servers.
func (*Renderer) Image ¶
Image encodes and sends an image with the specified content type. Encodes the provided image.Image (PNG, JPEG, GIF, WebP) and sends as binary data. Returns an error if encoding, header application, or writing fails.
func (*Renderer) Info ¶
Info sends a successful HTTP response with a message and optional info data. It constructs a Response with StatusSuccessful, the provided message, and info. Returns an error if the writer is nil or sending the response fails.
func (*Renderer) JSON ¶
JSON reads and parses a JSON request body into the provided value. Verifies the Content-Type is JSON and delegates to Request. Returns an error if the request is nil, content type is invalid, or parsing fails.
func (*Renderer) Log ¶
Log logs an error if not filtered and a logger is present. Applies error filters and logs the error via the Renderer’s logger. No return value; performs logging as a side effect.
func (*Renderer) Logf ¶
Logf logs a formatted message if a logger is present. Formats the message with filtered args and logs via the Renderer’s logger. No return value; performs logging as a side effect.
func (*Renderer) Msg ¶
Msg sends a successful HTTP response with a simple message. It constructs a Response with StatusSuccessful and the provided message. Returns an error if the writer is nil or sending the response fails.
func (*Renderer) MsgPack ¶
MsgPack reads and parses a MsgPack request body into the provided value. Verifies the Content-Type is MsgPack and delegates to Request. Returns an error if the request is nil, content type is invalid, or parsing fails.
func (*Renderer) Msgf ¶
Msgf sends a successful HTTP response with a formatted message. It formats the message using fmt.Sprintf and constructs a Response with StatusSuccessful. Returns an error if the writer is nil or sending the response fails.
func (*Renderer) Pending ¶
Pending sends a pending HTTP response with a message and optional info data. It constructs a Response with StatusPending and HTTP status 202 (Accepted). Returns an error if the writer is nil or sending the response fails.
func (*Renderer) Push ¶
Push sends a structured Response using the Renderer’s configuration. Encodes and writes the Response with headers, handling errors with fallbacks. Returns an error if encoding, header application, or writing fails.
func (*Renderer) Pusher ¶
Pusher sends data from an io.Reader with the specified content type and headers. Streams the provided reader data with appropriate headers. Returns an error if header application or writing fails.
func (*Renderer) Raw ¶
Raw sends raw data using the Renderer’s current content type. Encodes and writes the provided data with headers, handling errors. Returns an error if encoding, header application, or writing fails.
func (*Renderer) Reader ¶
Reader returns a new request reader instance for parsing HTTP bodies. Creates a new Hauler instance for parsing request data. Returns a pointer to the initialized Hauler.
func (*Renderer) Relay ¶
Relay sends raw data using the Renderer's configured content type, without encoding. Accepts string or []byte as data and writes it directly with headers. Returns an error if data is not string or []byte, or if header application or writing fails.
func (*Renderer) Request ¶
Request reads and parses an HTTP request body into the provided value. Uses the Hauler to parse the request body based on content type. Returns an error if the request is nil or parsing fails; logs errors if applicable.
func (*Renderer) Response ¶
Response sends a successful HTTP response with a message, optional info, and data. It constructs a Response with StatusSuccessful, the provided message, info, and data. Returns an error if the writer is nil or sending the response fails.
func (*Renderer) Rest ¶
Rest sends raw data as JSON using the Renderer's configuration. Encodes and writes the provided data with headers, forcing JSON content type. Just like Raw but always uses JSON with no additional information. Returns an error if encoding, header application, or writing fails.
func (*Renderer) Send ¶
Send sends an HTTP response with an unknown status, message, and optional info. It constructs a Response with StatusUnknown, the provided message, and info data. Returns an error if the writer is nil or sending the response fails.
func (*Renderer) Stream ¶
Stream sends data incrementally using a callback to produce chunks. Writes encoded chunks with headers, flushing if supported by the writer. Returns an error if encoding, header application, or writing fails.
func (*Renderer) Titled ¶
Titled sends a successful HTTP response with a title, message, and optional info. It constructs a Response with StatusSuccessful, the provided title, message, and info. Returns an error if the writer is nil or sending the response fails.
func (*Renderer) UseEncoder ¶
UseEncoder registers a custom encoder with the Renderer. Adds the provided Encoder to the EncoderRegistry. Returns a new Renderer with the updated encoders.
func (*Renderer) Warning ¶
Warning sends a warning response with a default message and errors. Sends a Response with StatusWarning and filtered errors, if any. Returns an error if the writer is unset or sending fails; skips if all errors filtered.
func (*Renderer) Warningf ¶
Warningf sends a warning response with a formatted message and errors. Formats the message with provided args, sending StatusWarning with filtered errors. Returns an error if the writer is unset or sending fails; skips if all errors filtered.
func (*Renderer) WithAction ¶
WithAction adds fully specified actions to the Renderer. Appends the provided Action structs to the actions slice. Returns a new Renderer with the updated actions.
func (*Renderer) WithActions ¶
WithActions replaces all current actions in the Renderer. Sets the provided Action slice as the actions list. Returns a new Renderer with the updated actions.
func (*Renderer) WithCallback ¶
func (r *Renderer) WithCallback(cb ...func(data CallbackData)) *Renderer
WithCallback adds callbacks to the Renderer. Adds the provided callback functions to handle response events. Returns a new Renderer with updated callbacks.
func (*Renderer) WithContentType ¶
WithContentType sets the output content type for the Renderer. Assigns the provided content type string (e.g., "application/json"). Returns a new Renderer with the updated content type.
func (*Renderer) WithContext ¶
WithContext sets the context for the Renderer. Assigns a context.Context for cancellation and deadlines. Returns a new Renderer with the updated context.
func (*Renderer) WithConvertFilter ¶
WithConvertFilter adds filters that can transform an error, e.g., to change its severity.
func (*Renderer) WithErrorHeader ¶
WithErrorHeader configures the Renderer to write the concatenated error messages to the specified header key during an error response. This is useful for providing error context in responses where a body cannot be read, like a failed WebSocket handshake.
func (*Renderer) WithFilter ¶
func (r *Renderer) WithFilter(efs ErrorFilterSet) *Renderer
WithFilter adds error filters to the Renderer. Appends the provided error filter functions to errorFilters. Returns a new Renderer with the updated filters. WithFilter sets the entire ErrorFilterSet for the Renderer. Replaces the current errorFilters with the provided ErrorFilterSet. Returns a new Renderer with the updated error filters.
func (*Renderer) WithFinalizer ¶
WithFinalizer sets the error finalizer for the Renderer. Assigns a Finalizer function to handle errors during response writing. Returns a new Renderer with the updated finalizer.
func (*Renderer) WithHeader ¶
WithHeader adds a header to the Renderer. Adds the provided key-value pair to the HTTP header map. Returns a new Renderer with the updated headers.
func (*Renderer) WithHeaders ¶
WithHeaders adds multiple headers to the Renderer. Adds the provided key-value pairs to the HTTP header map. Expects key-value pairs as variadic arguments (e.g., key1, value1, key2, value2, ...). Returns a new Renderer with the updated headers. Panics if the number of arguments is odd (missing value for a key).
func (*Renderer) WithHeadersEnabled ¶
WithHeadersEnabled enables or disables header output. Toggles the EnableHeaders setting in a new Renderer copy. Returns a new Renderer with the updated header setting.
func (*Renderer) WithID ¶
WithID sets the ID for the Renderer. Assigns the provided string ID for the response. Returns a new Renderer with the updated ID.
func (*Renderer) WithIDGeneration ¶
WithIDGeneration enables or disables automatic ID generation. Toggles the generateID field in a new Renderer copy. Returns a new Renderer with the updated ID generation setting.
func (*Renderer) WithLogger ¶
WithLogger sets the Renderer's logger for error logging. Assigns the provided Logger interface in a new Renderer copy. Returns a new Renderer with the updated logger.
func (*Renderer) WithMeta ¶
WithMeta adds metadata to the Renderer. Adds the provided key-value pair to the meta map. Returns a new Renderer with the updated metadata.
func (*Renderer) WithMetaKV ¶
WithMetaKV adds multiple key-value pairs to the meta map in a variadic manner. Expects arguments in pairs: key1 (string), value1 (interface{}), key2, value2, etc. Skips invalid pairs where key is not a string. Returns a new Renderer with the updated metadata.
func (*Renderer) WithProtocol ¶
WithProtocol sets the protocol handler for the Renderer. Assigns the provided Protocol interface for response output. Returns a new Renderer with the updated protocol handler.
func (*Renderer) WithRedactFilter ¶
WithRedactFilter adds filters that cause error messages to be masked in responses.
func (*Renderer) WithShowError ¶
WithShowError updates the error display configuration. Sets the State for controlling error output. Returns nil as no error conditions are currently defined.
func (*Renderer) WithShowSystem ¶
func (r *Renderer) WithShowSystem(show SystemShow) *Renderer
WithShowSystem updates the system metadata display configuration. Sets the SystemShow mode for controlling metadata output. Returns a new Renderer with the updated showSystem.
func (*Renderer) WithSingle ¶
WithSingle adds an action to the Renderer's response. Appends a new Action with the provided name and description. Returns a new Renderer with the updated actions.
func (*Renderer) WithSkipFilter ¶
WithSkipFilter adds filters that cause errors to be omitted from non-fatal responses.
func (*Renderer) WithStatus ¶
WithStatus sets the HTTP status code for the Renderer. Assigns the provided HTTP status code (e.g., http.StatusOK). Returns a new Renderer with the updated status code.
func (*Renderer) WithSystem ¶
func (r *Renderer) WithSystem(show SystemShow, sys System) *Renderer
WithSystem configures system metadata display for the Renderer. Sets the SystemShow mode and System struct for metadata inclusion. Returns a new Renderer with updated system settings.
func (*Renderer) WithTag ¶
WithTag adds tags to the Renderer. Appends the provided tags to the tags slice. Returns a new Renderer with the updated tags.
func (*Renderer) WithTitle ¶
WithTitle sets the title for the Renderer. Assigns the provided string title for the response. Returns a new Renderer with the updated title.
func (*Renderer) WithWriter ¶
WithWriter sets the default writer for the Renderer. Assigns the provided Writer and sets httpWriter if applicable. Returns a new Renderer with updated writer fields.
type Response ¶
type Response struct {
Status string `json:"status" xml:"status" msgpack:"status"`
Title string `json:"title,omitempty" xml:"title,omitempty" msgpack:"title"`
Message string `json:"message,omitempty" xml:"message,omitempty" msgpack:"message"`
Tags []string `json:"tags,omitempty" xml:"tags,omitempty" msgpack:"tags"`
Info interface{} `json:"info,omitempty" xml:"info,omitempty" msgpack:"info"`
Data interface{} `json:"data,omitempty" xml:"data,omitempty" msgpack:"data"`
Meta map[string]interface{} `json:"meta,omitempty" xml:"meta,omitempty" msgpack:"meta"`
Errors ErrorList `json:"errors,omitempty" xml:"errors,omitempty" msgpack:"errors"`
Actions []Action `json:"actions,omitempty" xml:"actions,omitempty" msgpack:"actions"`
}
Response is the standard response structure. Contains fields for status, message, data, and errors. Used by Renderer to structure response output.
type Setting ¶
type Setting struct {
Name string
ContentType string
EnableHeaders bool // Enable sending headers (default true)
Presets map[string]Preset // Custom presets for content types
}
Setting configures the renderer. Holds configuration like content type and header settings. Used to initialize Renderer with specific options.
type System ¶
type System struct {
App string `json:"app" xml:"App"`
Server string `json:"server,omitempty" xml:"Server,omitempty"`
Version string `json:"version,omitempty" xml:"Version,omitempty"`
Build string `json:"build,omitempty" xml:"Build,omitempty"`
Play bool `json:"play,omitempty" xml:"Play,omitempty"`
Duration time.Duration `json:"duration" xml:"Duration"`
}
System holds system metadata and display preferences. Stores metadata like app name, version, and duration. Used to include system information in responses.
func (System) MarshalJSON ¶
MarshalJSON provides a custom JSON encoding for System. Encodes the System struct with duration as a string. Returns the JSON-encoded bytes or an error if encoding fails.
func (System) MarshalXML ¶
MarshalXML provides a custom XML encoding for System. Encodes the System struct with duration as a string. Returns an error if XML encoding fails.
type SystemShow ¶
type SystemShow int
SystemShow defines modes for displaying system metadata in responses. It controls whether metadata appears in headers, body, both, or neither.
const ( SystemShowNone SystemShow = iota // No metadata in headers or body SystemShowHeaders // Metadata in headers only SystemShowBody // Metadata in response body only SystemShowBoth // Metadata in both headers and body )
SystemShow constants specify metadata display modes for Renderer configuration.
type TCPProtocol ¶
type TCPProtocol struct{}
TCPProtocol implements a basic TCP protocol. Provides TCP-specific header application (currently a no-op). Suitable for protocols without header requirements.
func (*TCPProtocol) ApplyHeaders ¶
func (p *TCPProtocol) ApplyHeaders(w Writer, code int) error
ApplyHeaders applies TCP-specific headers (none in this basic implementation). Takes a Writer and HTTP status code (ignored for TCP). Returns nil as TCP does not use headers in this implementation.
type TextEncoder ¶
type TextEncoder struct{}
func (*TextEncoder) ContentType ¶
func (e *TextEncoder) ContentType() string
ContentType returns the text content type. Returns the constant "text/plain". Used by EncoderRegistry to map this encoder. No side effects or parameters.
func (*TextEncoder) Marshal ¶
func (e *TextEncoder) Marshal(v interface{}) ([]byte, error)
Marshal converts data to plain text using a pooled buffer. Takes any data and formats it as a string using fmt.Sprintf. Returns the text as bytes or an error if formatting fails. Uses a pooled buffer to reduce memory allocations.
func (*TextEncoder) Unmarshal ¶
func (e *TextEncoder) Unmarshal(data []byte, v interface{}) error
Unmarshal is a no-op for text encoding. Takes a byte slice and a target variable (ignored). Always returns nil, as text decoding is not supported. No side effects or buffer usage.
type Writer ¶
Writer defines the interface for output destinations. Provides a method to write byte data to an output. Used by Renderer to send responses to clients.
type XMLEncoder ¶
type XMLEncoder struct{}
func (*XMLEncoder) ContentType ¶
func (e *XMLEncoder) ContentType() string
ContentType returns the XML content type. Returns the constant "application/xml". Used by EncoderRegistry to map this encoder. No side effects or parameters.
func (*XMLEncoder) Marshal ¶
func (e *XMLEncoder) Marshal(v interface{}) ([]byte, error)
Marshal encodes data to XML format, handling Response and map types specially. Takes any XML-serializable data, with special handling for Response and maps. Returns the encoded XML bytes or an error if encoding fails. Uses a pooled buffer for general encoding and specific methods for Response/maps.
func (*XMLEncoder) Unmarshal ¶
func (e *XMLEncoder) Unmarshal(data []byte, v interface{}) error
Unmarshal decodes XML data into the provided pointer. Takes a byte slice and a pointer to the target variable. Returns an error if decoding fails. Uses standard xml.Unmarshal without buffer pooling.