Documentation
¶
Index ¶
- Constants
- func BodyRead(r *http.Request, key string) (any, bool)
- func BodyReadStruct[T any](r *http.Request, data T) error
- func GetCaller(skip int) (string, int, bool)
- func GetData[T any](r *http.Request, key string, fb T) (T, error)
- func HasBody(r *http.Request) bool
- func LogError(w io.Writer, err error)
- func Patch(r *http.Request, key any, value any) *http.Request
- func PatchMap(r *http.Request, value JSON) *http.Request
- func PatchValue(r *http.Request, key string, value any) *http.Request
- func PrepareBody(r *http.Request) (*http.Request, error)
- func ReadFields(tp reflect.Type) []string
- func ReadValue[T any](tp reflect.Type, value any, fb T) (T, error)
- func RequestAddr(r *http.Request) net.Addr
- func StructToStruct(src any, data any) error
- func ValuesAs(w http.ResponseWriter, r *http.Request, data any, values ...ValueResolver) error
- func Walk(mux *http.ServeMux, cb WalkCallback, configs ...*WalkConfig)
- func WriteData(w io.Writer, data JSON) error
- func WriteError(w io.Writer, err error) error
- func WriteErrorMessage(w io.Writer, err string) error
- func WriteMessage(w io.Writer, msg string) error
- func WriteStats(mux *http.ServeMux, w io.Writer, configs ...*WalkConfig)
- type AsExportableResponse
- type AsLoggable
- type ContextValue
- type Handler
- type JSON
- type Middleware
- type MiddlewareWithError
- type MountableMux
- type MuxRouter
- func (g *MuxRouter) Handle(pattern string, handler http.Handler)
- func (g *MuxRouter) HandleFunc(pattern string, handler http.HandlerFunc)
- func (g MuxRouter) MountTo(target MountableMux)
- func (g *MuxRouter) Mux() *http.ServeMux
- func (g MuxRouter) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (g *MuxRouter) Use(hns ...NextHandler) *MuxRouter
- type NextHandler
- type ResponseError
- func (e *ResponseError) AsJSON() JSON
- func (e *ResponseError) Caller(skip int) *ResponseError
- func (e *ResponseError) Client() *ResponseError
- func (e *ResponseError) ClientMessage(m string) *ResponseError
- func (e ResponseError) Error() string
- func (e *ResponseError) ErrorCode(c string) *ResponseError
- func (e *ResponseError) Extras(d JSON) *ResponseError
- func (e ResponseError) Log(w io.Writer)
- func (e *ResponseError) Message() string
- func (e *ResponseError) Path(p string) *ResponseError
- func (e *ResponseError) Reason(r string) *ResponseError
- func (e ResponseError) ResponseJSON() JSON
- func (e ResponseError) ResponseStatus() int
- func (e *ResponseError) Server() *ResponseError
- func (e *ResponseError) Status(c int) *ResponseError
- type RouteStat
- type Value
- func Body[T any](field string) *Value[T]
- func Context[T any](key string) *Value[T]
- func Get[T any](field string) *Value[T]
- func HTTPContext() *Value[context.Context]
- func HTTPRequest() *Value[*http.Request]
- func HTTPResponseWriter() *Value[http.ResponseWriter]
- func Header[T any](field string) *Value[T]
- func NewValue[T any](field string, src ValueSource) *Value[T]
- func Path[T any](field string) *Value[T]
- func Reader[T any](cb func(http.ResponseWriter, *http.Request) (T, error)) *Value[T]
- func Struct[T any]() *Value[T]
- func StructFrom[T any](src ValueSource) *Value[T]
- func (v *Value[T]) Alias() string
- func (v *Value[T]) As(n string) *Value[T]
- func (v *Value[T]) Default() any
- func (v *Value[T]) Field() string
- func (v *Value[T]) Optional() *Value[T]
- func (v *Value[T]) Reader(cb func(http.ResponseWriter, *http.Request) (T, error)) *Value[T]
- func (v *Value[T]) Required() bool
- func (v Value[T]) Resolve(w http.ResponseWriter, r *http.Request) (any, error)
- func (v *Value[T]) Type() reflect.Type
- func (v *Value[T]) Validate(cb func(*http.Request, T) error) *Value[T]
- type ValueFailHandler
- type ValueResolver
- type ValueSource
- type WalkCallback
- type WalkConfig
Constants ¶
const ContentTypeJSON = "application/json"
ContentType of json
const ContentTypeMultipart = "multipart/form-data"
ContentType of multipart
const ContentTypeURLEncoded = "application/x-www-form-urlencoded"
ContentType of url encoded form
Variables ¶
This section is empty.
Functions ¶
func BodyReadStruct ¶
BodyReadStruct reads values from request body as struct
func PatchValue ¶
PatchValue writes key/value to default context data
func PrepareBody ¶
PrepareBody parses any body request
func ReadFields ¶
ReadFields retrieves all exported fields for the struct
func RequestAddr ¶
RequestAddr retrieves the requesting address info
func StructToStruct ¶
StructToStruct convert struct type
func ValuesAs ¶
func ValuesAs(w http.ResponseWriter, r *http.Request, data any, values ...ValueResolver) error
ValuesAs collects values and maps it to struct
func Walk ¶
func Walk(mux *http.ServeMux, cb WalkCallback, configs ...*WalkConfig)
Walk parses the *http.ServeMux using reflection to collect list of routes via callback WalkCallback
Route collection from nested *http.ServeMux isn't supported unless details are provided via WalkConfig
func WriteError ¶
WriteError writes [error] to io.Writer and tries to use AsExportableResponse when available
func WriteErrorMessage ¶
WriteError writes error message to io.Writer
func WriteMessage ¶ added in v0.1.0
WriteMessage writes message to io.Writer
func WriteStats ¶
func WriteStats(mux *http.ServeMux, w io.Writer, configs ...*WalkConfig)
WriteStats logs info of defined routes to io.Writer
Types ¶
type AsExportableResponse ¶
type AsExportableResponse interface {
// ResponseStatus returns the http status code
ResponseStatus() int
// ResponseJSON exports the error as json data
ResponseJSON() JSON
}
AsExportableResponse defines interface to export data for response
type AsLoggable ¶
AsLoggable defines interface to check if struct is loggable
type ContextValue ¶
type ContextValue int
ContextValue defines custom type for context.Context key
const ( ContextValueDefault ContextValue = iota // default context key for data ContextValueJSON )
type Handler ¶
type Handler struct {
Err error
// contains filtered or unexported fields
}
Handler defines struct for callback
func New ¶
func New(cb any, values ...ValueResolver) *Handler
New creates Handler for handling response and panics on invalid func signature
Example: reads query string 'name' and passes as func argument
mux.Handle("GET /hello", hndlor.New(func(name string) (hndlor.JSON, error) {
return hndlor.JSON{
"hello": name,
}, nil
}, hndlor.Get[string]("name")))
func (*Handler) Invalidate ¶
Invalidate verifies the provided function with requested values
func (*Handler) OnFail ¶
func (h *Handler) OnFail(cb ValueFailHandler) *Handler
OnFail defines callback when value resolve fails
type JSON ¶
JSON represents json data format
func GetAllData ¶
GetAllData retrieves saved JSON saved in default context data
func Values ¶
func Values(w http.ResponseWriter, r *http.Request, values ...ValueResolver) (JSON, error)
Values collects all provided values from *http.Request
type Middleware ¶
Middleware defines default function signature
type MiddlewareWithError ¶
MiddlewareWithError defines function signature with support for error capturing/response
type MountableMux ¶
MountableMux defines an interface to verify if it can handle requests
type MuxRouter ¶
type MuxRouter struct {
Path string
Middlewares []NextHandler
// contains filtered or unexported fields
}
MuxRouter defines a helper router
func (*MuxRouter) Handle ¶
Handle adds new request handler http.Handler
func (*MuxRouter) HandleFunc ¶
func (g *MuxRouter) HandleFunc(pattern string, handler http.HandlerFunc)
HandleFunc adds new request handler func http.HandlerFunc
func (MuxRouter) MountTo ¶
func (g MuxRouter) MountTo(target MountableMux)
MountTo attaches MuxRouter to parent MountableMux
func (*MuxRouter) Mux ¶
Get internal mux router *http.ServeMux
func (MuxRouter) ServeHTTP ¶
func (g MuxRouter) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServerHTTP server the response
func (*MuxRouter) Use ¶
func (g *MuxRouter) Use(hns ...NextHandler) *MuxRouter
Use adds NextHandler as middlewares for all routes
type NextHandler ¶
NextHandler defines function signature for next handler
func Chain ¶
func Chain(mds ...NextHandler) NextHandler
Chain accepts multiple NextHandler and builds new NextHandler as middleware
func Logger ¶
func Logger(lw any) NextHandler
Logger middleware builds handler to log every requests received
func MM ¶
func MM(fn MiddlewareWithError) NextHandler
MM creates a middleware wrapper around the handler with support for writing error response
func PrepareMux ¶
func PrepareMux() NextHandler
PrepareMux middleware parses request to create cache data as needed
type ResponseError ¶
type ResponseError struct {
// contains filtered or unexported fields
}
ResponseError defines struct with error message and extras
func Errorf ¶
func Errorf(format string, a ...any) *ResponseError
Errorf creates error with message and formatting options
func (*ResponseError) AsJSON ¶
func (e *ResponseError) AsJSON() JSON
AsJSON generates json data for export
func (*ResponseError) Caller ¶
func (e *ResponseError) Caller(skip int) *ResponseError
Caller reads caller info to error
func (*ResponseError) Client ¶
func (e *ResponseError) Client() *ResponseError
Client marks error as client side error
func (*ResponseError) ClientMessage ¶
func (e *ResponseError) ClientMessage(m string) *ResponseError
ClientMessage sets error message for exported server error
func (ResponseError) Error ¶
func (e ResponseError) Error() string
func (*ResponseError) ErrorCode ¶
func (e *ResponseError) ErrorCode(c string) *ResponseError
ErrorCode updates primary error code
func (*ResponseError) Extras ¶
func (e *ResponseError) Extras(d JSON) *ResponseError
Data updates the extra data for response
func (ResponseError) Log ¶
func (e ResponseError) Log(w io.Writer)
func (*ResponseError) Message ¶
func (e *ResponseError) Message() string
Message returns underlying error message
func (*ResponseError) Path ¶
func (e *ResponseError) Path(p string) *ResponseError
Path updates the request path info
func (*ResponseError) Reason ¶
func (e *ResponseError) Reason(r string) *ResponseError
Reason updates the reason of error
func (ResponseError) ResponseJSON ¶
func (e ResponseError) ResponseJSON() JSON
func (ResponseError) ResponseStatus ¶
func (e ResponseError) ResponseStatus() int
func (*ResponseError) Server ¶
func (e *ResponseError) Server() *ResponseError
Server marks error as server error
func (*ResponseError) Status ¶
func (e *ResponseError) Status(c int) *ResponseError
Status updates the status code for response
type RouteStat ¶
type RouteStat struct {
Str string
Path string
Method string
Host string
Loc string
Group bool
Prefix string
}
RouteStat defines struct for collected route info
func WalkCollect ¶
func WalkCollect(mux *http.ServeMux, configs ...*WalkConfig) []RouteStat
WalkCollect walks through mux to generate route stats
type Value ¶
type Value[T any] struct { // contains filtered or unexported fields }
Value[T any] defines struct for resolving value from sources
func HTTPContext ¶ added in v0.1.0
HTTPContext defines value resolver to access request's context.Context
func HTTPRequest ¶ added in v0.1.0
HTTPRequest defines value resolver to access *http.Request
func HTTPResponseWriter ¶ added in v0.1.0
func HTTPResponseWriter() *Value[http.ResponseWriter]
HTTPResponseWriter defines value resolver to access http.ResponseWriter
func NewValue ¶
func NewValue[T any](field string, src ValueSource) *Value[T]
NewValue define new value resolver instance
func StructFrom ¶
func StructFrom[T any](src ValueSource) *Value[T]
StructFrom defines new struct resolver instance
type ValueFailHandler ¶
type ValueFailHandler func(ValueResolver, error) error
type ValueResolver ¶
type ValueResolver interface {
// Field returns the name of the field
Field() string
// Alias returns the alias of the field
Alias() string
// Type returns [reflect.Type] of value
Type() reflect.Type
// Default returns default value of type
Default() any
// Checks if value is required
Required() bool
// Resolve evaluates and return the resulting value else error
Resolve(http.ResponseWriter, *http.Request) (any, error)
}
ValueResolver defines an interface to be used by handler
type ValueSource ¶
type ValueSource int
ValueSource defines the source of value
const ( ValueSourcePath ValueSource = iota // reads from path params ValueSourceGet // reads from url query ValueSourceBody // reads from request body ValueSourceHeader // reads from request header ValueSourceContext // reads from request context default data ValueSourceDefault // reads from source based on request method )
type WalkCallback ¶
type WalkCallback func(RouteStat)
WalkCallback defines function signature for walk callback
type WalkConfig ¶
WalkConfig defines configurations for walk
func (*WalkConfig) Clone ¶
func (c *WalkConfig) Clone(prefix string) *WalkConfig
Clone creates new config with updated prefix
func (*WalkConfig) Get ¶
func (c *WalkConfig) Get(path string) *http.ServeMux
Get retrieves mapping item
func (*WalkConfig) Set ¶
func (c *WalkConfig) Set(path string, mux *http.ServeMux) *WalkConfig
Set registers mapping item