beam

package module
v0.0.0-...-f5e3533 Latest Latest
Warning

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

Go to latest
Published: Oct 2, 2025 License: MIT Imports: 23 Imported by: 0

README

Beam - Flexible Response Rendering for Go

Go Reference Go Report Card Tests License

Beam is a high-performance Go package for streamlined API response generation. It emphasizes flexibility, consistency, and a first-class developer experience with a powerful, modern error handling system. It supports multiple formats, efficient streaming, and helps you build robust, scalable web services with ease.

Upgrading? This version introduces a powerful new error handling API and other enhancements. Please see the Migration Guide for details on breaking changes.

Table of Contents

Features

  • Powerful Error Handling: Granular control to Skip, Redact, or Convert errors.
  • Leveled Logging: Structured Error and Fatal logging with automatic caller info (file, line, function).
  • Sensitive Data Protection: Automatically redact sensitive error details in responses while keeping them in logs.
  • Request Parsing: Built-in helpers (r.JSON, r.XML, etc.) for easy request body decoding.
  • Multi-format Support: JSON, XML, MsgPack, text, binary, and images (PNG, JPEG, GIF, WebP).
  • HATEOAS Support: Add Actions to your responses to guide API clients.
  • Efficient Streaming: Handle large datasets with minimal memory usage via r.Stream().
  • Context-Aware: Integrates with Go’s context package for cancellation and timeouts.
  • Extensible: Add custom encoders for any format (e.g., CSV, Protobuf).
  • Memory Optimized: Uses sync.Pool for response objects and buffers to reduce GC pressure.

Installation

go get github.com/olekukonko/beam

Quick Start

Create a simple HTTP server that returns a structured JSON response.

package main

import (
	"net/http"
	"github.com/olekukonko/beam"
)

func main() {
	// Initialize a renderer. It's safe for concurrent use.
	renderer := beam.NewRenderer(beam.Setting{
		Name: "myapp",
	})

	// Define an HTTP handler using Beam's helper
	http.Handle("/users/1", renderer.Handler(func(r *beam.Renderer) error {
		// Define the data to be sent
		user := map[string]string{"id": "1", "name": "Alice"}
		
		// Send a successful response with a message and data payload
		return r.Data("User found successfully", user)
	}))

	// Start the server
	http.ListenAndServe(":8080", nil)
}

Output (at http://localhost:8080/users/1):

{
    "status": "+ok",
    "message": "User found successfully",
    "data": {
        "id": "1",
        "name": "Alice"
    }
}

Core Concepts

The Renderer

The *beam.Renderer is the heart of the library. It's an immutable builder for your responses. Every call to a With... method (e.g., r.WithStatus(404)) returns a new copy of the renderer with the change applied. This makes it safe to pass around and use concurrently without worrying about race conditions.

// Start with a base renderer
baseRenderer := beam.NewRenderer(beam.Setting{Name: "api"})

// Create a specialized renderer for a specific handler
func myHandler(w http.ResponseWriter, req *http.Request) {
    // Each request gets its own configured renderer
    r := baseRenderer.WithWriter(w).WithContext(req.Context())
    
    // This renderer is configured for XML output, but the baseRenderer remains unchanged
    xmlRenderer := r.WithContentType(beam.ContentTypeXML)
    xmlRenderer.Msg("Hello from XML!")
}
Response Structure

Beam uses a consistent Response struct for all structured outputs, ensuring your API is predictable.

type Response struct {
    Status  string                 `json:"status"`
    Title   string                 `json:"title,omitempty"`
    Message string                 `json:"message,omitempty"`
    Tags    []string               `json:"tags,omitempty"`
    Info    interface{}            `json:"info,omitempty"`
    Data    interface{}            `json:"data,omitempty"`
    Meta    map[string]interface{} `json:"meta,omitempty"`
    Errors  ErrorList              `json:"errors,omitempty"`
    Actions []Action               `json:"actions,omitempty"` // For HATEOAS
}

Advanced Error Handling

This is where Beam truly shines. It provides a sophisticated system for managing errors gracefully and securely.

Error, Warning, and Fatal Responses

The API offers a clear distinction between error severities.

// A standard, non-fatal error (HTTP 400 Bad Request)
if err != nil {
    return r.Errorf("Validation failed for user %s: %w", userID, err)
}

// A warning that doesn't halt the entire process
r.Warningf("Cache miss for key: %s", cacheKey)

// A critical, fatal error (HTTP 500 Internal Server Error)
// This will also log the error with stack context if a logger is configured.
if err != nil {
    return r.FatalMsg("Failed to connect to database", err)
}
Filtering and Transforming Errors

Configure the renderer to globally Skip, Redact, or Convert certain errors.

renderer := beam.NewRenderer(beam.Setting{}).
    // 1. Skip: Don't treat `sql.ErrNoRows` as an error for the client.
    WithSkipFilter(func(err error) bool {
        return errors.Is(err, sql.ErrNoRows)
    }).
    // 2. Redact: Hide details of a specific error type.
    WithRedactFilter(func(err error) bool {
        return errors.Is(err, &MySensitiveError{})
    }).
    // 3. Convert: Treat a specific error as non-fatal, even in r.Fatal().
    WithConvertFilter(func(err error) error {
        if errors.Is(err, &NonCriticalDBError{}) {
            return beam.ToNormal(err) // Downgrade severity
        }
        return err
    })

// This call will now do nothing and return `nil`, because the filter skips it.
r.Error(sql.ErrNoRows) 
Redacting Sensitive Errors

To prevent leaking sensitive information, wrap an error with beam.ErrHidden. The details will be masked in the API response but fully visible in your logs.

// The original error contains sensitive info
authErr := errors.New("invalid password for user 'admin'")

// Wrap it to redact the output
err := fmt.Errorf("auth failed: %w", beam.ErrHidden)

r.ErrorMsg("Login failed", authErr)

JSON Output:

{
    "status": "-error",
    "message": "Login failed",
    "errors": [
        "inva [REDACTED]"
    ]
}
Controlling Error Severity

You can dynamically change an error's severity using beam.ToFatal and beam.ToNormal.

// Even though we call r.Error(), this will be treated as a fatal error
// because we've wrapped it with ToFatal.
r.Error(beam.ToFatal(errors.New("corruption detected")))

Parsing Request Bodies

Beam integrates the hauler package to provide simple helpers for decoding request bodies.

func CreateUser(r *beam.Renderer, req *http.Request) error {
    var user User
    // Automatically decodes JSON, XML, MsgPack, etc., based on Content-Type
    if err := r.Request(req, &user); err != nil {
        return r.Errorf("Invalid request body: %w", err)
    }

    // Or use a specific parser
    if err := r.JSON(req, &user); err != nil {
        return r.Errorf("Invalid JSON: %w", err)
    }

    // ... process user ...
    return r.Msg("User created")
}

Advanced Usage

Streaming Data

Stream large datasets like CSV files or logs without consuming excessive memory.

func exportUsers(r *beam.Renderer) error {
    // Set headers for file download
    r = r.WithContentType("text/csv").
        WithHeader("Content-Disposition", "attachment; filename=users.csv")

    // The callback is called repeatedly until it returns io.EOF
    return r.Stream(func(renderer *beam.Renderer) (interface{}, error) {
        users, err := getNextBatchOfUsers() // Your function to get data chunks
        if err == io.EOF {
            return nil, io.EOF // Signal end of stream
        }
        if err != nil {
            return nil, err // Propagate errors
        }
        return convertUsersToCSV(users), nil
    })
}```

### Response Actions (HATEOAS)

Guide your API clients by telling them what actions they can perform next.

```go
r.WithAction(beam.Action{
    Name:   "view-profile",
    Method: "GET",
    Href:   "/api/users/123",
}, beam.Action{
    Name:   "update-profile",
    Method: "PUT",
    Href:   "/api/users/123",
}).Data("User logged in", user)

JSON Output:

{
    "status": "+ok",
    "message": "User logged in",
    "data": { "...": "..." },
    "actions": [
        { "name": "view-profile", "method": "GET", "href": "/api/users/123" },
        { "name": "update-profile", "method": "PUT", "href": "/api/users/123" }
    ]
}
System Metadata

Include application metadata in headers, the response body, or both.

renderer := beam.NewRenderer(beam.Setting{}).
    WithSystem(beam.SystemShowBoth, beam.System{
        App:     "MyApp",
        Version: "1.2.3",
        Build:   "abcdef",
    })

// This will add X-MyApp-Version headers AND a "system" object in the JSON body.
renderer.Msg("Ready")
Custom Encoders

Beam is fully extensible. Add support for any format by implementing the Encoder interface.

type CSVEncoder struct{}
func (e *CSVEncoder) Marshal(v interface{}) ([]byte, error) { /* ... */ }
func (e *CSVEncoder) Unmarshal(data []byte, v interface{}) error { /* ... */ }
func (e *CSVEncoder) ContentType() string { return "text/csv" }

// Register and use it
renderer.UseEncoder(&CSVEncoder{}).
    WithContentType("text/csv").
    Raw("id,name\n1,alice")
Context Support

All operations respect context.Context for handling cancellations and deadlines.

ctx, cancel := context.WithTimeout(req.Context(), 2*time.Second)
defer cancel()

// If the context expires, the Push operation will return ErrContextCanceled
err := r.WithContext(ctx).Push(w, response)

Full Application Example

Here is a complete example using the chi router and showcasing advanced features like logging, error handling, and request parsing.

package main

import (
	"errors"
	"fmt"
	"net/http"

	"github.com/go-chi/chi/v5"
	"github.com/olekukonko/beam"
)

// A simple structured logger
type AppLogger struct{}
func (l *AppLogger) Error(err error, fields ...interface{}) { 
    fmt.Println("[ERROR]", err, fields) 
}
func (l *AppLogger) Fatal(err error, fields ...interface{}) { 
    fmt.Println("[FATAL]", err, fields)
}

func main() {
	// 1. Initialize a base renderer with global settings
	renderer := beam.NewRenderer(beam.Setting{Name: "beam-app"}).
		WithLogger(&AppLogger{}).
		WithSystem(beam.SystemShowBody, beam.System{
			App: "MyAwesomeApp", Version: "1.0.0",
		})

	r := chi.NewRouter()

	// 2. Handle successful requests
	r.Get("/hello", renderer.Handler(func(r *beam.Renderer) error {
		return r.Info("Hello, world!", map[string]string{"greeting": "Hi!"})
	}))

	// 3. Handle requests with potential errors
	r.Get("/users/{id}", renderer.Handler(func(r *beam.Renderer) error {
		// This error would be logged as fatal
		return r.Fatal(errors.New("database connection failed"))
	}))

    // 4. Handle request body parsing
    type CreateRequest struct { Name string `json:"name"` }
    r.Post("/users", renderer.Handler(func(r *beam.Renderer) error {
        var reqData CreateRequest
        // Use the built-in JSON parser
        if err := r.JSON(chi.RequestFromContext(r.ctx), &reqData); err != nil {
            // Send a 400 Bad Request for invalid input
            return r.Errorf("Invalid user data: %w", err)
        }
        return r.Msgf("User '%s' created!", reqData.Name)
    }))

	fmt.Println("Server listening on :4040")
	http.ListenAndServe(":4040", r)
}

Contributing

Contributions are welcome! Please fork the repository, create a feature branch, and submit a pull request with clear descriptions and tests. See CONTRIBUTING.md for more details.

License

Beam is licensed under the MIT License. See LICENSE for details.

Documentation

Index

Constants

View Source
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.

View Source
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.

View Source
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.

View Source
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"
)
View Source
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

View Source
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.

View Source
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.

func ToFatal

func ToFatal(err error) error

ToFatal wraps an error to mark it as fatal. Returns a fatalError wrapping the provided error.

func ToNormal

func ToNormal(err error) error

ToNormal wraps an error to mark it as non-fatal. Returns a normalError wrapping the provided error.

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

type EncoderError struct {
	OriginalError error
	ContentType   string
	FallbackData  []byte
}

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

func (el ErrorList) MarshalJSON() ([]byte, error)

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

func (el *ErrorList) UnmarshalJSON(data []byte) error

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

type Finalizer func(w Writer, err error)

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

type Preset struct {
	ContentType string
	Headers     http.Header
}

Preset defines a preset for custom content types. Specifies content type and associated headers. Used in Setting to customize response headers.

type Protocol

type Protocol interface {
	ApplyHeaders(w Writer, code int) error
}

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

func NewRenderer(s Setting) *Renderer

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

func (r *Renderer) Binary(contentType string, data []byte) error

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

func (r *Renderer) Data(msg string, data interface{}) error

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

func (r *Renderer) Error(errs ...error) 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

func (r *Renderer) ErrorInfo(message string, info interface{}, errs ...error) error

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

func (r *Renderer) ErrorMsg(message string, errs ...error) error

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

func (r *Renderer) Errorf(format string, args ...interface{}) error

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

func (r *Renderer) Fatal(errs ...error) error

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

func (r *Renderer) FatalInfo(message string, info interface{}, errs ...error) error

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

func (r *Renderer) FatalMsg(message string, errs ...error) error

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

func (r *Renderer) Fatalf(format string, args ...interface{}) error

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

func (r *Renderer) Form(req *http.Request, v interface{}) error

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

func (r *Renderer) Image(contentType string, img image.Image) error

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

func (r *Renderer) Info(msg string, info interface{}) error

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

func (r *Renderer) JSON(req *http.Request, v interface{}) error

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

func (r *Renderer) Log(err error)

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

func (r *Renderer) Logf(format string, args ...interface{})

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

func (r *Renderer) Msg(msg string) error

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

func (r *Renderer) MsgPack(req *http.Request, v interface{}) error

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

func (r *Renderer) Msgf(format string, args ...interface{}) error

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

func (r *Renderer) Pending(msg string, info interface{}) error

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

func (r *Renderer) Push(w Writer, d Response) error

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

func (r *Renderer) Pusher(contentType string, data io.Reader) error

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

func (r *Renderer) Raw(data interface{}) error

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

func (r *Renderer) Reader() *hauler.Hauler

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

func (r *Renderer) Relay(data interface{}) error

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

func (r *Renderer) Request(req *http.Request, v interface{}) error

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

func (r *Renderer) Response(msg string, info interface{}, data interface{}) error

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

func (r *Renderer) Rest(data interface{}) error

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

func (r *Renderer) Send(msg string, info interface{}) error

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

func (r *Renderer) Stream(callback func(*Renderer) (interface{}, error)) error

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

func (r *Renderer) Titled(title, msg string, info interface{}) error

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

func (r *Renderer) UseEncoder(e Encoder) *Renderer

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

func (r *Renderer) Warning(errs ...error) error

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

func (r *Renderer) Warningf(format string, args ...interface{}) error

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

func (r *Renderer) WithAction(actions ...Action) *Renderer

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

func (r *Renderer) WithActions(actions []Action) *Renderer

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

func (r *Renderer) WithContentType(contentType string) *Renderer

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

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

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

func (r *Renderer) WithConvertFilter(filters ...func(error) error) *Renderer

WithConvertFilter adds filters that can transform an error, e.g., to change its severity.

func (*Renderer) WithErrorHeader

func (r *Renderer) WithErrorHeader(key string) *Renderer

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

func (r *Renderer) WithFinalizer(f Finalizer) *Renderer

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

func (r *Renderer) WithHeader(key, value string) *Renderer

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

func (r *Renderer) WithHeaders(kv ...string) *Renderer

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

func (r *Renderer) WithHeadersEnabled(enabled bool) *Renderer

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

func (r *Renderer) WithID(id string) *Renderer

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

func (r *Renderer) WithIDGeneration(enabled State) *Renderer

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

func (r *Renderer) WithLogger(l Logger) *Renderer

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

func (r *Renderer) WithMeta(key string, value interface{}) *Renderer

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

func (r *Renderer) WithMetaKV(kvs ...interface{}) *Renderer

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

func (r *Renderer) WithProtocol(p Protocol) *Renderer

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

func (r *Renderer) WithRedactFilter(filters ...func(error) bool) *Renderer

WithRedactFilter adds filters that cause error messages to be masked in responses.

func (*Renderer) WithShowError

func (r *Renderer) WithShowError(show State) error

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

func (r *Renderer) WithSingle(name, description string) *Renderer

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

func (r *Renderer) WithSkipFilter(filters ...func(error) bool) *Renderer

WithSkipFilter adds filters that cause errors to be omitted from non-fatal responses.

func (*Renderer) WithStatus

func (r *Renderer) WithStatus(code int) *Renderer

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

func (r *Renderer) WithTag(tags ...string) *Renderer

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

func (r *Renderer) WithTitle(t string) *Renderer

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

func (r *Renderer) WithWriter(w Writer) *Renderer

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.

func (*Renderer) XML

func (r *Renderer) XML(req *http.Request, v interface{}) error

XML reads and parses an XML request body into the provided value. Verifies the Content-Type is XML and delegates to Request. Returns an error if the request is nil, content type is invalid, or parsing fails.

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 State

type State int

func (State) Default

func (o State) Default() bool

Default checks if the state is unknown

func (State) Disabled

func (o State) Disabled() bool

Disabled checks if the state is off

func (State) Enabled

func (o State) Enabled() bool

Enabled checks if the state is on

func (State) On

func (o State) On(f func())

type Streamer

type Streamer interface {
	Stream(w Writer, callback func() (interface{}, error)) error
}

Streamer defines an optional interface for streaming data.

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

func (s System) MarshalJSON() ([]byte, error)

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

func (s System) MarshalXML(e *xml.Encoder, start xml.StartElement) error

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

type Writer interface {
	Write(data []byte) (int, error)
}

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.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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