interceptor

package
v1.14.4 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2025 License: MIT Imports: 24 Imported by: 0

README

interceptor

Common interceptors for gRPC server and client side, including:


Example of use

All import paths are "github.com/go-dev-frame/sponge/pkg/grpc/interceptor".

Logging interceptor

gRPC server side

import (
    "github.com/go-dev-frame/sponge/pkg/grpc/interceptor"
    "github.com/go-dev-frame/sponge/pkg/logger"
    "google.golang.org/grpc"
)

func setServerOptions() []grpc.ServerOption {
    var options []grpc.ServerOption

    option := grpc.ChainUnaryInterceptor(
        // if you don't want to log reply data, you can use interceptor.StreamServerSimpleLog instead of interceptor.UnaryServerLog,
        interceptor.UnaryServerLog( // set unary server logging
            logger.Get(),
            interceptor.WithReplaceGRPCLogger(),
            //interceptor.WithMarshalFn(fn), // customised marshal function, default is jsonpb.Marshal
            //interceptor.WithLogIgnoreMethods(fullMethodNames), // ignore methods logging
            //interceptor.WithMaxLen(400), // logging max length, default 300
        ),
    )
    options = append(options, option)

    return options
}


// you can also set stream server logging

gRPC client side

import (
    "github.com/go-dev-frame/sponge/pkg/grpc/interceptor"
    "google.golang.org/grpc"
)

func setDialOptions() []grpc.DialOption {
    var options []grpc.DialOption

    option := grpc.WithChainUnaryInterceptor(
        interceptor.UnaryClientLog( // set unary client logging
            logger.Get(),
            interceptor.WithReplaceGRPCLogger(),
        ),
    )
    options = append(options, option)

    return options
}

// you can also set stream client logging

Recovery interceptor

gRPC server side

import (
    "github.com/go-dev-frame/sponge/pkg/grpc/interceptor"
    "google.golang.org/grpc"
)

func setServerOptions() []grpc.ServerOption {
    var options []grpc.ServerOption

    option := grpc.ChainUnaryInterceptor(
        interceptor.UnaryServerRecovery(),
    )
    options = append(options, option)

    return options
}

gRPC client side

import (
    "github.com/go-dev-frame/sponge/pkg/grpc/interceptor"
    "google.golang.org/grpc"
)

func setDialOptions() []grpc.DialOption {
    var options []grpc.DialOption

    option := grpc.WithChainUnaryInterceptor(
        interceptor.UnaryClientRecovery(),
    )
    options = append(options, option)

    return options
}

Retry interceptor

gRPC client side

import (
    "github.com/go-dev-frame/sponge/pkg/grpc/interceptor"
    "google.golang.org/grpc"
)

func setDialOptions() []grpc.DialOption {
    var options []grpc.DialOption

    // use insecure transfer
    options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

    // retry
    option := grpc.WithChainUnaryInterceptor(
        interceptor.UnaryClientRetry(
            //interceptor.WithRetryTimes(5), // modify the default number of retries to 3 by default
            //interceptor.WithRetryInterval(100*time.Millisecond), // modify the default retry interval, default 50 milliseconds
            //interceptor.WithRetryErrCodes(), // add trigger retry error code, default is codes.Internal, codes.DeadlineExceeded, codes.Unavailable
        ),
    )
    options = append(options, option)

    return options
}

Rate limiter interceptor

Adaptive flow limitation based on hardware resources.

gRPC server side

import (
    "github.com/go-dev-frame/sponge/pkg/grpc/interceptor"
    "google.golang.org/grpc"
)

func setDialOptions() []grpc.DialOption {
    var options []grpc.DialOption

    // use insecure transfer
    options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

    // rate limiter
    option := grpc.ChainUnaryInterceptor(
        interceptor.UnaryServerRateLimit(
            //interceptor.WithWindow(time.Second*5),
            //interceptor.WithBucket(200),
            //interceptor.WithCPUThreshold(600),
            //interceptor.WithCPUQuota(0),
        ),
    )
    options = append(options, option)

    return options
}

Circuit breaker interceptor

gRPC server side

import (
    "github.com/go-dev-frame/sponge/pkg/grpc/interceptor"
    "google.golang.org/grpc"
)

func setDialOptions() []grpc.DialOption {
    var options []grpc.DialOption

    // use insecure transfer
    options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

    // circuit breaker
    option := grpc.ChainUnaryInterceptor(
        interceptor.UnaryServerCircuitBreaker(
            //interceptor.WithValidCode(codes.DeadlineExceeded), // add error code for circuit breaker
            //interceptor.WithUnaryServerDegradeHandler(handler), // add custom degrade handler
            //interceptor.WithBreakerOption(
                //circuitbreaker.WithSuccess(75),           // default 60
                //circuitbreaker.WithRequest(200),          // default 100
                //circuitbreaker.WithBucket(20),            // default 10
                //circuitbreaker.WithWindow(time.Second*5), // default 3s
            //),
        ),
    )
    options = append(options, option)

    return options
}

Timeout interceptor

gRPC client side

import (
    "github.com/go-dev-frame/sponge/pkg/grpc/interceptor"
    "google.golang.org/grpc"
)

func setDialOptions() []grpc.DialOption {
    var options []grpc.DialOption

    // use insecure transfer
    options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

    option := grpc.WithChainUnaryInterceptor(
        interceptor.UnaryClientTimeout(time.Second), // set timeout
    )
    options = append(options, option)

    return options
}

Tracing interceptor

Initialize tracing

import (
    "github.com/go-dev-frame/sponge/pkg/tracer"
    "go.opentelemetry.io/otel"
)

// initialize tracing
func InitTrace(serviceName string) {
    exporter, err := tracer.NewJaegerAgentExporter("192.168.3.37", "6831")
    if err != nil {
        panic(err)
    }

    resource := tracer.NewResource(
        tracer.WithServiceName(serviceName),
        tracer.WithEnvironment("dev"),
        tracer.WithServiceVersion("demo"),
    )

    tracer.Init(exporter, resource) // collect all by default
}

// if necessary, you can create a span in the program
func SpanDemo(serviceName string, spanName string, ctx context.Context) {
_, span := otel.Tracer(serviceName).Start(
ctx, spanName,
trace.WithAttributes(attribute.String(spanName, time.Now().String())), // customised attributes
)
defer span.End()

// ......
}

gRPC server side

import (
    "github.com/go-dev-frame/sponge/pkg/grpc/interceptor"
    "google.golang.org/grpc"
)

func setServerOptions() []grpc.ServerOption {
    var options []grpc.ServerOption

    // use tracing
    option := grpc.UnaryInterceptor(
        interceptor.UnaryServerTracing(),
    )
    options = append(options, option)

    return options
}

gRPC client side

import (
    "github.com/go-dev-frame/sponge/pkg/grpc/interceptor"
    "google.golang.org/grpc"
)

func setDialOptions() []grpc.DialOption {
    var options []grpc.DialOption

    // use insecure transfer
    options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

    // use tracing
    option := grpc.WithUnaryInterceptor(
        interceptor.UnaryClientTracing(),
    )
    options = append(options, option)

    return options
}

Metrics interceptor

Click to view metrics examples.


Request id interceptor

gRPC server side

import (
    "github.com/go-dev-frame/sponge/pkg/grpc/interceptor"
    "google.golang.org/grpc"
)

func setServerOptions() []grpc.ServerOption {
    var options []grpc.ServerOption

    option := grpc.ChainUnaryInterceptor(
        interceptor.UnaryServerRequestID(),
    )
    options = append(options, option)

    return options
}

gRPC client side

import (
    "github.com/go-dev-frame/sponge/pkg/grpc/interceptor"
    "google.golang.org/grpc"
)

func setDialOptions() []grpc.DialOption {
    var options []grpc.DialOption

    // use insecure transfer
    options = append(options, grpc.WithTransportCredentials(insecure.NewCredentials()))

    option := grpc.WithChainUnaryInterceptor(
        interceptor.UnaryClientRequestID(),
    )
    options = append(options, option)

    return options
}

JWT authentication interceptor

gRPC server side

package main

import (
    "context"
    "net"
    "time"
    "github.com/go-dev-frame/sponge/pkg/grpc/interceptor"
    "github.com/go-dev-frame/sponge/pkg/jwt"
    "google.golang.org/grpc"
    userV1 "user/api/user/v1"
)

func main() {
    list, err := net.Listen("tcp", ":8282")
    server := grpc.NewServer(getUnaryServerOptions()...)
    userV1.RegisterUserServer(server, &user{})
    server.Serve(list)
    select {}
}

func getUnaryServerOptions() []grpc.ServerOption {
    var options []grpc.ServerOption

    // Case1: default options
    {
        options = append(options, grpc.UnaryInterceptor(
            interceptor.UnaryServerJwtAuth(),
        ))
    }

    // Case 2: custom options, signKey, extra verify function, rpc method
    {
        options = append(options, grpc.UnaryInterceptor(
            interceptor.UnaryServerJwtAuth(
                interceptor.WithSignKey([]byte("your_secret_key")),
                interceptor.WithExtraVerify(extraVerifyFn),
                interceptor.WithAuthIgnoreMethods(// specify the gRPC API to ignore token verification(full path)
                    "/api.user.v1.User/Register",
                    "/api.user.v1.User/Login",
                ),
            ),
        ))
    }

    return options
}

type user struct {
    userV1.UnimplementedUserServer
}

// Login ...
func (s *user) Login(ctx context.Context, req *userV1.LoginRequest) (*userV1.LoginReply, error) {
    // check user and password success

    uid := "100"
    fields := map[string]interface{}{"name":   "bob","age":    10,"is_vip": true}

    // Case 1: default jwt options, signKey, signMethod(HS256), expiry time(24 hour)
    {
        _, token, err := jwt.GenerateToken("100")
    }

    // Case 2: custom jwt options, signKey, signMethod(HS512), expiry time(12 hour), fields, claims
    {
        _, token, err := jwt.GenerateToken(
            uid,
            jwt.WithGenerateTokenSignKey([]byte("your_secret_key")),
            jwt.WithGenerateTokenSignMethod(jwt.HS384),
            jwt.WithGenerateTokenFields(fields),
            jwt.WithGenerateTokenClaims([]jwt.RegisteredClaimsOption{
                jwt.WithExpires(time.Hour * 12),
                // jwt.WithIssuedAt(now),
                // jwt.WithSubject("123"),
                // jwt.WithIssuer("https://auth.example.com"),
                // jwt.WithAudience("https://api.example.com"),
                // jwt.WithNotBefore(now),
                // jwt.WithJwtID("abc1234xxx"),
            }...),
        )
    }

    return &userV1.LoginReply{Token: token}, nil
}

func extraVerifyFn(ctx context.Context, claims *jwt.Claims) error {
    // judge whether the user is disabled, query whether jwt id exists from the blacklist
    //if CheckBlackList(uid, claims.ID) {
    //    return errors.New("user is disabled")
    //}

    // get fields from claims
    //uid := claims.UID
    //name, _ := claims.GetString("name")
    //age, _ := claims.GetInt("age")
    //isVip, _ := claims.GetBool("is_vip")

    return nil
}

// GetByID ...
func (s *user) GetByID(ctx context.Context, req *userV1.GetByIDRequest) (*userV1.GetByIDReply, error) {
    // ......

	claims,ok := interceptor.GetJwtClaims(ctx) // if necessary, claims can be got from gin context.

	// ......
}

gRPC client side

package main

import (
    "context"
    "github.com/go-dev-frame/sponge/pkg/grpc/grpccli"
    "github.com/go-dev-frame/sponge/pkg/grpc/interceptor"
    userV1 "user/api/user/v1"
)

func main() {
    conn, _ := grpccli.NewClient("127.0.0.1:8282")
    cli := userV1.NewUserClient(conn)

    uid := "100"
    ctx := context.Background()

    // Case 1: get authorization from header key is "authorization", value is "Bearer xxx"
    {
        ctx = interceptor.SetAuthToCtx(ctx, authorization)
    }
    // Case 2: get token from grpc server response result
    {
        ctx = interceptor.SetJwtTokenToCtx(ctx, token)
    }

    cli.GetByID(ctx, &userV1.GetUserByIDRequest{Id: 100})
}

Documentation

Overview

Package interceptor provides commonly used grpc client-side and server-side interceptors.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ContextRequestIDKey request id key for context
	ContextRequestIDKey = "request_id"
)
View Source
var ErrLimitExceed = rl.ErrLimitExceed

ErrLimitExceed is returned when the rate limiter is triggered and the request is rejected due to limit exceeded.

ErrNotAllowed error not allowed.

RequestIDKey request_id

Functions

func ClientCtxRequestID

func ClientCtxRequestID(ctx context.Context) string

ClientCtxRequestID get request id from rpc client context.Context

func ClientCtxRequestIDField

func ClientCtxRequestIDField(ctx context.Context) zap.Field

ClientCtxRequestIDField get request id field from rpc client context.Context

func ClientOptionTracing

func ClientOptionTracing() grpc.DialOption

ClientOptionTracing client-side tracing interceptor

func ClientTokenOption

func ClientTokenOption(appID string, appKey string, isSecure bool) grpc.DialOption

ClientTokenOption client token

func CtxRequestIDField

func CtxRequestIDField(ctx context.Context) zap.Field

CtxRequestIDField get request id field from context.Context

func GetAuthCtxKey

func GetAuthCtxKey() string

GetAuthCtxKey get the name of Claims

func GetAuthorization

func GetAuthorization(token string) string

GetAuthorization combining tokens into authentication information

func GetJwtClaims

func GetJwtClaims(ctx context.Context) (*jwt.Claims, bool)

GetJwtClaims get the jwt default claims from context, contains fixed fields uid and name

func ServerCtxRequestID

func ServerCtxRequestID(ctx context.Context) string

ServerCtxRequestID get request id from rpc server context.Context

func ServerCtxRequestIDField

func ServerCtxRequestIDField(ctx context.Context) zap.Field

ServerCtxRequestIDField get request id field from rpc server context.Context

func ServerOptionTracing

func ServerOptionTracing() grpc.ServerOption

ServerOptionTracing server-side tracing interceptor

func SetAuthToCtx

func SetAuthToCtx(ctx context.Context, authorization string) context.Context

SetAuthToCtx set the authorization (including prefix Bearer) to the context in grpc client side Example:

ctx := SetAuthToCtx(ctx, authorization)
cli.GetByID(ctx, req)

func SetContextRequestIDKey

func SetContextRequestIDKey(key string)

SetContextRequestIDKey set context request id key

func SetJwtTokenToCtx

func SetJwtTokenToCtx(ctx context.Context, token string) context.Context

SetJwtTokenToCtx set the token (excluding prefix Bearer) to the context in grpc client side Example:

authorization := "Bearer jwt-token"

ctx := SetJwtTokenToCtx(ctx, jwt-token)
cli.GetByID(ctx, req)

func StreamClientCircuitBreaker

func StreamClientCircuitBreaker(opts ...CircuitBreakerOption) grpc.StreamClientInterceptor

StreamClientCircuitBreaker client-side stream circuit breaker interceptor

func StreamClientLog

func StreamClientLog(logger *zap.Logger, opts ...LogOption) grpc.StreamClientInterceptor

StreamClientLog client log stream interceptor

func StreamClientMetrics

func StreamClientMetrics() grpc.StreamClientInterceptor

StreamClientMetrics client-side metrics stream interceptor

func StreamClientRecovery

func StreamClientRecovery() grpc.StreamClientInterceptor

StreamClientRecovery client-side recovery stream interceptor

func StreamClientRequestID

func StreamClientRequestID() grpc.StreamClientInterceptor

StreamClientRequestID client request id stream interceptor

func StreamClientRetry

func StreamClientRetry(opts ...RetryOption) grpc.StreamClientInterceptor

StreamClientRetry client-side retry stream interceptor

func StreamClientTimeout

func StreamClientTimeout(d time.Duration) grpc.StreamClientInterceptor

StreamClientTimeout server-side timeout interceptor

func StreamClientTracing

func StreamClientTracing() grpc.StreamClientInterceptor

StreamClientTracing client-side tracing stream interceptor

func StreamServerCircuitBreaker

func StreamServerCircuitBreaker(opts ...CircuitBreakerOption) grpc.StreamServerInterceptor

StreamServerCircuitBreaker server-side stream circuit breaker interceptor

func StreamServerJwtAuth

func StreamServerJwtAuth(opts ...AuthOption) grpc.StreamServerInterceptor

StreamServerJwtAuth jwt stream interceptor

func StreamServerLog

func StreamServerLog(logger *zap.Logger, opts ...LogOption) grpc.StreamServerInterceptor

StreamServerLog Server-side log stream interceptor

func StreamServerMetrics

func StreamServerMetrics(opts ...metrics.Option) grpc.StreamServerInterceptor

StreamServerMetrics server-side metrics stream interceptor

func StreamServerRateLimit

func StreamServerRateLimit(opts ...RatelimitOption) grpc.StreamServerInterceptor

StreamServerRateLimit server-side stream circuit breaker interceptor

func StreamServerRecovery

func StreamServerRecovery() grpc.StreamServerInterceptor

StreamServerRecovery recovery stream interceptor

func StreamServerRequestID

func StreamServerRequestID() grpc.StreamServerInterceptor

StreamServerRequestID server-side request id stream interceptor

func StreamServerSimpleLog

func StreamServerSimpleLog(logger *zap.Logger, opts ...LogOption) grpc.StreamServerInterceptor

StreamServerSimpleLog Server-side log stream interceptor, only print response

func StreamServerToken

func StreamServerToken(f CheckToken) grpc.StreamServerInterceptor

StreamServerToken recovery stream token

func StreamServerTracing

func StreamServerTracing() grpc.StreamServerInterceptor

StreamServerTracing server-side tracing stream interceptor

func UnaryClientCircuitBreaker

func UnaryClientCircuitBreaker(opts ...CircuitBreakerOption) grpc.UnaryClientInterceptor

UnaryClientCircuitBreaker client-side unary circuit breaker interceptor

func UnaryClientLog

func UnaryClientLog(logger *zap.Logger, opts ...LogOption) grpc.UnaryClientInterceptor

UnaryClientLog client log unary interceptor

func UnaryClientMetrics

func UnaryClientMetrics() grpc.UnaryClientInterceptor

UnaryClientMetrics client-side metrics unary interceptor

func UnaryClientRecovery

func UnaryClientRecovery() grpc.UnaryClientInterceptor

UnaryClientRecovery client-side unary recovery

func UnaryClientRequestID

func UnaryClientRequestID() grpc.UnaryClientInterceptor

UnaryClientRequestID client-side request_id unary interceptor

func UnaryClientRetry

func UnaryClientRetry(opts ...RetryOption) grpc.UnaryClientInterceptor

UnaryClientRetry client-side retry unary interceptor

func UnaryClientTimeout

func UnaryClientTimeout(d time.Duration) grpc.UnaryClientInterceptor

UnaryClientTimeout client-side timeout unary interceptor

func UnaryClientTracing

func UnaryClientTracing() grpc.UnaryClientInterceptor

UnaryClientTracing client-side tracing unary interceptor

func UnaryServerCircuitBreaker

func UnaryServerCircuitBreaker(opts ...CircuitBreakerOption) grpc.UnaryServerInterceptor

UnaryServerCircuitBreaker server-side unary circuit breaker interceptor

func UnaryServerJwtAuth

func UnaryServerJwtAuth(opts ...AuthOption) grpc.UnaryServerInterceptor

UnaryServerJwtAuth jwt unary interceptor

func UnaryServerLog

func UnaryServerLog(logger *zap.Logger, opts ...LogOption) grpc.UnaryServerInterceptor

UnaryServerLog server-side log unary interceptor

func UnaryServerMetrics

func UnaryServerMetrics(opts ...metrics.Option) grpc.UnaryServerInterceptor

UnaryServerMetrics server-side metrics unary interceptor

func UnaryServerRateLimit

func UnaryServerRateLimit(opts ...RatelimitOption) grpc.UnaryServerInterceptor

UnaryServerRateLimit server-side unary circuit breaker interceptor

func UnaryServerRecovery

func UnaryServerRecovery() grpc.UnaryServerInterceptor

UnaryServerRecovery recovery unary interceptor

func UnaryServerRequestID

func UnaryServerRequestID() grpc.UnaryServerInterceptor

UnaryServerRequestID server-side request_id unary interceptor

func UnaryServerSimpleLog

func UnaryServerSimpleLog(logger *zap.Logger, opts ...LogOption) grpc.UnaryServerInterceptor

UnaryServerSimpleLog server-side log unary interceptor, only print response

func UnaryServerToken

func UnaryServerToken(f CheckToken) grpc.UnaryServerInterceptor

UnaryServerToken recovery unary token

func UnaryServerTracing

func UnaryServerTracing() grpc.UnaryServerInterceptor

UnaryServerTracing server-side tracing unary interceptor

func WrapServerCtx

func WrapServerCtx(ctx context.Context, kvs ...KV) context.Context

WrapServerCtx wrap context, used in grpc server-side

Types

type AuthOption

type AuthOption func(*authOptions)

AuthOption setting the Authentication Field

func WithAuthClaimsName

func WithAuthClaimsName(claimsName string) AuthOption

WithAuthClaimsName set the key name of the information in ctx for authentication

func WithAuthIgnoreMethods

func WithAuthIgnoreMethods(fullMethodNames ...string) AuthOption

WithAuthIgnoreMethods ways to ignore forensics fullMethodName format: /packageName.serviceName/methodName, example /api.userExample.v1.userExampleService/GetByID

func WithAuthScheme

func WithAuthScheme(scheme string) AuthOption

WithAuthScheme set the message prefix for authentication

func WithExtraVerify added in v1.13.0

func WithExtraVerify(fn ExtraVerifyFn) AuthOption

WithExtraVerify set extra verify function

func WithSignKey added in v1.13.0

func WithSignKey(key []byte) AuthOption

WithSignKey set jwt sign key

type CheckToken

type CheckToken func(appID string, appKey string) error

CheckToken check app id and app key Example:

var f CheckToken=func(appID string, appKey string) error{
	if appID != targetAppID || appKey != targetAppKey {
		return status.Errorf(codes.Unauthenticated, "app id or app key checksum failure")
	}
	return nil
}

type CircuitBreakerOption

type CircuitBreakerOption func(*circuitBreakerOptions)

CircuitBreakerOption set the circuit breaker circuitBreakerOptions.

func WithBreakerOption added in v1.14.3

func WithBreakerOption(opts ...circuitbreaker.Option) CircuitBreakerOption

WithBreakerOption set the circuit breaker options.

func WithGroup

func WithGroup(g *group.Group) CircuitBreakerOption

WithGroup with circuit breaker group. Deprecated: use WithBreakerOption instead

func WithUnaryServerDegradeHandler

func WithUnaryServerDegradeHandler(handler func(ctx context.Context, req interface{}) (reply interface{}, err error)) CircuitBreakerOption

WithUnaryServerDegradeHandler unary server degrade handler function

func WithValidCode

func WithValidCode(code ...codes.Code) CircuitBreakerOption

WithValidCode rpc code to mark failed

type CtxKeyString

type CtxKeyString string

CtxKeyString for context.WithValue key type

type ExtraVerifyFn added in v1.13.0

type ExtraVerifyFn = func(ctx context.Context, claims *jwt.Claims) error

ExtraVerifyFn extra verify function

type KV

type KV struct {
	Key string
	Val interface{}
}

KV key value

type LogOption

type LogOption func(*logOptions)

LogOption log settings

func WithLogIgnoreMethods

func WithLogIgnoreMethods(fullMethodNames ...string) LogOption

WithLogIgnoreMethods ignore printing methods fullMethodName format: /packageName.serviceName/methodName, example /api.userExample.v1.userExampleService/GetByID

func WithMarshalFn

func WithMarshalFn(fn func(reply interface{}) []byte) LogOption

WithMarshalFn custom response data marshal function

func WithMaxLen

func WithMaxLen(maxLen int) LogOption

WithMaxLen logger content max length

func WithPrintErrorByCodes added in v1.13.0

func WithPrintErrorByCodes(code ...codes.Code) LogOption

WithPrintErrorByCodes set print error by grpc codes

func WithReplaceGRPCLogger

func WithReplaceGRPCLogger() LogOption

WithReplaceGRPCLogger replace grpc logger v2

type RatelimitOption

type RatelimitOption func(*ratelimitOptions)

RatelimitOption set the rate limits ratelimitOptions.

func WithBucket

func WithBucket(b int) RatelimitOption

WithBucket with bucket size.

func WithCPUQuota

func WithCPUQuota(quota float64) RatelimitOption

WithCPUQuota with real cpu quota(if it can not collect from process correct);

func WithCPUThreshold

func WithCPUThreshold(threshold int64) RatelimitOption

WithCPUThreshold with cpu threshold

func WithWindow

func WithWindow(d time.Duration) RatelimitOption

WithWindow with window size.

type RetryOption

type RetryOption func(*retryOptions)

RetryOption set the retry retryOptions.

func WithRetryErrCodes

func WithRetryErrCodes(errCodes ...codes.Code) RetryOption

WithRetryErrCodes set the trigger retry error code

func WithRetryInterval

func WithRetryInterval(t time.Duration) RetryOption

WithRetryInterval set the retry interval from 1 ms to 10 seconds

func WithRetryTimes

func WithRetryTimes(n uint) RetryOption

WithRetryTimes set number of retries, max 10

Jump to

Keyboard shortcuts

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