interceptors

package
v0.9.13 Latest Latest
Warning

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

Go to latest
Published: Feb 12, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package interceptors provides gRPC interceptors for Velocity applications.

Interceptors are middleware for gRPC that can:

  • Log requests and responses
  • Handle authentication
  • Recover from panics
  • Add request IDs
  • Rate limit requests

Usage:

server := grpc.NewServer(grpc.WithPort("50051"))
server.Use(
    interceptors.RecoveryInterceptor(),
    interceptors.LoggingInterceptor(),
)
server.UseStream(
    interceptors.StreamRecoveryInterceptor(),
    interceptors.StreamLoggingInterceptor(),
)

Or using UseAll with pairs:

server.UseAll(
    interceptors.Recovery(),
    interceptors.Logging(),
)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthInterceptor

func AuthInterceptor(validator AuthValidator, opts ...AuthOption) grpc.UnaryServerInterceptor

AuthInterceptor creates a unary auth interceptor. This is a convenience function for when you only need the unary interceptor.

func ContextWithClaims

func ContextWithClaims(ctx context.Context, claims Claims) context.Context

ContextWithClaims adds claims to the context

func ContextWithRequestID

func ContextWithRequestID(ctx context.Context, requestID string) context.Context

ContextWithRequestID adds a request ID to the context

func LoggingInterceptor

func LoggingInterceptor(opts ...LoggingOption) grpc.UnaryServerInterceptor

LoggingInterceptor creates a unary logging interceptor. This is a convenience function for when you only need the unary interceptor.

func RecoveryInterceptor

func RecoveryInterceptor(opts ...RecoveryOption) grpc.UnaryServerInterceptor

RecoveryInterceptor creates a unary recovery interceptor. This is a convenience function for when you only need the unary interceptor.

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext extracts the request ID from the context. Returns empty string if no request ID is present.

func StreamAuthInterceptor

func StreamAuthInterceptor(validator AuthValidator, opts ...AuthOption) grpc.StreamServerInterceptor

StreamAuthInterceptor creates a stream auth interceptor. This is a convenience function for when you only need the stream interceptor.

func StreamLoggingInterceptor

func StreamLoggingInterceptor(opts ...LoggingOption) grpc.StreamServerInterceptor

StreamLoggingInterceptor creates a stream logging interceptor. This is a convenience function for when you only need the stream interceptor.

func StreamRecoveryInterceptor

func StreamRecoveryInterceptor(opts ...RecoveryOption) grpc.StreamServerInterceptor

StreamRecoveryInterceptor creates a stream recovery interceptor. This is a convenience function for when you only need the stream interceptor.

Types

type AuthConfig

type AuthConfig struct {
	// Validator is the token validator implementation (required)
	Validator AuthValidator

	// PublicMethods are method prefixes that don't require authentication.
	// Examples: "/grpc.health.v1.Health/", "/mypackage.MyService/PublicMethod"
	PublicMethods []string

	// TokenExtractor extracts the token from context.
	// Defaults to extracting from "authorization" header with "Bearer " prefix.
	TokenExtractor func(ctx context.Context) (string, error)

	// OnAuthError is called when authentication fails.
	// Can be used for logging or custom error responses.
	OnAuthError func(ctx context.Context, method string, err error)
}

AuthConfig configures the auth interceptor

type AuthOption

type AuthOption func(*AuthConfig)

AuthOption configures auth behavior

func WithOnAuthError

func WithOnAuthError(handler func(ctx context.Context, method string, err error)) AuthOption

WithOnAuthError sets a callback for auth errors

func WithPublicMethods

func WithPublicMethods(methods ...string) AuthOption

WithPublicMethods sets methods that don't require authentication

func WithTokenExtractor

func WithTokenExtractor(extractor func(ctx context.Context) (string, error)) AuthOption

WithTokenExtractor sets a custom token extractor

type AuthValidator

type AuthValidator interface {
	// ValidateToken validates a bearer token and returns claims.
	// Returns an error if the token is invalid.
	ValidateToken(ctx context.Context, token string) (Claims, error)
}

AuthValidator is the interface that must be implemented to validate tokens. Applications provide their own implementation that validates tokens and returns claims.

type BasicClaims

type BasicClaims struct {
	UserID uint
	TeamID uint
}

BasicClaims is a simple implementation of the Claims interface

func (*BasicClaims) GetTeamID

func (c *BasicClaims) GetTeamID() uint

GetTeamID returns the team ID

func (*BasicClaims) GetUserID

func (c *BasicClaims) GetUserID() uint

GetUserID returns the user ID

type Claims

type Claims interface {
	// GetUserID returns the authenticated user's ID
	GetUserID() uint
	// GetTeamID returns the authenticated user's team ID (0 if none)
	GetTeamID() uint
}

Claims represents authenticated user claims. Applications can implement this interface with their own claims structure.

func ClaimsFromContext

func ClaimsFromContext(ctx context.Context) Claims

ClaimsFromContext extracts claims from the context. Returns nil if no claims are present.

type Interceptor

type Interceptor func() InterceptorPair

Interceptor is a function that returns an InterceptorPair. This allows for lazy initialization and configuration.

type InterceptorPair

type InterceptorPair struct {
	Unary  grpc.UnaryServerInterceptor
	Stream grpc.StreamServerInterceptor
}

InterceptorPair holds both unary and stream interceptor variants. Many interceptors need both variants, so this groups them together.

func Auth

func Auth(validator AuthValidator, opts ...AuthOption) InterceptorPair

Auth creates an auth interceptor pair that validates bearer tokens. The validator is responsible for validating tokens and returning claims.

func Logging

func Logging(opts ...LoggingOption) InterceptorPair

Logging creates a logging interceptor pair that logs all requests.

func Recovery

func Recovery(opts ...RecoveryOption) InterceptorPair

Recovery creates a recovery interceptor pair that recovers from panics. It logs the panic and returns an internal error to the client.

type LoggingConfig

type LoggingConfig struct {
	// Logger is the logger to use. Defaults to the global logger.
	Logger log.Logger

	// LogPayloads enables logging of request/response payloads
	LogPayloads bool

	// SkipMethods is a list of methods to skip logging
	SkipMethods map[string]bool

	// SkipHealthChecks skips logging for health check endpoints
	SkipHealthChecks bool

	// SlowThreshold logs requests slower than this duration at warn level
	SlowThreshold time.Duration

	// ExtraFields adds extra fields to log entries
	ExtraFields func(ctx context.Context) []interface{}

	// EventDispatcher dispatches gRPC events. If nil, no events are dispatched.
	EventDispatcher grpcevents.EventDispatchFunc
}

LoggingConfig configures the logging interceptor

type LoggingOption

type LoggingOption func(*LoggingConfig)

LoggingOption configures logging behavior

func WithEventDispatcher added in v0.9.11

func WithEventDispatcher(dispatcher grpcevents.EventDispatchFunc) LoggingOption

WithEventDispatcher sets the event dispatcher for gRPC events.

func WithExtraFields

func WithExtraFields(fn func(ctx context.Context) []interface{}) LoggingOption

WithExtraFields adds extra fields to log entries

func WithLogPayloads

func WithLogPayloads(enabled bool) LoggingOption

WithLogPayloads enables payload logging

func WithLoggingLogger

func WithLoggingLogger(logger log.Logger) LoggingOption

WithLoggingLogger sets a custom logger

func WithSkipHealthChecks

func WithSkipHealthChecks(skip bool) LoggingOption

WithSkipHealthChecks skips logging for health check endpoints

func WithSkipMethods

func WithSkipMethods(methods ...string) LoggingOption

WithSkipMethods sets methods to skip logging

func WithSlowThreshold

func WithSlowThreshold(d time.Duration) LoggingOption

WithSlowThreshold sets the slow request threshold

type RecoveryConfig

type RecoveryConfig struct {
	// Logger is the logger to use. Defaults to the global logger.
	Logger log.Logger

	// EnableStackTrace enables logging of stack traces on panic
	EnableStackTrace bool

	// PanicHandler is an optional custom handler for panics.
	// If set, it's called before the standard error response is returned.
	// Return an error to override the default internal error response.
	PanicHandler func(ctx context.Context, p interface{}) error
}

RecoveryConfig configures the recovery interceptor

type RecoveryOption

type RecoveryOption func(*RecoveryConfig)

RecoveryOption configures recovery behavior

func WithPanicHandler

func WithPanicHandler(handler func(ctx context.Context, p interface{}) error) RecoveryOption

WithPanicHandler sets a custom panic handler

func WithRecoveryLogger

func WithRecoveryLogger(logger log.Logger) RecoveryOption

WithRecoveryLogger sets a custom logger for recovery

func WithStackTrace

func WithStackTrace(enabled bool) RecoveryOption

WithStackTrace enables stack trace logging

Jump to

Keyboard shortcuts

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