2023-04-11 22:20:37 +03:00
|
|
|
package random // import "go.unistack.org/micro/v4/selector/random"
|
2020-06-30 14:54:38 +01:00
|
|
|
|
|
|
|
import (
|
2023-04-11 22:20:37 +03:00
|
|
|
"go.unistack.org/micro/v4/selector"
|
|
|
|
"go.unistack.org/micro/v4/util/rand"
|
2020-06-30 14:54:38 +01:00
|
|
|
)
|
|
|
|
|
2020-08-17 22:44:45 +01:00
|
|
|
type random struct{}
|
|
|
|
|
|
|
|
func (r *random) Select(routes []string, opts ...selector.SelectOption) (selector.Next, error) {
|
|
|
|
// we can't select from an empty pool of routes
|
|
|
|
if len(routes) == 0 {
|
|
|
|
return nil, selector.ErrNoneAvailable
|
|
|
|
}
|
|
|
|
|
|
|
|
// return the next func
|
|
|
|
return func() string {
|
|
|
|
// if there is only one route provided we'll select it
|
|
|
|
if len(routes) == 1 {
|
|
|
|
return routes[0]
|
|
|
|
}
|
2021-02-17 22:58:55 +03:00
|
|
|
var rng rand.Rand
|
2020-08-17 22:44:45 +01:00
|
|
|
// select a random route from the slice
|
2021-02-17 22:58:55 +03:00
|
|
|
return routes[rng.Intn(len(routes))]
|
2020-08-17 22:44:45 +01:00
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *random) Record(addr string, err error) error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *random) Reset() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *random) String() string {
|
|
|
|
return "random"
|
|
|
|
}
|
|
|
|
|
2020-06-30 14:54:38 +01:00
|
|
|
// NewSelector returns a random selector
|
|
|
|
func NewSelector(opts ...selector.Option) selector.Selector {
|
2021-02-13 01:46:16 +03:00
|
|
|
return &random{}
|
2020-06-30 14:54:38 +01:00
|
|
|
}
|