helper

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package helper provides the request, header and HTTP error helpers of the relay proxy.

Index

Constants

View Source
const XAPIKeyHeader = "X-Api-Key" //nolint:gosec // G101: the name of a header, not a credential

XAPIKeyHeader defines the header name for passing API keys. This is not a credential itself, but a standard HTTP header key.

Variables

View Source
var (
	ErrUnauthorized = StatusError(http.StatusUnauthorized)
	ErrNotFound     = StatusError(http.StatusNotFound)
)

Predefined errors of the statuses used without a message of their own. Their message is the text of the status.

Functions

func APIKey

func APIKey(r *http.Request) string

APIKey extracts the API key from the request headers. It checks headers in the following order of precedence: 1. X-API-Key header (raw value) 2. Authorization header (with "Bearer " prefix removed if present) Returns an empty string if no API key is found.

func APIKeyFromHeaders added in v0.2.0

func APIKeyFromHeaders(header func(string) string) string

APIKeyFromHeaders is APIKey for a source that reads a header by its name.

func AuthenticateFlagSet

func AuthenticateFlagSet(
	ctx context.Context, flagsetManager service.FlagSetResolver, apiKey string,
) (context.Context, bool)

AuthenticateFlagSet resolves the flag set of the API key of the request. It returns the context to give to the handler, which carries the flag set, and false if the key does not route to a flag set. The accepted keys and the routing of the flag sets are one table: authentication and handler use the flag set resolved here, so a reload that swaps the routing in between can not make an authenticated request fail.

func AuthenticateFlagSetName

func AuthenticateFlagSetName(
	ctx context.Context, flagsetManager service.FlagSetResolver, apiKey string,
) (context.Context, bool)

AuthenticateFlagSetName is AuthenticateFlagSet for the endpoints that only need the name of the flag set.

func BindBody added in v0.2.0

func BindBody(r *http.Request, target any) error

BindBody decodes the JSON body of the request in target. An empty body leaves target untouched, another content type than JSON is refused with 415, and a body that can not be read or decoded with 400.

func BindRawBody added in v0.2.0

func BindRawBody(contentType string, raw []byte, target any) error

BindRawBody is BindBody for a body that was read already, and checked against its content type.

func DecodeJSON added in v0.2.0

func DecodeJSON(data []byte, target any) error

DecodeJSON decodes a JSON document in target. A failure is a 400.

func EncodedOr added in v0.3.0

func EncodedOr(
	enc service.ValueEncoder, flagKey, variation string, reason flagdef.ResolutionReason, value any,
) any

EncodedOr returns what a response puts in a value field for the value of an evaluation: the encoding that the flag set stored for the variation when the value is the one of the flag (an object or an array that the evaluation took from the variation), else the value itself, which the response encodes. The bytes of both are the same.

A value that is the default of the caller (an error or a disabled flag) is never replaced: it is not the value of the variation, whatever the variation is named. A nil enc (a flag set that stores no encodings) returns the value.

func Handle added in v0.2.0

func Handle(h func(http.ResponseWriter, *http.Request) error, exposeError bool) http.Handler

Handle makes a handler that returns the error to send a http.Handler: the error is sent as the response, and kept for the access log.

func HasBody added in v0.3.0

func HasBody(contentLength, transferEncoding string) bool

HasBody reports whether a request with these Content-Length and Transfer-Encoding headers carries a body.

func IsJSON added in v0.2.0

func IsJSON(contentType string) bool

IsJSON reports whether the content type is application/json, whatever its parameters.

func QueryValue added in v0.3.0

func QueryValue(rawQuery, name string) string

QueryValue returns the first value of the parameter of a raw query, like url.Values.Get of url.ParseQuery does: a pair that does not parse (a bad escape, a semicolon) is skipped. It builds no map: the cost of a query that does not carry the parameter is a scan, whatever its size, and nothing else is allocated for it. The key of a stream comes through it, so a client can make the relay read a long query for nothing.

func RequestFlagSetName

func RequestFlagSetName(ctx context.Context, flagsetManager service.FlagSetResolver, apiKey string) (string, error)

RequestFlagSetName returns the name of the flag set of the request, like RequestFlagSet. The name is added to the logs of the request when it is looked up here: the authentication did it when it resolved the name.

func StreamAPIKey added in v1.0.0

func StreamAPIKey(r *http.Request) string

StreamAPIKey is the API key of a request to a change stream. A client that can set headers sends it in X-API-Key or as a bearer token, so that it is in no URL and no access log. A browser EventSource cannot set headers: its key stays in the apiKey query parameter (the URL the bulk evaluation advertises). The header wins when both are sent; an Authorization header that is not a bearer token (a proxy may add one) is ignored.

func WriteError added in v0.2.0

func WriteError(w http.ResponseWriter, r *http.Request, err error, exposeError bool)

WriteError sends the error as the response. It sends nothing for a HEAD request but the status.

func WriteJSON added in v0.2.0

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

WriteJSON sends v as the JSON body of the response, with the status code.

func WriteRefusal added in v0.3.0

func WriteRefusal(w http.ResponseWriter, r *http.Request, code int, body string)

WriteRefusal sends a refusal whose JSON body is a constant (it ends with the newline of the encoder): nothing is built for it, a request that is refused costs no more than the answer. The body of the request is not read: on HTTP/1 a request that carries one gets "Connection: close", so the server closes the connection instead of reading up to 256 KiB of the body to reuse it (HTTP/2 resets the stream, which is already cheap, and "Connection" is not sent there: it would close the connection of the other requests it carries). It sends nothing but the status for a HEAD request, like WriteError.

Types

type ErrorBody added in v0.2.0

type ErrorBody struct {
	Message string `example:"Not Found"                                  json:"message"`
	Error   string `example:"the wrapped error, only at the debug level" json:"error,omitempty"`
}

ErrorBody is the JSON body sent for an error.

func ErrorResponse added in v0.2.0

func ErrorResponse(err error, exposeError bool) (int, ErrorBody)

ErrorResponse returns the status code and the body to send to the client for err: the status of the error when it has one (500 otherwise) and its message. exposeError adds the wrapped error to the body.

type HTTPError added in v0.2.0

type HTTPError struct {
	Message string
	Code    int
	// contains filtered or unexported fields
}

HTTPError is an error that carries the status code of the response and the message sent to the client. The body sent for it is {"message": ...}, plus {"error": ...} when the relay proxy runs with the debug level.

func FlagSet

func FlagSet(flagsetManager service.FlagSetResolver, apiKey string) (service.FlagSet, *HTTPError)

FlagSet retrieves the flagset for the given API key from the resolver This layer ensure that the resolver is initialized and that the API key is valid.

func NewHTTPError added in v0.2.0

func NewHTTPError(code int, message string) *HTTPError

NewHTTPError returns an HTTPError with the given status code and message.

func RequestFlagSet

func RequestFlagSet(
	ctx context.Context, flagsetManager service.FlagSetResolver, apiKey string,
) (service.FlagSet, *HTTPError)

RequestFlagSet returns the flag set of the request: the one resolved by the authentication when there is one, or else the one of the API key of the request (authentication disabled, default mode).

func WrapHTTPError added in v0.2.0

func WrapHTTPError(code int, err error) *HTTPError

WrapHTTPError returns an HTTPError with the status code, the text of the status as message and err as the wrapped error (exposed in the body at the debug level only).

func (*HTTPError) ContentType added in v0.2.0

func (*HTTPError) ContentType(ct string) string

ContentType keeps the content type of the negotiation (huma defaults an error to application/problem+json).

func (*HTTPError) Error added in v0.2.0

func (e *HTTPError) Error() string

Error implements the error interface.

func (*HTTPError) GetStatus added in v0.2.0

func (e *HTTPError) GetStatus() int

GetStatus makes HTTPError a huma.StatusError.

func (*HTTPError) Schema added in v0.2.0

func (*HTTPError) Schema(r huma.Registry) *huma.Schema

Schema documents the error as the body it is sent as.

func (*HTTPError) StatusCode added in v0.2.0

func (e *HTTPError) StatusCode() int

StatusCode returns the status code of the response.

func (*HTTPError) Unwrap added in v0.2.0

func (e *HTTPError) Unwrap() error

Unwrap returns the wrapped error.

func (*HTTPError) WithCause added in v0.2.0

func (e *HTTPError) WithCause(cause error) *HTTPError

WithCause records the error that made the response, for errors.Is and errors.As: unlike the wrapped error of WrapHTTPError, it is never sent in the body.

type StatusError added in v0.2.0

type StatusError int

StatusError is the error of a status that has no HTTPError: the body is the text of the status.

func (StatusError) Error added in v0.2.0

func (s StatusError) Error() string

Error returns the text of the status.

func (StatusError) StatusCode added in v0.2.0

func (s StatusError) StatusCode() int

StatusCode returns the status code.

type StoredBody added in v1.0.0

type StoredBody interface {
	// StoredJSON returns the bytes to send, or nil when the value has none and must be encoded.
	StoredJSON() []byte
}

StoredBody is a response body that is already the encoded JSON document the endpoint sends, final newline included (what the JSON encoder of the relay writes for the value). The JSON format of the relay writes these bytes as they are, in one write, instead of encoding the value again. The bytes are shared between requests and READ-ONLY: a body stores them once and never changes them.

Jump to

Keyboard shortcuts

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