reqkey

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: MIT Imports: 15 Imported by: 0

README

ReqKey Go SDK

CI Go Reference

The official Go SDK for ReqKey: API-key validation, credit enforcement, and request analytics for Go services.

It includes:

  • A concurrency-safe client for /key/validate and /ingest
  • Consistent validation decisions and typed errors
  • net/http middleware with no framework dependency
  • Direct compatibility with Chi, Gorilla/Mux, and other http.Handler routers
  • Native adapters for Gin, Echo v4, and Fiber v3
  • Validation-only, analytics-only, and correlated validation-plus-analytics modes
  • Static or request-aware credit costs
  • Header, Bearer token, query parameter, cookie, and custom key extraction
  • Privacy-safe header filtering and opt-in query, response, and client-IP capture
  • Open or closed behavior when ReqKey is unavailable

Install

go get github.com/Req-Key/reqkey-go@latest

Go modules are published from Git tags; there is no central upload step like npm or PyPI. Once a version tag is pushed and fetched through the Go proxy, its API documentation becomes discoverable on pkg.go.dev.

The current framework adapters target Gin 1.12, Echo 4.15, and Fiber 3.4. The module requires Go 1.25 or newer because those current framework releases do.

Why these integrations?

The standard library is the most common Go routing choice. Among full web frameworks, the 2025 Go ecosystem survey reports Gin at 48%, Echo at 16%, and Fiber at 11%; Chi is also a widely used net/http router at roughly 12%. Accordingly, ReqKey provides native adapters for the three frameworks whose request contexts require them, plus standard middleware that works directly with net/http, Chi, Gorilla/Mux, and other compatible routers. See the survey analysis.

Direct client

package main

import (
	"context"
	"log"
	"os"

	"github.com/Req-Key/reqkey-go"
)

func main() {
	client, err := reqkey.NewClient(reqkey.ClientOptions{
		ProjectKey: os.Getenv("REQKEY_PROJECT_KEY"),
	})
	if err != nil {
		log.Fatal(err)
	}

	decision, err := client.Verify(context.Background(), "consumer_api_key", reqkey.VerifyOptions{
		APIID:    "api_payments",
		Credits:  reqkey.Ptr(2),
		Resource: "/payments",
	})
	if err != nil {
		log.Fatal(err)
	}
	if !decision.Allowed() {
		log.Printf("denied: %s", decision.Reason)
		return
	}
	if decision.CreditsRemaining != nil {
		log.Printf("allowed; %d credits remain", *decision.CreditsRemaining)
	}
}

NewClientFromEnv reads REQKEY_PROJECT_KEY and falls back to the legacy REQKEY_ROOT_KEY name:

client, err := reqkey.NewClientFromEnv(reqkey.ClientOptions{})

VerifyOptions.Credits defaults to 1. Use reqkey.Ptr(0) for a deliberate zero-credit check.

Direct ingestion
status := 201
latency := int64(38)
err := client.Ingest(ctx, reqkey.IngestEvent{
	RequestID:  decision.RequestID,
	APIID:      "api_payments",
	Method:     "POST",
	Endpoint:   "/payments",
	Path:       "/payments?currency=USD",
	StatusCode: &status,
	LatencyMS:  &latency,
	ConsumerID: "consumer_123",
})

Ingestion requires RequestID, APIID, or both. Request and response bodies are truncated to 1,000 Unicode characters before transmission.

net/http

package main

import (
	"encoding/json"
	"net/http"
	"os"

	"github.com/Req-Key/reqkey-go"
)

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /protected", func(w http.ResponseWriter, r *http.Request) {
		decision, _ := reqkey.DecisionFromContext(r.Context())
		_ = json.NewEncoder(w).Encode(map[string]any{
			"ok":         true,
			"request_id": decision.RequestID,
		})
	})

	protect := reqkey.MustHTTPMiddleware(reqkey.MiddlewareOptions{
		ProjectKey: os.Getenv("REQKEY_PROJECT_KEY"),
		APIID:      "api_payments",
	})

	_ = http.ListenAndServe(":8080", protect(mux))
}

Gin

import (
	"os"

	"github.com/Req-Key/reqkey-go"
	reqkeygin "github.com/Req-Key/reqkey-go/gin"
	"github.com/gin-gonic/gin"
)

router := gin.Default()
router.Use(reqkeygin.MustMiddleware(reqkey.MiddlewareOptions{
	ProjectKey: os.Getenv("REQKEY_PROJECT_KEY"),
	APIID:      "api_payments",
}))
router.GET("/protected", func(c *gin.Context) {
	decision, _ := c.Get(reqkey.ContextDecisionKey)
	c.JSON(200, gin.H{"request_id": decision.(*reqkey.VerificationResult).RequestID})
})

Chi

Chi uses the standard func(http.Handler) http.Handler middleware contract, so the core adapter works directly—there is no separate ReqKey Chi package:

import (
	"github.com/Req-Key/reqkey-go"
	"github.com/go-chi/chi/v5"
	"os"
)

router := chi.NewRouter()
router.Use(reqkey.MustHTTPMiddleware(reqkey.MiddlewareOptions{
	ProjectKey: os.Getenv("REQKEY_PROJECT_KEY"),
	APIID:      "api_payments",
}))
router.Get("/protected", handler)

The same core middleware works with Gorilla/Mux and any other router built on http.Handler.

Echo

import (
	"os"

	"github.com/Req-Key/reqkey-go"
	reqkeyecho "github.com/Req-Key/reqkey-go/echo"
	"github.com/labstack/echo/v4"
)

server := echo.New()
server.Use(reqkeyecho.MustMiddleware(reqkey.MiddlewareOptions{
	ProjectKey: os.Getenv("REQKEY_PROJECT_KEY"),
	APIID:      "api_payments",
}))
server.GET("/protected", func(c echo.Context) error {
	decision := c.Get(reqkey.ContextDecisionKey).(*reqkey.VerificationResult)
	return c.JSON(200, map[string]string{"request_id": decision.RequestID})
})

Fiber v3

import (
	"os"

	"github.com/Req-Key/reqkey-go"
	reqkeyfiber "github.com/Req-Key/reqkey-go/fiber"
	"github.com/gofiber/fiber/v3"
)

app := fiber.New()
app.Use(reqkeyfiber.MustMiddleware(reqkey.MiddlewareOptions{
	ProjectKey: os.Getenv("REQKEY_PROJECT_KEY"),
	APIID:      "api_payments",
}))
app.Get("/protected", func(c fiber.Ctx) error {
	decision := c.Locals(reqkey.ContextDecisionKey).(*reqkey.VerificationResult)
	return c.JSON(fiber.Map{"request_id": decision.RequestID})
})

Complete programs are in examples/.

Request lifecycle

With Mode: reqkey.ModeBoth (the default):

consumer request
  -> extract consumer key
  -> call /key/validate
  -> denied: call /ingest, then return 401 / 402 / 403 / 429
  -> approved: run the application handler
  -> collect opted-in response metadata
  -> call /ingest with the validation requestId
  -> finish the middleware lifecycle

Denied requests are ingested by default so missing keys, exhausted credits, forbidden access, and rate-limit pressure appear in analytics. Set IngestDeniedRequests: reqkey.Ptr(false) to disable that behavior.

Response-body capture is bounded to the first 1,000 decoded characters. Binary and compressed responses are not captured. The net/http and Gin adapters forward writes as they happen; they do not buffer the full response. Fiber normally buffers its response internally, so its adapter reads Fiber's final response buffer after the handler.

Modes

Validation only:

Mode: reqkey.ModeValidate

Analytics only (does not require or validate a consumer key):

Mode: reqkey.ModeIngest

Validation plus correlated analytics:

Mode: reqkey.ModeBoth

In ingest-only mode, use RequestIDResolver if another component already performed validation and can provide the correlation ID.

Consumer key sources

Custom header, recommended:

KeyLocation: reqkey.KeyInHeader,
KeyName:     "X-Startup-Key",
KeyScheme:   reqkey.KeyRaw,

Authorization Bearer token:

KeyLocation: reqkey.KeyInHeader,
KeyName:     "Authorization",
KeyScheme:   reqkey.KeyBearer,

Query parameter:

KeyLocation: reqkey.KeyInQuery,
KeyName:     "api_key",

Cookie:

KeyLocation: reqkey.KeyInCookie,
KeyName:     "startup_key",

Query parameters are available for compatibility, but headers are safer because URLs are commonly retained in histories and access logs. When query capture is enabled, the configured consumer-key parameter is always redacted from both the captured map and path.

For a custom source:

GetConsumerKey: func(ctx context.Context, request *reqkey.MiddlewareRequest) (string, error) {
	return request.Headers.Get("X-Custom-Key"), nil
},

request.Raw contains the adapter's native request value when a resolver needs framework-specific data.

Middleware options

Field Default Purpose
ProjectKey environment Server-side project credential.
RootKey Legacy alias for ProjectKey; do not set both.
APIID required ReqKey API being protected or observed.
Client automatic Injectable reqkey.ClientAPI, useful for tests.
BaseURL https://api.reqkey.com ReqKey API origin.
Timeout 2s Timeout used when the middleware creates its client.
Mode ModeBoth ModeValidate, ModeIngest, or ModeBoth.
Enabled true Set reqkey.Ptr(false) to bypass ReqKey.
KeyLocation KeyInHeader Header, query parameter, or cookie.
KeyName X-API-Key Customer-facing credential name.
KeyScheme KeyRaw KeyRaw or KeyBearer for headers.
GetConsumerKey Custom consumer-key resolver.
Credits 1 Static non-negative request cost.
CreditsResolver Request-aware non-negative cost resolver.
ExcludePaths empty Exact paths or trailing-* prefix patterns.
SkipMethods OPTIONS Methods that bypass ReqKey. An empty non-nil slice skips none.
ShouldProtect Dynamic bypass predicate.
RequestIDResolver Correlation ID for ingest-only mode.
PathResolver request path Resource used for validation and analytics.
ConsumerNameResolver Optional analytics display name.
ClientIPResolver framework address Override trusted client-IP resolution.
OnError Validation or ingestion service-failure callback.
IngestDeniedRequests true Record denied traffic in ModeBoth.
ErrorMessages built in Override customer-facing denial messages by error code.
CaptureQueryParams false Capture redacted query values and append them to Path.
CaptureRequestHeaders false Capture request headers after filtering.
CaptureResponseHeaders false Capture response headers after filtering.
CaptureResponseBody false Capture up to 1,000 textual response characters.
CaptureClientIP false Capture the framework-resolved client IP.
CaptureUserAgent true Capture User-Agent; set reqkey.Ptr(false) to disable.
ExcludedHeaders sensitive defaults Add case-insensitive header names to redact.
FailureMode FailureClosed Deny or continue when ReqKey cannot be reached.

Default header filtering removes Authorization, Cookie, Proxy-Authorization, Set-Cookie, X-API-Key, the configured KeyName, and every custom ExcludedHeaders entry.

Request-aware configuration

Dynamic credits:

CreditsResolver: func(ctx context.Context, request *reqkey.MiddlewareRequest) (int, error) {
	if request.Method == http.MethodPost {
		return 5, nil
	}
	return 1, nil
},

Path exclusions and dynamic protection can be combined:

ExcludePaths: []string{"/health", "/public/*"},
ShouldProtect: func(ctx context.Context, request *reqkey.MiddlewareRequest) (bool, error) {
	return request.Headers.Get("X-Internal-Request") != "true", nil
},

Failure handling

The default is fail closed: a validation transport, timeout, authentication, or unexpected API failure returns 503. To let the application continue:

FailureMode: reqkey.FailureOpen,

The error is then available from reqkey.ValidationErrorFromContext, reqkey.ContextErrorKey in Gin/Echo/Fiber, and OnError:

OnError: func(ctx context.Context, event reqkey.MiddlewareErrorEvent) {
	log.Printf("ReqKey %s failed on %s %s: %v",
		event.Operation, event.Method, event.Path, event.Err)
},

Ingestion failures never replace the application response. Exceptions or panics inside OnError are isolated from request handling.

Errors

Use errors.Is for broad handling and errors.As for response details:

decision, err := client.Verify(ctx, key, reqkey.VerifyOptions{})
if errors.Is(err, reqkey.ErrTimeout) {
	// Retry or apply a service-specific fallback.
}

var apiErr *reqkey.APIError
if errors.As(err, &apiErr) {
	log.Printf("ReqKey returned %d: %s", apiErr.StatusCode, apiErr.Message)
}

Available sentinels are ErrConfiguration, ErrTransport, ErrTimeout, ErrAPI, and ErrAuthentication.

Development

go mod tidy
gofmt -w .
go vet ./...
go test -race ./...

Publishing

This directory is designed to become the root of the public github.com/Req-Key/reqkey-go repository.

  1. Confirm the final repository path matches the module line in go.mod.

  2. Update Version in types.go and CHANGELOG.md.

  3. Run sh scripts/check-release.sh v0.1.0.

  4. Commit and push the source.

  5. Create and push an immutable semantic-version tag: git tag v0.1.0 && git push origin v0.1.0.

  6. Ask the Go proxy to index it:

    GOPROXY=proxy.golang.org go list -m github.com/Req-Key/reqkey-go@v0.1.0
    

Go's official publication workflow is documented at go.dev/doc/modules/publishing.

License

MIT

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

View Source
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

View Source
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")
)
View Source
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

func NewHTTPMiddleware(options MiddlewareOptions) (func(http.Handler) http.Handler, error)

NewHTTPMiddleware creates standard net/http middleware.

func Ptr

func Ptr[T any](v T) *T

Ptr returns a pointer to v. It is useful for optional numeric event fields and tri-state middleware settings.

func ValidationErrorFromContext

func ValidationErrorFromContext(ctx context.Context) (error, bool)

ValidationErrorFromContext returns the service error attached when FailureOpen allowed the request to continue.

Types

type APIError

type APIError struct {
	Message    string
	StatusCode int
	Body       map[string]any
}

APIError describes a response that is not an access decision.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Unwrap

func (e *APIError) Unwrap() error

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

type DenialResponse struct {
	StatusCode int
	Code       ErrorCode
	Message    string
	Headers    http.Header
}

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"
	ErrorReqKeyUnavailable   ErrorCode = "reqkey_unavailable"
	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 KeyScheme

type KeyScheme string

KeyScheme selects raw or Bearer header parsing.

const (
	KeyRaw    KeyScheme = "raw"
	KeyBearer KeyScheme = "bearer"
)

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

func (r *Runtime) CapturesResponseBody() bool

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

type TimeoutError struct {
	Operation string
	Cause     error
}

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

type TransportError struct {
	Message string
	Cause   error
}

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.

Jump to

Keyboard shortcuts

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