Documentation
¶
Overview ¶
Package reqkey is the official Go SDK for ReqKey API-key validation and request analytics.
Create a Client to call ReqKey directly, or use NewHTTPMiddleware and the framework adapter packages for net/http, Gin, Echo, and Fiber.
Index ¶
- Constants
- Variables
- func ContextWithOutcome(ctx context.Context, outcome *AuthorizationOutcome) context.Context
- func MustHTTPMiddleware(options MiddlewareOptions) func(http.Handler) http.Handler
- func NewHTTPMiddleware(options MiddlewareOptions) (func(http.Handler) http.Handler, error)
- func Ptr[T any](v T) *T
- func ValidationErrorFromContext(ctx context.Context) (error, bool)
- type APIError
- type AuthenticationError
- type AuthorizationKind
- type AuthorizationOutcome
- type AuthorizationState
- type Client
- type ClientAPI
- type ClientIPResolver
- type ClientOptions
- type ConfigurationError
- type ConsumerKeyResolver
- type ConsumerNameResolver
- type CreditsResolver
- type DenialResponse
- type ErrorCode
- type FailureMode
- type IngestEvent
- type KeyLocation
- type KeyScheme
- type MiddlewareErrorEvent
- type MiddlewareErrorHandler
- type MiddlewareMode
- type MiddlewareOptions
- type MiddlewareRequest
- type MiddlewareResponse
- type PathResolver
- type ProtectionResolver
- type RequestIDResolver
- type Runtime
- type StringResolver
- type TimeoutError
- type TransportError
- type VerificationReason
- type VerificationResult
- type VerifyOptions
Constants ¶
const ( // Version is the semantic version of this SDK. Version = "0.1.0" // DefaultBaseURL is the production ReqKey API endpoint. DefaultBaseURL = "https://api.reqkey.com" // DefaultTimeout is applied independently to every ReqKey API call. DefaultTimeout = 2 * time.Second // MaxBodyCharacters is the largest request or response body sent to analytics. MaxBodyCharacters = 1000 )
Variables ¶
var ( // ErrConfiguration marks invalid SDK configuration or call input. ErrConfiguration = errors.New("reqkey configuration error") // ErrTransport marks a failure to reach ReqKey. ErrTransport = errors.New("reqkey transport error") // ErrTimeout marks an API call that exceeded its deadline. ErrTimeout = errors.New("reqkey timeout") // ErrAPI marks an unexpected ReqKey HTTP response. ErrAPI = errors.New("reqkey API error") // ErrAuthentication marks a rejected project credential. ErrAuthentication = errors.New("reqkey authentication error") )
var DefaultErrorMessages = map[ErrorCode]string{ ErrorMissingAPIKey: "An API key is required.", ErrorInvalidAPIKey: "The API key is invalid or inactive.", ErrorInsufficientCredits: "The API key has insufficient credits.", ErrorAccessDenied: "The API key is not allowed to access this API.", ErrorRateLimited: "The API key has exceeded its rate limit.", ErrorReqKeyUnavailable: "API key verification is temporarily unavailable.", }
DefaultErrorMessages contains safe messages returned by middleware.
Functions ¶
func ContextWithOutcome ¶
func ContextWithOutcome(ctx context.Context, outcome *AuthorizationOutcome) context.Context
ContextWithOutcome attaches the public result of authorization. Framework adapters use it to provide the same context API as net/http.
func MustHTTPMiddleware ¶
func MustHTTPMiddleware(options MiddlewareOptions) func(http.Handler) http.Handler
MustHTTPMiddleware is NewHTTPMiddleware for configuration known at startup. It panics when options are invalid.
func NewHTTPMiddleware ¶
NewHTTPMiddleware creates standard net/http middleware.
Types ¶
type AuthenticationError ¶
type AuthenticationError struct{ *APIError }
AuthenticationError indicates a missing, invalid, or expired project key.
func (*AuthenticationError) Unwrap ¶
func (e *AuthenticationError) Unwrap() error
type AuthorizationKind ¶
type AuthorizationKind string
AuthorizationKind describes the middleware action for a request.
const ( AuthorizationSkip AuthorizationKind = "skip" AuthorizationAllow AuthorizationKind = "allow" AuthorizationDeny AuthorizationKind = "deny" )
type AuthorizationOutcome ¶
type AuthorizationOutcome struct {
Kind AuthorizationKind
State *AuthorizationState
Decision *VerificationResult
ValidationError error
Denial *DenialResponse
ResponseHeaders http.Header
}
AuthorizationOutcome is returned by Runtime.Authorize.
type AuthorizationState ¶
type AuthorizationState struct {
Request *MiddlewareRequest
RequestStartedAt time.Time
HandlerStartedAt time.Time
ConsumerKey string
Decision *VerificationResult
}
AuthorizationState correlates authorization with later analytics.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client calls the ReqKey HTTP API. It is safe for concurrent use.
func NewClient ¶
func NewClient(options ClientOptions) (*Client, error)
NewClient creates a ReqKey client.
func NewClientFromEnv ¶
func NewClientFromEnv(options ClientOptions) (*Client, error)
NewClientFromEnv creates a client using REQKEY_PROJECT_KEY, falling back to the legacy REQKEY_ROOT_KEY. Explicit keys in options take precedence.
func (*Client) Ingest ¶
func (c *Client) Ingest(ctx context.Context, event IngestEvent) error
Ingest sends request and response metadata to ReqKey analytics.
func (*Client) Verify ¶
func (c *Client) Verify(ctx context.Context, key string, options VerifyOptions) (*VerificationResult, error)
Verify validates a consumer API key and atomically deducts credits.
type ClientAPI ¶
type ClientAPI interface {
Verify(context.Context, string, VerifyOptions) (*VerificationResult, error)
Ingest(context.Context, IngestEvent) error
}
ClientAPI is implemented by Client and can be replaced by a test double.
type ClientIPResolver ¶
type ClientIPResolver = StringResolver
type ClientOptions ¶
type ClientOptions struct {
ProjectKey string
RootKey string
BaseURL string
Timeout time.Duration
HTTPClient *http.Client
}
ClientOptions configures a Client. ProjectKey is preferred; RootKey is a backward-compatible alias and must not be supplied at the same time.
type ConfigurationError ¶
type ConfigurationError struct{ Message string }
ConfigurationError describes invalid configuration or input.
func (*ConfigurationError) Error ¶
func (e *ConfigurationError) Error() string
func (*ConfigurationError) Unwrap ¶
func (e *ConfigurationError) Unwrap() error
type ConsumerKeyResolver ¶
type ConsumerKeyResolver = StringResolver
type ConsumerNameResolver ¶
type ConsumerNameResolver = StringResolver
type CreditsResolver ¶
type CreditsResolver func(context.Context, *MiddlewareRequest) (int, error)
type DenialResponse ¶
DenialResponse is a normalized middleware rejection.
func (*DenialResponse) Body ¶
func (d *DenialResponse) Body() map[string]string
Body returns the JSON-compatible denial payload.
type ErrorCode ¶
type ErrorCode string
ErrorCode is a stable customer-facing middleware denial category.
const ( ErrorMissingAPIKey ErrorCode = "missing_api_key" ErrorInvalidAPIKey ErrorCode = "invalid_api_key" ErrorInsufficientCredits ErrorCode = "insufficient_credits" ErrorAccessDenied ErrorCode = "access_denied" ErrorRateLimited ErrorCode = "rate_limited" ContextDecisionKey = "reqkey.decision" ContextRequestIDKey = "reqkey.request_id" ContextErrorKey = "reqkey.error" )
type FailureMode ¶
type FailureMode string
FailureMode controls what happens when ReqKey itself is unavailable.
const ( FailureClosed FailureMode = "closed" FailureOpen FailureMode = "open" )
type IngestEvent ¶
type IngestEvent struct {
RequestID string
APIID string
Method string
Endpoint string
Path string
StatusCode *int
LatencyMS *int64
ClientIP string
UserAgent string
UserID string
ConsumerName string
APIKey string
ConsumerID string
QueryParams map[string]any
RequestHeaders map[string]string
ResponseHeaders map[string]string
RequestBody string
ResponseBody string
Timestamp string
}
IngestEvent contains request and response metadata for ReqKey analytics. RequestID, APIID, or both must be supplied.
type KeyLocation ¶
type KeyLocation string
KeyLocation selects where middleware reads the consumer key.
const ( KeyInHeader KeyLocation = "header" KeyInQuery KeyLocation = "query" KeyInCookie KeyLocation = "cookie" )
type MiddlewareErrorEvent ¶
type MiddlewareErrorEvent struct {
Operation string
Err error
Method string
Path string
RequestID string
StatusCode int
}
MiddlewareErrorEvent is a safe notification for validation or ingestion failures. It intentionally excludes credentials and captured headers.
func (MiddlewareErrorEvent) Message ¶
func (e MiddlewareErrorEvent) Message() string
Message returns a human-readable description suitable for logs and alerts.
type MiddlewareErrorHandler ¶
type MiddlewareErrorHandler func(context.Context, MiddlewareErrorEvent)
type MiddlewareMode ¶
type MiddlewareMode string
MiddlewareMode selects validation, analytics ingestion, or both.
const ( ModeValidate MiddlewareMode = "validate" ModeIngest MiddlewareMode = "ingest" ModeBoth MiddlewareMode = "both" )
type MiddlewareOptions ¶
type MiddlewareOptions struct {
APIID string
Client ClientAPI
ProjectKey string
RootKey string
BaseURL string
Timeout time.Duration
HTTPClient *http.Client
Mode MiddlewareMode
Enabled *bool
KeyLocation KeyLocation
KeyName string
KeyScheme KeyScheme
GetConsumerKey ConsumerKeyResolver
Credits *int
CreditsResolver CreditsResolver
ExcludePaths []string
SkipMethods []string
ShouldProtect ProtectionResolver
RequestIDResolver RequestIDResolver
PathResolver PathResolver
ConsumerNameResolver ConsumerNameResolver
ClientIPResolver ClientIPResolver
OnError MiddlewareErrorHandler
IngestDeniedRequests *bool
ErrorMessages map[ErrorCode]string
CaptureQueryParams bool
CaptureRequestHeaders bool
CaptureResponseHeaders bool
CaptureResponseBody bool
CaptureClientIP bool
CaptureUserAgent *bool
ExcludedHeaders []string
FailureMode FailureMode
}
MiddlewareOptions configures every framework adapter. Pointer booleans are used only where the default is true; nil selects the documented default.
type MiddlewareRequest ¶
type MiddlewareRequest struct {
Raw any
Method string
URL *url.URL
Path string
Headers http.Header
Cookies map[string]string
ClientIP string
}
MiddlewareRequest is the framework-neutral request view used by resolvers. Raw contains the native *http.Request, *gin.Context, echo.Context, or fiber.Ctx supplied by the adapter.
func NewHTTPRequest ¶
func NewHTTPRequest(request *http.Request) *MiddlewareRequest
NewHTTPRequest converts a standard request for Runtime.Authorize.
type MiddlewareResponse ¶
type MiddlewareResponse struct {
StatusCode int
Headers http.Header
Body string
Latency time.Duration
}
MiddlewareResponse contains the response metadata recorded by an adapter.
type PathResolver ¶
type PathResolver = StringResolver
type ProtectionResolver ¶
type ProtectionResolver func(context.Context, *MiddlewareRequest) (bool, error)
type RequestIDResolver ¶
type RequestIDResolver = StringResolver
type Runtime ¶
type Runtime struct {
// contains filtered or unexported fields
}
Runtime is the framework-neutral authorization and analytics engine used by all adapters. It is public so unsupported frameworks can integrate without duplicating ReqKey protocol and privacy behavior.
func NewRuntime ¶
func NewRuntime(options MiddlewareOptions) (*Runtime, error)
NewRuntime validates options and constructs the shared middleware engine.
func (*Runtime) Authorize ¶
func (r *Runtime) Authorize(ctx context.Context, request *MiddlewareRequest) (*AuthorizationOutcome, error)
Authorize evaluates bypass rules, extracts the consumer key, and validates when the selected mode requires it.
func (*Runtime) CapturesResponseBody ¶
CapturesResponseBody reports whether an adapter should retain a bounded body.
func (*Runtime) Mode ¶
func (r *Runtime) Mode() MiddlewareMode
Mode returns the configured middleware mode.
func (*Runtime) Record ¶
func (r *Runtime) Record(ctx context.Context, state *AuthorizationState, response MiddlewareResponse)
Record sends correlated request/response analytics. Service and resolver failures are reported through OnError and never replace the app response.
type StringResolver ¶
type StringResolver func(context.Context, *MiddlewareRequest) (string, error)
type TimeoutError ¶
TimeoutError describes a ReqKey request that exceeded its timeout.
func (*TimeoutError) Error ¶
func (e *TimeoutError) Error() string
func (*TimeoutError) Unwrap ¶
func (e *TimeoutError) Unwrap() error
type TransportError ¶
TransportError describes a network failure while calling ReqKey.
func (*TransportError) Error ¶
func (e *TransportError) Error() string
func (*TransportError) Unwrap ¶
func (e *TransportError) Unwrap() error
type VerificationReason ¶
type VerificationReason string
VerificationReason is a stable SDK-level category for a key decision.
const ( ReasonValid VerificationReason = "valid" ReasonInvalidKey VerificationReason = "invalid_key" ReasonInsufficientCredits VerificationReason = "insufficient_credits" ReasonForbidden VerificationReason = "forbidden" ReasonRateLimited VerificationReason = "rate_limited" ReasonDenied VerificationReason = "denied" )
type VerificationResult ¶
type VerificationResult struct {
Valid bool
Reason VerificationReason
StatusCode int
RequestID string
Message string
APIID string
APIName string
Resource string
CreditsRemaining *int64
CreditsLimit *int64
AllowedAPIs []string
RetryAfter *float64
RateLimit map[string]any
Raw map[string]any
}
VerificationResult is the normalized result of /key/validate.
func DecisionFromContext ¶
func DecisionFromContext(ctx context.Context) (*VerificationResult, bool)
DecisionFromContext returns the successful ReqKey decision attached by NewHTTPMiddleware or a framework adapter.
func (VerificationResult) Allowed ¶
func (r VerificationResult) Allowed() bool
Allowed reads naturally inside authorization code.
type VerifyOptions ¶
type VerifyOptions struct {
APIID string
// Credits defaults to 1 when nil. Use Ptr(0) for a zero-credit check.
Credits *int
Resource string
}
VerifyOptions configures a single key verification.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package echo integrates ReqKey with Echo v4.
|
Package echo integrates ReqKey with Echo v4. |
|
examples
|
|
|
chi
command
|
|
|
echo
command
|
|
|
fiber
command
|
|
|
gin
command
|
|
|
net-http
command
|
|
|
Package fiber integrates ReqKey with Fiber v3.
|
Package fiber integrates ReqKey with Fiber v3. |
|
Package gin integrates ReqKey with Gin.
|
Package gin integrates ReqKey with Gin. |
|
internal
|
|
|
bodycapture
Package bodycapture contains the bounded response-body capture shared by ReqKey's framework adapters.
|
Package bodycapture contains the bounded response-body capture shared by ReqKey's framework adapters. |