Documentation
¶
Overview ¶
Package webutil provides utility functions and types for web applications.
Index ¶
- Constants
- Variables
- func ConvertPhpQuery(values url.Values) map[string]any
- func EncodePhpQuery(query map[string]any) string
- func ErrorHandler(handler http.Handler) error
- func ErrorHandlerFunc(handlerFn func(w http.ResponseWriter, req *http.Request)) error
- func ErrorToHTTPHandler(e error) http.Handler
- func ErrorToHttpHandler(e error) http.Handlerdeprecated
- func Get(url string) (io.ReadCloser, error)
- func HTTPErrorHandler(code int) http.Handlerdeprecated
- func HTTPHandlerToError(h http.Handler) error
- func HTTPStatus(err error) int
- func HttpErrorHandler(code int) http.Handlerdeprecated
- func HttpHandlerToError(h http.Handler) errordeprecated
- func IsRedirect(err error) http.Handler
- func ParseDataURI(uri string) ([]byte, string, error)
- func ParseDataUri(uri string) ([]byte, string, error)deprecated
- func ParseIPPort(ipStr string) *net.TCPAddr
- func ParsePhpQuery(query string) map[string]any
- func RedirectError(u *url.URL) error
- func RedirectErrorCode(u *url.URL, code int) error
- func SendRedirect(w http.ResponseWriter, target string, code int)deprecated
- func ServeError(w http.ResponseWriter, req *http.Request, err error)
- func Wrap(h Handler) http.Handler
- type AddPrefix
- type HTTPError
- type Handler
- type HttpError
- type Redirect
- type SkipPrefix
- type WrapFunc
- type Wrapper
Constants ¶
const ( // 4xx Client Errors StatusBadRequest = HTTPError(http.StatusBadRequest) StatusPaymentRequired = HTTPError(http.StatusPaymentRequired) StatusForbidden = HTTPError(http.StatusForbidden) StatusNotFound = HTTPError(http.StatusNotFound) StatusMethodNotAllowed = HTTPError(http.StatusMethodNotAllowed) StatusNotAcceptable = HTTPError(http.StatusNotAcceptable) StatusProxyAuthRequired = HTTPError(http.StatusProxyAuthRequired) StatusRequestTimeout = HTTPError(http.StatusRequestTimeout) StatusConflict = HTTPError(http.StatusConflict) StatusGone = HTTPError(http.StatusGone) StatusLengthRequired = HTTPError(http.StatusLengthRequired) StatusPreconditionFailed = HTTPError(http.StatusPreconditionFailed) StatusRequestEntityTooLarge = HTTPError(http.StatusRequestEntityTooLarge) StatusRequestURITooLong = HTTPError(http.StatusRequestURITooLong) StatusUnsupportedMediaType = HTTPError(http.StatusUnsupportedMediaType) StatusRequestedRangeNotSatisfiable = HTTPError(http.StatusRequestedRangeNotSatisfiable) StatusExpectationFailed = HTTPError(http.StatusExpectationFailed) StatusTeapot = HTTPError(http.StatusTeapot) StatusMisdirectedRequest = HTTPError(http.StatusMisdirectedRequest) StatusUnprocessableEntity = HTTPError(http.StatusUnprocessableEntity) StatusLocked = HTTPError(http.StatusLocked) StatusFailedDependency = HTTPError(http.StatusFailedDependency) StatusTooEarly = HTTPError(http.StatusTooEarly) StatusUpgradeRequired = HTTPError(http.StatusUpgradeRequired) StatusPreconditionRequired = HTTPError(http.StatusPreconditionRequired) StatusTooManyRequests = HTTPError(http.StatusTooManyRequests) StatusRequestHeaderFieldsTooLarge = HTTPError(http.StatusRequestHeaderFieldsTooLarge) // 5xx Server Errors StatusInternalServerError = HTTPError(http.StatusInternalServerError) StatusNotImplemented = HTTPError(http.StatusNotImplemented) StatusBadGateway = HTTPError(http.StatusBadGateway) StatusGatewayTimeout = HTTPError(http.StatusGatewayTimeout) StatusHTTPVersionNotSupported = HTTPError(http.StatusHTTPVersionNotSupported) StatusVariantAlsoNegotiates = HTTPError(http.StatusVariantAlsoNegotiates) StatusInsufficientStorage = HTTPError(http.StatusInsufficientStorage) StatusLoopDetected = HTTPError(http.StatusLoopDetected) StatusNotExtended = HTTPError(http.StatusNotExtended) StatusNetworkAuthenticationRequired = HTTPError(http.StatusNetworkAuthenticationRequired) )
Pre-defined HTTP status error constants. These provide HTTP status codes as HTTPError objects that can be used directly as errors or as http.Handler instances.
Variables ¶
var ErrNoEncodedValue = errors.New("could not locate encoded value")
ErrNoEncodedValue is returned when the data URI doesn't contain a value part
var ErrNotDataURI = errors.New("not a data URI")
ErrNotDataURI is returned when the input string is not a valid data URI
Functions ¶
func ConvertPhpQuery ¶
ConvertPhpQuery converts standard url.Values to a structured map using PHP-style array/object notation in the keys.
func EncodePhpQuery ¶
EncodePhpQuery converts a structured map back to a PHP-compatible query string.
func ErrorHandler ¶ added in v0.0.2
ErrorHandler converts a standard http.Handler into an error type that still implements the http.Handler interface.
This is useful for returning handlers as errors in functions that need to indicate that a request should be handled differently.
func ErrorHandlerFunc ¶ added in v0.0.2
func ErrorHandlerFunc(handlerFn func(w http.ResponseWriter, req *http.Request)) error
ErrorHandlerFunc converts a standard handler function into an error type that also implements the http.Handler interface.
This allows function-based handlers to be returned as errors from functions that might need to delegate handling.
func ErrorToHTTPHandler ¶ added in v0.2.3
ErrorToHTTPHandler converts an error to an http.Handler. If the error already implements http.Handler, it's returned directly. Otherwise, it's wrapped in a serverError.
func ErrorToHttpHandler
deprecated
func Get ¶ added in v0.2.1
func Get(url string) (io.ReadCloser, error)
Get retrieves content from a URL or data URI and returns it as an io.ReadCloser.
For HTTP/HTTPS URLs, it returns an io.ReadCloser that will: 1. Automatically resume the download if the connection is interrupted 2. Handle proper error reporting based on HTTP status codes 3. Use Range headers for transparent resuming when connections fail mid-download
For data URIs (URLs starting with "data:"), it decodes the embedded data and returns it directly without any network request.
Limitations for HTTP requests: - If the server doesn't support Range headers, it can't resume - If Content-Length isn't provided, size tracking won't be accurate
func HTTPErrorHandler
deprecated
added in
v0.2.3
func HTTPHandlerToError ¶ added in v0.2.3
HTTPHandlerToError converts an http.Handler to an error.
func HTTPStatus ¶ added in v0.0.5
HTTPStatus extracts an HTTP status code from an error.
It can handle several types of errors: 1. Standard fs package errors (ErrNotExist, ErrPermission) 2. HTTPError type from this package 3. Any error that implements HTTPStatus() int 4. Wrapped errors (recursively checks unwrapped errors)
Returns 0 if no status code can be determined from the error.
func HttpErrorHandler
deprecated
func HttpHandlerToError
deprecated
func IsRedirect ¶
IsRedirect checks if an error is a Redirect error. If it is, returns the error as an http.Handler for convenient use. Otherwise, returns nil.
func ParseDataURI ¶ added in v0.2.3
ParseDataURI parses a given data: URI and returns its binary data and MIME type.
The format of a data URI is:
data:[<media type>][;base64],<data>
Example: "data:text/plain;base64,SGVsbG8gV29ybGQ="
func ParseDataUri
deprecated
func ParseIPPort ¶
ParseIPPort parses a string containing an IP address with an optional port.
The input can be in the following formats:
- "127.0.0.1:80" -> IP with port
- "127.0.0.1" -> IP only
- "[::1]:80" -> IPv6 with port
- "::1" -> IPv6 only
- ":80" -> Empty host with port
Returns nil if the input cannot be parsed as a valid IP/port combination.
func ParsePhpQuery ¶
ParsePhpQuery parses a PHP-compatible query string into a structured map.
The function handles various PHP-style query formats:
- a=b (simple key-value)
- a[b]=c (nested object)
- a[]=c (array)
- a[b][]=c (multi-level nesting)
- a[][][]=c (multi-level arrays)
The resulting map contains properly structured nested objects and arrays.
func RedirectError ¶
RedirectError creates a redirect error with the default 302 Found status.
Parameter:
- u: Target URL for the redirection
Returns a Redirect object implementing both error and http.Handler interfaces.
func RedirectErrorCode ¶
RedirectErrorCode creates a redirect error with a specific HTTP status code.
Parameters:
- u: Target URL for the redirection
- code: HTTP status code (should be a 3xx status code)
Returns a Redirect object implementing both error and http.Handler interfaces.
func SendRedirect
deprecated
func SendRedirect(w http.ResponseWriter, target string, code int)
SendRedirect is a robust HTTP redirect implementation that uses multiple fallback techniques to ensure successful redirection.
Deprecated: Use http.Redirect() for standard redirects. This function is only needed in edge cases where user agents may not support standard redirects.
func ServeError ¶
func ServeError(w http.ResponseWriter, req *http.Request, err error)
ServeError serves an error via HTTP. If the error can be type-asserted to an http.Handler, it uses that. Otherwise, it wraps the error in a serverError and serves that.
Types ¶
type AddPrefix ¶ added in v0.2.3
type AddPrefix struct {
// Prefix is the string to be added to the beginning of the URL path
Prefix string
// Handler is the http.Handler that will serve the request after the prefix is added
Handler http.Handler
}
AddPrefix is an http.Handler that adds a prefix to the request URL path before passing the request to the underlying handler.
func (*AddPrefix) ServeHTTP ¶ added in v0.2.3
func (h *AddPrefix) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface for AddPrefix. It adds the specified prefix to the request URL path, RawPath, and RequestURI, and then passes the modified request to the underlying handler.
type HTTPError ¶ added in v0.2.3
type HTTPError int
HTTPError represents an HTTP error code as an error type. It also implements the http.Handler interface to serve the error.
func (HTTPError) Error ¶ added in v0.2.3
Error returns a formatted string with the HTTP error code and text.
func (HTTPError) HTTPStatus ¶ added in v0.2.3
HTTPStatus returns the numeric HTTP status code represented by this error.
type Handler ¶ added in v0.0.8
type Handler interface {
ServeHTTP(w http.ResponseWriter, req *http.Request) error
}
Handler extends the standard http.Handler interface by allowing ServeHTTP to return an error. This enables more flexible error handling and allows handlers to delegate requests via error returns.
type HttpError ¶
type HttpError = HTTPError
HttpError is an alias for HTTPError to maintain backward compatibility. Deprecated: Use HTTPError instead.
type Redirect ¶ added in v0.0.6
Redirect represents an error that requires an HTTP redirect. It implements both error and http.Handler interfaces.
func (*Redirect) HTTPStatus ¶ added in v0.0.6
HTTPStatus returns the HTTP status code for this redirect.
type SkipPrefix ¶ added in v0.2.3
type SkipPrefix struct {
// Prefix is the string to be removed from the beginning of the URL path
Prefix string
// Handler is the http.Handler that will serve the request after the prefix is removed
Handler http.Handler
}
SkipPrefix is an http.Handler that removes a prefix from the request URL path before passing the request to the underlying handler.
func (*SkipPrefix) ServeHTTP ¶ added in v0.2.3
func (h *SkipPrefix) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface for SkipPrefix. It removes the specified prefix from the request URL path, RawPath, and RequestURI, sets a Sec-Access-Prefix header with the removed prefix, and then passes the modified request to the underlying handler.
type WrapFunc ¶ added in v0.0.8
type WrapFunc func(w http.ResponseWriter, req *http.Request) error
WrapFunc is a function type that implements the Handler interface. It's similar to http.HandlerFunc but can return an error.