Documentation
¶
Index ¶
- Variables
- func BasicAuthUser(r *http.Request) (string, bool)
- func Bind(r *http.Request, dst any, opts ...BindOption) error
- func Blob(w http.ResponseWriter, statusCode int, contentType string, data []byte)
- func Conn(r *http.Request) (map[string]any, *pgxpool.Conn, *pgconn.PgError)
- func ConnWithRole(r *http.Request) (map[string]any, *pgxpool.Conn, *pgconn.PgError)
- func Error(w http.ResponseWriter, statusCode int, message string)
- func HTML(w http.ResponseWriter, statusCode int, html string)
- func JSON(w http.ResponseWriter, statusCode int, v any)
- func OIDCUser(r *http.Request) (map[string]any, bool)
- func Text(w http.ResponseWriter, statusCode int, text string)
- type BindOption
- type ErrorResponse
- type Logger
- type Middleware
- type RequestConfig
- type Response
- type Router
- func (r *Router) Group(prefix string) *Router
- func (r *Router) Handle(methodPattern string, handler http.Handler)
- func (r *Router) HandleFunc(methodPattern string, handler http.HandlerFunc)
- func (r *Router) ListenAndServe(addr string) error
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) Shutdown(ctx context.Context) error
- func (r *Router) Use(mw Middleware, additional ...Middleware)
- type RouterOptions
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ConnWithRole ¶
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.
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 ¶
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 ¶
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 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 ¶
Group creates a new sub-router with a specified prefix. The sub-router inherits the middleware from its parent router.
func (*Router) Handle ¶
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 ¶
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) 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.