diff --git a/router/context.go b/router/context.go new file mode 100644 index 00000000..2f156cfc --- /dev/null +++ b/router/context.go @@ -0,0 +1,34 @@ +package router + +import ( + "context" +) + +type routerKey struct{} + +// FromContext get router from context +func FromContext(ctx context.Context) (Router, bool) { + if ctx == nil { + return nil, false + } + c, ok := ctx.Value(routerKey{}).(Router) + return c, ok +} + +// NewContext put router in context +func NewContext(ctx context.Context, c Router) context.Context { + if ctx == nil { + ctx = context.Background() + } + return context.WithValue(ctx, routerKey{}, c) +} + +// SetOption returns a function to setup a context with given value +func SetOption(k, v interface{}) Option { + return func(o *Options) { + if o.Context == nil { + o.Context = context.Background() + } + o.Context = context.WithValue(o.Context, k, v) + } +} diff --git a/util/jitter/random.go b/util/jitter/random.go index c3caa5d3..eb03b29f 100644 --- a/util/jitter/random.go +++ b/util/jitter/random.go @@ -13,3 +13,8 @@ func Random(d time.Duration) time.Duration { v := rng.Float64() * float64(d.Nanoseconds()) return time.Duration(v) } + +func RandomInterval(min, max time.Duration) time.Duration { + var rng rand.Rand + return time.Duration(rng.Int63n(max.Nanoseconds()-min.Nanoseconds())+min.Nanoseconds()) * time.Nanosecond +}