2020-06-30 14:54:38 +01:00
|
|
|
package random
|
|
|
|
|
|
|
|
import (
|
2020-08-17 22:44:45 +01:00
|
|
|
"math/rand"
|
|
|
|
|
2020-07-27 13:22:00 +01:00
|
|
|
"github.com/micro/go-micro/v3/selector"
|
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]
|
|
|
|
}
|
|
|
|
|
|
|
|
// select a random route from the slice
|
|
|
|
return routes[rand.Intn(len(routes)-1)]
|
|
|
|
}, 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 {
|
2020-08-17 22:44:45 +01:00
|
|
|
return new(random)
|
2020-06-30 14:54:38 +01:00
|
|
|
}
|