httputil

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	RequestIDCtxKey     = contextKey("RequestID")
	LogEntryCtxKey      = contextKey("LogEntry")
	OIDCUserCtxKey      = contextKey("OIDCUser")
	BasicAuthCtxKey     = contextKey("BasicAuth")
	PgConnCtxKey        = contextKey("PgConn")
	OIDCRoleClaimCtxKey = contextKey("OIDCRoleClaim")
)

Context keys for values stored by middleware.

Functions

func BasicAuthUser

func BasicAuthUser(r *http.Request) (string, bool)

BasicAuthUser retrieves the authenticated username from the context.

func Bind

func Bind(r *http.Request, dst any, opts ...BindOption) error

Bind decodes a JSON request body into dst, capped at 1 MiB by default. For strict decoding (no unknown fields), configure the decoder directly.

Override the limit with WithMaxBytes:

if err := httputil.Bind(r, &dst, httputil.WithMaxBytes(10<<20)); err != nil {
    httputil.Error(w, http.StatusBadRequest, err.Error())
    return
}

func Blob

func Blob(w http.ResponseWriter, statusCode int, contentType string, data []byte)

Blob writes a binary response with the given status code and content type.

func Conn

func Conn(r *http.Request) (map[string]any, *pgxpool.Conn, *pgconn.PgError)

Conn returns the user and pgxpool.Conn retrieved from the request context.

func ConnWithRole

func ConnWithRole(r *http.Request) (map[string]any, *pgxpool.Conn, *pgconn.PgError)

ConnWithRole retrieves the OIDC user and a pooled database connection, then sets the appropriate PostgreSQL role based on the request context. It's designed for use with Row Level Security (RLS) enabled tables.

The function also sets JWT claims in the PostgreSQL session using the environment variable PIGO_POSTGRES_OIDC_REQUEST_JWT_CLAIMS (defaults to "request.jwt.claims" for PostgREST compatibility).

Example RLS policy that allows users to only select their own rows:

ALTER TABLE wallets ENABLE ROW LEVEL SECURITY;
ALTER TABLE wallets FORCE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS select_own ON wallets;
CREATE POLICY select_own ON wallets FOR SELECT USING (
	user_id = (current_setting('request.jwt.claims', true)::json->>'sub')::TEXT
);
ALTER POLICY select_own ON wallets TO authn;

For more information on how claims are used, see: https://docs.postgrest.org/en/v12/references/transactions.html#request-headers-cookies-and-jwt-claims

func Error

func Error(w http.ResponseWriter, statusCode int, message string)

Error writes a JSON error response. It is safe to call before WriteHeader has been invoked; calling it after is a no-op on the status (already sent) but will still attempt to write the body.

func HTML

func HTML(w http.ResponseWriter, statusCode int, html string)

HTML writes an HTML response with the given status code.

func JSON

func JSON(w http.ResponseWriter, statusCode int, v any)

JSON marshals v to JSON and writes it with the given status code.

Marshalling happens before WriteHeader so that a marshalling failure can still be reported as a 500 without having already committed a 200.

func OIDCUser

func OIDCUser(r *http.Request) (map[string]any, bool)

func Text

func Text(w http.ResponseWriter, statusCode int, text string)

Text writes a plain-text response with the given status code.

Types

type BindOption added in v0.0.4

type BindOption func(*bindOptions)

BindOption configures Bind behaviour.

func WithMaxBytes added in v0.0.4

func WithMaxBytes(n int64) BindOption

WithMaxBytes sets the body size limit for Bind. Default is 1 MiB.

type ErrorResponse

type ErrorResponse struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
}

ErrorResponse is the JSON shape returned by Error. The HTTP status code is already in the response line; Code is included here so API clients that only inspect the body don't need to track it separately.

type Logger

type Logger interface {
	Printf(format string, v ...interface{})
}

Logger interface for customizable logging

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware defines a function type that represents a middleware. Middleware functions wrap an http.Handler to modify or enhance its behavior.

type RequestConfig

type RequestConfig struct {
	Logger          Logger
	Headers         map[string][]string
	ResponseHandler func(*http.Response) error
	Method          string
	URL             string
	Timeout         time.Duration
	MaxRetries      int
	InitialBackoff  time.Duration
	MaxBackoff      time.Duration
	RetryEnabled    bool
}

RequestConfig holds configuration for HTTP requests

func DefaultRequestConfig

func DefaultRequestConfig(method, url string) RequestConfig

DefaultRequestConfig returns a RequestConfig with sensible defaults

type Response

type Response struct {
	Headers    http.Header
	Request    *http.Request
	Body       []byte
	StatusCode int
}

Response represents an HTTP response with additional metadata

func Request

func Request(ctx context.Context, config RequestConfig, payload interface{}) (*Response, error)

Request performs an HTTP request with configurable retry logic

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router handles HTTP routing and middleware chaining. It implements http.Handler and can therefore be used with any standard net/http server, httptest.NewServer, or embedded in other handlers.

func NewRouter

func NewRouter(opts ...RouterOptions) *Router

NewRouter creates a new instance of Router with the given options.

func (*Router) Group

func (r *Router) Group(prefix string) *Router

Group creates a new sub-router with a specified prefix. The sub-router inherits the middleware from its parent router.

func (*Router) Handle

func (r *Router) Handle(methodPattern string, handler http.Handler)

Handle registers handler for "METHOD /path" patterns (Go 1.22+). Panics on malformed input.

func (*Router) HandleFunc added in v0.0.4

func (r *Router) HandleFunc(methodPattern string, handler http.HandlerFunc)

HandleFunc is a convenience wrapper around Handle for plain functions.

func (*Router) ListenAndServe

func (r *Router) ListenAndServe(addr string) error

ListenAndServe starts the HTTP (or HTTPS if TLS is configured) server on addr. It sets the router itself as the server's Handler so that ServeHTTP is the single entry point.

func (*Router) ServeHTTP added in v0.0.4

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

ServeHTTP implements http.Handler, allowing Router to be used anywhere an http.Handler is accepted - httptest.NewServer, http.ListenAndServe, etc.

func (*Router) Shutdown

func (r *Router) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the HTTP server.

func (*Router) Use

func (r *Router) Use(mw Middleware, additional ...Middleware)

Use adds one or more middleware to the router. At least one middleware must be provided. Middleware functions are applied in the order they are added.

type RouterOptions

type RouterOptions func(*Router)

RouterOptions is a function type that represents options to configure a Router.

func WithServerOptions

func WithServerOptions(opts ...func(*http.Server)) RouterOptions

WithServerOptions returns a RouterOptions function that sets custom http.Server options.

func WithTLS

func WithTLS(certFile, keyFile string) RouterOptions

WithTLS provides a simplified way to enable HTTPS in your router.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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