httputil

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2026 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

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) error

Bind decodes the JSON body of an HTTP request into the given destination object.

func BindOrError deprecated

func BindOrError(r *http.Request, w http.ResponseWriter, dst any) error

BindOrError decodes the JSON body of an HTTP request into the given destination object. If decoding fails, it responds with a 400 Bad Request error.

Deprecated: Use Bind instead and handle errors manually. BindOrError will be removed in a future version. Migration example:

Old: if err := BindOrError(r, w, &dst); err != nil { return }
New: if err := Bind(r, &dst); err != nil { Error(w, http.StatusBadRequest, err.Error()); return }

func Blob

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

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

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 sends a JSON response with an error code and message.

func HTML

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

HTML writes an HTML response with the given status code and HTML content.

func JSON

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

JSON writes a JSON response with the given status code and data.

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 and text content.

Types

type ContextKey

type ContextKey string
const (
	RequestIDCtxKey     ContextKey = "RequestID"
	LogEntryCtxKey      ContextKey = "LogEntry"
	OIDCUserCtxKey      ContextKey = "OIDCUser"
	BasicAuthCtxKey     ContextKey = "BasicAuth"
	PgConnCtxKey        ContextKey = "PgConn"
	OIDCRoleClaimCtxKey ContextKey = "OIDCRoleClaim"
)

type ErrorResponse

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

ErrorResponse represents a structured error response.

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 is the main structure for handling HTTP routing and middleware.

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 an HTTP handler function for a given method and pattern as introduced in [Routing Enhancements for Go 1.22](https://go.dev/blog/routing-enhancements) The handler `METHOD /pattern` on a route group with a /prefix resolves to `METHOD /prefix/pattern`

func (*Router) ListenAndServe

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

ListenAndServe starts the server, automatically choosing between HTTP and HTTPS based on TLS config.

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