httpx

package
v0.0.2-beta.3 Latest Latest
Warning

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

Go to latest
Published: Dec 15, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AbortWithJsonError

func AbortWithJsonError(ctx Context, err error)

AbortWithJsonError terminates the request with a JSON error response. It uses the configured error parser to extract error details and ensures the HTTP status code is valid (200-599 range).

func Close

func Close(ctx context.Context, server *http.Server) error

Close gracefully shuts down the HTTP server using the provided context. It handles nil server gracefully and returns any shutdown error.

func EndpointsToMatches

func EndpointsToMatches(base string, endpoints ...[][3]string) map[string]map[string]string

func Fs

func Fs(local string, files fs.FS, emPath string) (fs.FS, error)

Fs create a fs.FS from either a local directory or an embedded filesystem. Priority:

  1. local directory (if it exists)
  2. embedded filesystem + emPath

func ListenAndAutoShutdown

func ListenAndAutoShutdown(ctx context.Context, server *http.Server, closeTimeout time.Duration) error

ListenAndAutoShutdown starts an HTTP server and automatically handles graceful shutdown. It listens for context cancellation to trigger shutdown with the specified timeout. Returns any error from server startup or shutdown, prioritizing startup errors.

func MatchOperation

func MatchOperation(base string, endpoints [][3]string, operations ...string) func(ctx Context) bool

func ParseError

func ParseError(err error) (code int32, status int32, message string)

ParseError extracts error information from various error types. It recognizes StatusError, CodeError, and MessageError interfaces and falls back to defaults for unknown error types.

func SetDefaultErrorParser

func SetDefaultErrorParser(parser ErrorParser)

SetDefaultErrorParser sets the global error parser function for the package. This parser will be used by AbortWithJsonError when no specific parser is provided.

func Start

func Start(server *http.Server) error

Start begins serving HTTP requests on the configured address. It ignores http.ErrServerClosed which is expected during graceful shutdown. Returns any other error that occurs during server startup.

func Value

func Value[T any](ctx Context, key string) (T, bool)

Value retrieves a typed value from the Gin context. It returns the value and a boolean indicating whether the key exists and the type matches.

Types

type Aborter

type Aborter interface {
	Abort()
	AbortWithStatus(code int)
	AbortWithStatusError(code int, err error)
	AbortWithStatusJSON(code int, obj interface{})
	IsAborted() bool
}

Aborter allows a handler to short-circuit the remaining chain.

type Binder

type Binder interface {
	BindJSON(dst any) error
	BindQuery(dst any) error
	BindForm(dst any) error
	BindURI(dst any) error
	BindHeader(dst any) error
}

Binder standardizes payload decoding across frameworks.

type Config

type Config[E any] struct {
	ErrorHandler ErrorHandler
	Middleware   MiddlewareChain
	Engine       E // framework-specific passthrough (e.g., *gin.Engine, *fiber.App, *echo.Echo, *chi.Mux)
}

Config controls router adapter creation.

func NewConfig

func NewConfig[E any](opts ...Option[E]) *Config[E]

NewConfig builds a Config with the given options.

func (*Config[E]) Apply

func (c *Config[E]) Apply(opts ...Option[E])

Apply iterates through the provided options and applies each non-nil option to the Config instance.

type Context

Context is the cross-framework surface passed into handlers.

type DataResponse

type DataResponse[T any] struct {
	Success bool `json:"success" default:"true"`
	Code    int  `json:"code,omitempty" default:"0"`
	Data    T    `json:"data"`
}

DataResponse represents a successful API response containing typed data. It follows a standard structure for consistent API responses across the application.

type Engine

type Engine interface {
	MiddlewareScope
	Start() error
	Stop(ctx context.Context) error
	Group(prefix string, m ...Middleware) Router
}

Engine is the entrypoint: it can serve HTTP, apply global middleware, and create groups, but cannot register routes directly.

type ErrorHandler

type ErrorHandler func(Context, error)

ErrorHandler receives the terminal error from a Handler.

type ErrorParser

type ErrorParser func(error) (int32, int32, string)

ErrorParser is a function type that extracts error information for HTTP responses. It returns the error code, HTTP status code, and user-friendly message from an error.

type ErrorResponse

type ErrorResponse struct {
	Success bool   `json:"success" default:"false"`
	Code    int    `json:"code" default:"0"`
	Error   string `json:"error,omitempty"`
	Message string `json:"message,omitempty"`
}

ErrorResponse represents an API error response with error details. It provides both error and message fields for different levels of error information.

type H

type H map[string]any

type Handler

type Handler func(Context) error

Handler is the canonical function signature for framework adapters.

func ApplyMiddleware

func ApplyMiddleware(h Handler, m ...Middleware) Handler

ApplyMiddleware wraps h with the provided middleware in declaration order.

func WithFormFileBytes

func WithFormFileBytes[T any](handler func(ctx Context, file []byte, filename string) (*T, error), options ...WithFormOption) Handler

WithFormFileBytes creates a Gin handler that processes uploaded files as byte arrays. It reads the entire file content into memory and passes it to the handler function. This is convenient for smaller files but should be used carefully with large files.

func WithFormFileReader

func WithFormFileReader[T any](handler func(ctx Context, file io.ReadSeekCloser, filename string) (*T, error), options ...WithFormOption) Handler

WithFormFileReader creates a Gin handler that processes uploaded files as io.ReadSeekCloser. It validates file size, extension constraints, and passes the file content to the handler function. The handler receives the file as an io.Reader along with the original filename.

func WithJson

func WithJson[T any](handler func(ctx Context) (T, error)) Handler

WithJson creates a Gin handler that returns JSON responses for typed data. It automatically handles errors by calling AbortWithJsonError and wraps successful responses in a standardized DataResponse structure.

func WithRecover

func WithRecover(message string, handler func(ctx Context) error) Handler

WithRecover wraps a Gin handler with panic recovery. If a panic occurs, it logs the error and returns a standardized internal server error response.

func WithText

func WithText(handler func(ctx Context) (string, error)) Handler

WithText creates a Gin handler that returns plain text responses. It handles errors by calling AbortWithJsonError and returns successful string responses with HTTP 200 status.

type Middleware

type Middleware func(Handler) Handler

Middleware wraps a Handler with cross-cutting behavior (logging, tracing, etc).

func ComposeMiddleware

func ComposeMiddleware(m ...Middleware) Middleware

ComposeMiddleware flattens multiple middleware into one.

type MiddlewareChain

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

MiddlewareChain manages ordered middleware application.

func NewMiddlewareChain

func NewMiddlewareChain(m ...Middleware) *MiddlewareChain

NewMiddlewareChain creates a chain with the given middleware.

func (*MiddlewareChain) Clone

func (m *MiddlewareChain) Clone() *MiddlewareChain

Clone returns a copy of the chain that can be mutated independently.

func (*MiddlewareChain) Middlewares

func (m *MiddlewareChain) Middlewares() []Middleware

Middlewares returns a defensive copy of the underlying chain.

func (*MiddlewareChain) Then

func (m *MiddlewareChain) Then(h Handler) Handler

Then applies the chain to a Handler in order (first middleware runs first).

func (*MiddlewareChain) Use

func (m *MiddlewareChain) Use(mm ...Middleware)

Use appends middleware in call order.

func (*MiddlewareChain) Wrap

func (m *MiddlewareChain) Wrap() Middleware

Wrap collapses the chain into single middleware.

type MiddlewareOrder

type MiddlewareOrder int
const (
	MiddlewareBeforeNext MiddlewareOrder = iota
	MiddlewareAfterNext
)

type MiddlewareScope

type MiddlewareScope interface {
	Use(...Middleware)
}

MiddlewareScope attaches middleware to the current scope.

type Option

type Option[E any] func(*Config[E])

Option defines a functional option for configuring a Config instance.

func WithEngine

func WithEngine[E any](engine E) Option[E]

WithEngine passes a framework-native engine into the factory.

func WithErrorHandler

func WithErrorHandler[E any](h ErrorHandler) Option[E]

WithErrorHandler installs a terminal error handler.

func WithMiddleware

func WithMiddleware[E any](m ...Middleware) Option[E]

WithMiddleware appends global middleware.

type Registrar

type Registrar interface {
	Handle(method, path string, h Handler)
	Any(path string, h Handler)
	Static(prefix, root string)
	StaticFS(prefix string, fs fs.FS)
}

Registrar registers handlers on a router scope.

type Request

type Request interface {
	Method() string
	Path() string
	FullPath() string // best-effort; empty if unsupported
	ClientIP() string

	Param(key string) string
	Params() map[string]string

	Query(key string) string
	Queries() map[string][]string
	RawQuery() string

	FormValue(key string) string
	FormValues() map[string][]string
	FormFile(name string) (*multipart.FileHeader, error)

	GetBodyRaw() ([]byte, error)

	Header(key string) string
	Cookie(name string) (string, error)
}

Request exposes a common, read-only view over incoming HTTP requests.

type Responder

type Responder interface {
	Status(code int)

	JSON(code int, v any)
	Text(code int, s string)
	Bytes(code int, b []byte, contentType string)
	DataFromReader(code int, contentType string, r io.Reader, size int)
	File(path string)
	Redirect(code int, location string)

	SetHeader(key, value string)
	SetCookie(cookie *http.Cookie)
}

Responder writes responses across frameworks.

type Router

type Router interface {
	MiddlewareScope
	Registrar
	Group(prefix string, m ...Middleware) Router
}

Router is a full-featured route scope.

type StateStore

type StateStore interface {
	Set(key string, val any)
	Get(key string) (any, bool)
}

StateStore carries request-scoped values.

type WithFormOption

type WithFormOption func(*WithFormOptions)

WithFormOption is a functional option for configuring file upload behavior.

func WithFormAllowExtensions

func WithFormAllowExtensions(extensions ...string) WithFormOption

WithFormAllowExtensions restricts file uploads to specific file extensions. Extensions are matched case-insensitively. If no extensions are provided, all file types are allowed.

func WithFormFileKey

func WithFormFileKey(key string) WithFormOption

WithFormFileKey sets the form field name for file uploads. The default field name is "file".

func WithFormMaxSize

func WithFormMaxSize(maxSize int64) WithFormOption

WithFormMaxSize sets the maximum file size allowed for uploads. The size is specified in bytes.

type WithFormOptions

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

WithFormOptions contains configuration for file upload handling via multipart forms.

Jump to

Keyboard shortcuts

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