small improve

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2022-03-27 01:37:21 +03:00
parent 35ab6ae84e
commit 03410c4ab1
2 changed files with 39 additions and 0 deletions

34
router/context.go Normal file
View File

@ -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)
}
}

View File

@ -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
}