webutil

package module
v0.2.7 Latest Latest
Warning

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

Go to latest
Published: Dec 18, 2025 License: MIT Imports: 17 Imported by: 6

README

GoDoc

Web Utilities for Go

A collection of utilities for HTTP servers and web applications in Go.

Features

  • HTTP Error Handling: Type HTTPError implements both error and http.Handler interfaces
  • Resumable Downloads: Auto-resuming HTTP downloads using Range headers
  • Data URI Parsing: Parse and work with data: URI schemes
  • IP:Port Parsing: Parse and validate IP addresses with ports
  • Error-to-Handler Conversion: Convert between errors and HTTP handlers
  • PHP Query String Handling: Parse and generate PHP-style query strings with array notation
  • HTTP Redirects: Create and handle HTTP redirects as errors

Usage Examples

// Get with auto-resume
resp, err := webutil.Get("https://example.com/large-file.zip")
if err != nil {
    // Handle error
}
defer resp.Close()
// Reading from resp will auto-resume on network errors

// Return HTTP errors from handlers
if !authenticated {
    return webutil.StatusUnauthorized
}

// Parse data URIs
data, mime, err := webutil.ParseDataURI("data:text/plain;base64,SGVsbG8gV29ybGQ=")

Documentation

See GoDoc for complete API documentation.

Documentation

Overview

Package webutil provides utility functions and types for web applications.

Index

Constants

View Source
const (
	// 4xx Client Errors
	StatusBadRequest                   = HTTPError(http.StatusBadRequest)
	StatusUnauthorized                 = HTTPError(http.StatusUnauthorized)
	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)
	StatusUnavailableForLegalReasons   = HTTPError(http.StatusUnavailableForLegalReasons)

	// 5xx Server Errors
	StatusInternalServerError           = HTTPError(http.StatusInternalServerError)
	StatusNotImplemented                = HTTPError(http.StatusNotImplemented)
	StatusBadGateway                    = HTTPError(http.StatusBadGateway)
	StatusServiceUnavailable            = HTTPError(http.StatusServiceUnavailable)
	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

View Source
var ErrNoEncodedValue = errors.New("could not locate encoded value")

ErrNoEncodedValue is returned when the data URI doesn't contain a value part

View Source
var ErrNotDataURI = errors.New("not a data URI")

ErrNotDataURI is returned when the input string is not a valid data URI

Functions

func ConvertPhpQuery

func ConvertPhpQuery(values url.Values) map[string]any

ConvertPhpQuery converts standard url.Values to a structured map using PHP-style array/object notation in the keys.

func EncodePhpQuery

func EncodePhpQuery(query map[string]any) string

EncodePhpQuery converts a structured map back to a PHP-compatible query string.

func ErrorHandler added in v0.0.2

func ErrorHandler(handler http.Handler) error

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

func ErrorToHTTPHandler(e error) http.Handler

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 ErrorToHttpHandler(e error) http.Handler

ErrorToHttpHandler is an alias for ErrorToHTTPHandler to maintain backward compatibility.

Deprecated: Use ErrorToHTTPHandler instead.

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 HTTPErrorHandler(code int) http.Handler

HTTPErrorHandler returns a http.Handler for a given error code.

Deprecated: HTTPError can be directly used as a handler.

func HTTPHandlerToError added in v0.2.3

func HTTPHandlerToError(h http.Handler) error

HTTPHandlerToError converts an http.Handler to an error.

func HTTPStatus added in v0.0.5

func HTTPStatus(err error) int

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 HttpErrorHandler(code int) http.Handler

HttpErrorHandler is an alias for HTTPErrorHandler to maintain backward compatibility.

Deprecated: Use HTTPErrorHandler instead.

func HttpHandlerToError deprecated

func HttpHandlerToError(h http.Handler) error

HttpHandlerToError is an alias for HTTPHandlerToError to maintain backward compatibility.

Deprecated: Use HTTPHandlerToError instead.

func IsRedirect

func IsRedirect(err error) http.Handler

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

func ParseDataURI(uri string) ([]byte, string, error)

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 ParseDataUri(uri string) ([]byte, string, error)

ParseDataUri is an alias for ParseDataURI to maintain backward compatibility.

Deprecated: Use ParseDataURI instead.

func ParseIPPort

func ParseIPPort(ipStr string) *net.TCPAddr

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

func ParsePhpQuery(query string) map[string]any

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

func RedirectError(u *url.URL) error

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

func RedirectErrorCode(u *url.URL, code int) error

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.

func Wrap added in v0.0.8

func Wrap(h Handler) http.Handler

Wrap converts a Handler to a standard http.Handler by wrapping it in a Wrapper that will handle any returned errors.

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

func (e HTTPError) Error() string

Error returns a formatted string with the HTTP error code and text.

func (HTTPError) HTTPStatus added in v0.2.3

func (e HTTPError) HTTPStatus() int

HTTPStatus returns the numeric HTTP status code represented by this error.

func (HTTPError) ServeHTTP added in v0.2.3

func (e HTTPError) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements the http.Handler interface to serve the HTTP error.

func (HTTPError) Unwrap added in v0.2.3

func (e HTTPError) Unwrap() error

Unwrap maps HTTP errors to standard filesystem errors when appropriate, making it easier to check if a response matches a specific kind of 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

type Redirect struct {
	URL  *url.URL // Target URL
	Code int      // HTTP status code (should be 3xx)
}

Redirect represents an error that requires an HTTP redirect. It implements both error and http.Handler interfaces.

func (*Redirect) Error added in v0.0.6

func (r *Redirect) Error() string

Error implements the error interface for Redirect.

func (*Redirect) HTTPStatus added in v0.0.6

func (r *Redirect) HTTPStatus() int

HTTPStatus returns the HTTP status code for this redirect.

func (*Redirect) ServeHTTP added in v0.0.6

func (r *Redirect) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements the http.Handler interface for Redirect. When called, it performs an HTTP redirect to the target URL.

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.

func (WrapFunc) ServeHTTP added in v0.0.8

func (wf WrapFunc) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements the http.Handler interface for WrapFunc, allowing it to be used directly as an http.Handler while still returning errors.

type Wrapper added in v0.0.8

type Wrapper struct {
	Child Handler // The wrapped Handler that may return errors
}

Wrapper adapts the Handler interface to the standard http.Handler interface. It automatically handles any errors returned by the wrapped Handler by converting them to HTTP responses.

func (*Wrapper) ServeHTTP added in v0.0.8

func (wrapper *Wrapper) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP implements the http.Handler interface by calling the wrapped Handler and handling any returned errors by converting them to appropriate HTTP responses.

Jump to

Keyboard shortcuts

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