httputil

package
v0.90.0 Latest Latest
Warning

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

Go to latest
Published: Jan 20, 2026 License: AGPL-3.0 Imports: 7 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrBadRequest          = NewHTTPError(http.StatusBadRequest, "bad request")
	ErrUnauthorized        = NewHTTPError(http.StatusUnauthorized, "unauthorized")
	ErrForbidden           = NewHTTPError(http.StatusForbidden, "forbidden")
	ErrNotFound            = NewHTTPError(http.StatusNotFound, "not found")
	ErrMethodNotAllowed    = NewHTTPError(http.StatusMethodNotAllowed, "method not allowed")
	ErrConflict            = NewHTTPError(http.StatusConflict, "conflict")
	ErrInternalServerError = NewHTTPError(http.StatusInternalServerError, "internal server error")
	ErrServiceUnavailable  = NewHTTPError(http.StatusServiceUnavailable, "service unavailable")
)

Common HTTP errors

Functions

func CheckMethod

func CheckMethod(w http.ResponseWriter, r *http.Request, method string) bool

CheckMethod validates that the request method matches the expected method. If it doesn't match, it writes a 405 Method Not Allowed error and returns false.

func CheckMethodOneOf

func CheckMethodOneOf(w http.ResponseWriter, r *http.Request, methods ...string) bool

CheckMethodOneOf validates that the request method is one of the allowed methods. If it doesn't match any, it writes a 405 Method Not Allowed error and returns false.

func DecodeBase64

func DecodeBase64(s string) ([]byte, error)

DecodeBase64 decodes a base64-encoded string to bytes.

func DecodeJSON

func DecodeJSON(r *http.Request, v any) error

DecodeJSON decodes the request body as JSON into the provided value. Returns an error if decoding fails.

func DecodeJSONStrict

func DecodeJSONStrict(r *http.Request, v any) error

DecodeJSONStrict decodes the request body as JSON with strict validation. It disallows unknown fields and returns an error if any are present.

func EncodeBase64

func EncodeBase64(data []byte) string

EncodeBase64 encodes bytes to a base64-encoded string.

func ExtractAPIKey

func ExtractAPIKey(r *http.Request) string

ExtractAPIKey extracts an API key from various sources: 1. X-API-Key header (highest priority) 2. Authorization header with "ApiKey" scheme 3. Authorization header with "Bearer" scheme (if not a JWT) 4. Query parameter "api_key" 5. Query parameter "token"

Note: Bearer tokens that look like JWTs (have 2 dots) are skipped.

func ExtractBasicAuth

func ExtractBasicAuth(r *http.Request) (username, password string, ok bool)

ExtractBasicAuth extracts username and password from Basic authentication. Returns empty strings if Basic auth is not present or invalid.

func ExtractBearerToken

func ExtractBearerToken(r *http.Request) string

ExtractBearerToken extracts a Bearer token from the Authorization header. Returns an empty string if no Bearer token is found.

func ExtractNamespaceHeader

func ExtractNamespaceHeader(r *http.Request) string

ExtractNamespaceHeader extracts the namespace from the X-Namespace header.

func ExtractWalletHeader

func ExtractWalletHeader(r *http.Request) string

ExtractWalletHeader extracts the wallet address from the X-Wallet header.

func HasAuthHeader

func HasAuthHeader(r *http.Request) bool

HasAuthHeader checks if the request has any Authorization header.

func IsEmpty

func IsEmpty(s string) bool

IsEmpty checks if a string is empty after trimming whitespace.

func IsJWT

func IsJWT(token string) bool

IsJWT checks if a token looks like a JWT (has exactly 2 dots separating 3 parts).

func IsNotEmpty

func IsNotEmpty(s string) bool

IsNotEmpty checks if a string is not empty after trimming whitespace.

func NormalizeWalletAddress

func NormalizeWalletAddress(wallet string) string

NormalizeWalletAddress normalizes a wallet address by removing "0x" prefix and converting to lowercase.

func QueryParam

func QueryParam(r *http.Request, key, defaultValue string) string

QueryParam returns the value of a query parameter, or defaultValue if not present.

func QueryParamBool

func QueryParamBool(r *http.Request, key string, defaultValue bool) bool

QueryParamBool returns the boolean value of a query parameter. Returns true if the parameter value is "true", "1", "yes", or "on" (case-insensitive). Returns defaultValue if the parameter is not present or has an invalid value.

func QueryParamInt

func QueryParamInt(r *http.Request, key string, defaultValue int) int

QueryParamInt returns the integer value of a query parameter, or defaultValue if not present or invalid.

func ReadBody

func ReadBody(r *http.Request, maxBytes int64) ([]byte, error)

ReadBody reads the entire request body up to maxBytes. Returns the body bytes or an error if reading fails.

func RequireNotEmpty

func RequireNotEmpty(w http.ResponseWriter, value, fieldName string) bool

RequireNotEmpty checks if a string value is empty after trimming whitespace. If empty, it writes a 400 Bad Request error with the field name and returns false.

func ValidateCID

func ValidateCID(cid string) bool

ValidateCID checks if a string is a valid IPFS CID.

func ValidateDMapName

func ValidateDMapName(dmap string) bool

func ValidateNamespace

func ValidateNamespace(ns string) bool

func ValidateTopicName

func ValidateTopicName(topic string) bool

func ValidateWalletAddress

func ValidateWalletAddress(wallet string) bool

func WriteError

func WriteError(w http.ResponseWriter, code int, msg string)

WriteError writes a standardized JSON error response. The response format is: {"error": "message"}

func WriteHTTPError

func WriteHTTPError(w http.ResponseWriter, err *HTTPError)

WriteHTTPError writes an HTTPError to the response.

func WriteJSON

func WriteJSON(w http.ResponseWriter, code int, v any)

WriteJSON writes a JSON response with the given status code. It sets the Content-Type header to application/json and encodes the value as JSON. Any encoding errors are silently ignored (best-effort).

func WriteSuccess

func WriteSuccess(w http.ResponseWriter)

WriteSuccess writes a standardized JSON success response. The response format is: {"status": "ok"}

func WriteSuccessWithData

func WriteSuccessWithData(w http.ResponseWriter, data map[string]any)

WriteSuccessWithData writes a success response with additional data fields. The response format is: {"status": "ok", ...data}

Types

type HTTPError

type HTTPError struct {
	Code    int
	Message string
}

HTTPError represents a structured HTTP error with a status code and message.

func NewHTTPError

func NewHTTPError(code int, message string) *HTTPError

NewHTTPError creates a new HTTP error with the given code and message.

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error implements the error interface.

Jump to

Keyboard shortcuts

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