Ejemplo n.º 1
0
// New constructs a `TokenLimiter` middleware instance.
func New(next http.Handler, extract utils.SourceExtractor, defaultRates *RateSet, opts ...TokenLimiterOption) (*TokenLimiter, error) {
	if defaultRates == nil || len(defaultRates.m) == 0 {
		return nil, fmt.Errorf("Provide default rates")
	}
	if extract == nil {
		return nil, fmt.Errorf("Provide extract function")
	}
	tl := &TokenLimiter{
		next:         next,
		defaultRates: defaultRates,
		extract:      extract,
	}

	for _, o := range opts {
		if err := o(tl); err != nil {
			return nil, err
		}
	}
	setDefaults(tl)
	bucketSets, err := ttlmap.NewMapWithProvider(tl.capacity, tl.clock)
	if err != nil {
		return nil, err
	}
	tl.bucketSets = bucketSets
	return tl, nil
}
Ejemplo n.º 2
0
// NewLimiter constructs a `TokenLimiter` middleware instance.
func NewLimiter(defaultRates *RateSet, capacity int, mapper limit.MapperFn, configMapper ConfigMapperFn, clock timetools.TimeProvider) (*TokenLimiter, error) {
	if defaultRates == nil || len(defaultRates.m) == 0 {
		return nil, fmt.Errorf("Provide default rates")
	}
	if mapper == nil {
		return nil, fmt.Errorf("Provide mapper function")
	}

	// Set default values for optional fields.
	if capacity <= 0 {
		capacity = DefaultCapacity
	}
	if clock == nil {
		clock = &timetools.RealTime{}
	}

	bucketSets, err := ttlmap.NewMapWithProvider(DefaultCapacity, clock)
	if err != nil {
		return nil, err
	}

	return &TokenLimiter{
		defaultRates: defaultRates,
		mapper:       mapper,
		configMapper: configMapper,
		clock:        clock,
		bucketSets:   bucketSets,
	}, nil
}
Ejemplo n.º 3
0
// Return a new NonceCache. Allows you to control cache capacity, ttl, as well as the TimeProvider.
func NewNonceCache(capacity int, cacheTTL int, timeProvider timetools.TimeProvider) (*NonceCache, error) {
	c, err := ttlmap.NewMapWithProvider(capacity, timeProvider)
	if err != nil {
		return nil, err
	}

	return &NonceCache{
		cache:        c,
		cacheTTL:     cacheTTL,
		timeProvider: timeProvider,
	}, nil
}
Ejemplo n.º 4
0
func NewTokenLimiterWithOptions(mapper MapperFn, rate Rate, o Options) (*TokenLimiter, error) {
	if mapper == nil {
		return nil, fmt.Errorf("Provide mapper function")
	}
	options, err := parseOptions(o)
	if err != nil {
		return nil, err
	}
	buckets, err := ttlmap.NewMapWithProvider(options.Capacity, options.TimeProvider)
	if err != nil {
		return nil, err
	}

	return &TokenLimiter{
		rate:    rate,
		mapper:  mapper,
		options: options,
		mutex:   &sync.Mutex{},
		buckets: buckets,
	}, nil
}