Documentation
¶
Index ¶
- func AbortWithJsonError(ctx Context, err error)
- func Close(ctx context.Context, server *http.Server) error
- func EndpointsToMatches(base string, endpoints ...[][3]string) map[string]map[string]string
- func Fs(local string, files fs.FS, emPath string) (fs.FS, error)
- func ListenAndAutoShutdown(ctx context.Context, server *http.Server, closeTimeout time.Duration) error
- func MatchOperation(base string, endpoints [][3]string, operations ...string) func(ctx Context) bool
- func ParseError(err error) (code int32, status int32, message string)
- func SetDefaultErrorParser(parser ErrorParser)
- func Start(server *http.Server) error
- func Value[T any](ctx Context, key string) (T, bool)
- type Aborter
- type Binder
- type Config
- type Context
- type DataResponse
- type Engine
- type ErrorHandler
- type ErrorParser
- type ErrorResponse
- type H
- type Handler
- func ApplyMiddleware(h Handler, m ...Middleware) Handler
- func WithFormFileBytes[T any](handler func(ctx Context, file []byte, filename string) (*T, error), ...) Handler
- func WithFormFileReader[T any](handler func(ctx Context, file io.ReadSeekCloser, filename string) (*T, error), ...) Handler
- func WithJson[T any](handler func(ctx Context) (T, error)) Handler
- func WithRecover(message string, handler func(ctx Context) error) Handler
- func WithText(handler func(ctx Context) (string, error)) Handler
- type Middleware
- type MiddlewareChain
- type MiddlewareOrder
- type MiddlewareScope
- type Option
- type Registrar
- type Request
- type Responder
- type Router
- type StateStore
- type WithFormOption
- type WithFormOptions
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AbortWithJsonError ¶
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 ¶
Close gracefully shuts down the HTTP server using the provided context. It handles nil server gracefully and returns any shutdown error.
func EndpointsToMatches ¶
func Fs ¶
Fs create a fs.FS from either a local directory or an embedded filesystem. Priority:
- local directory (if it exists)
- 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 ParseError ¶
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.
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.
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 ¶
ErrorHandler receives the terminal error from a Handler.
type ErrorParser ¶
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 Handler ¶
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 ¶
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 ¶
WithRecover wraps a Gin handler with panic recovery. If a panic occurs, it logs the error and returns a standardized internal server error response.
type Middleware ¶
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 ¶
Option defines a functional option for configuring a Config instance.
func WithEngine ¶
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 ¶
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.