2020-06-30 16:54:38 +03:00
|
|
|
package selector
|
|
|
|
|
|
|
|
import (
|
|
|
|
"math/rand"
|
|
|
|
|
|
|
|
"github.com/micro/go-micro/v2/router"
|
|
|
|
)
|
|
|
|
|
|
|
|
type random struct{}
|
|
|
|
|
|
|
|
func (r *random) Init(opts ...Option) error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *random) Options() Options {
|
|
|
|
return Options{}
|
|
|
|
}
|
|
|
|
|
2020-06-30 17:51:26 +03:00
|
|
|
func (r *random) Select(routes []router.Route) (*router.Route, error) {
|
2020-06-30 16:54:38 +03:00
|
|
|
// we can't select from an empty pool of routes
|
|
|
|
if len(routes) == 0 {
|
|
|
|
return nil, ErrNoneAvailable
|
|
|
|
}
|
|
|
|
|
|
|
|
// if there is only one route provided we'll select it
|
|
|
|
if len(routes) == 1 {
|
2020-06-30 17:51:26 +03:00
|
|
|
return &routes[0], nil
|
2020-06-30 16:54:38 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// select a random route from the slice
|
2020-06-30 17:51:26 +03:00
|
|
|
return &routes[rand.Intn(len(routes)-1)], nil
|
2020-06-30 16:54:38 +03:00
|
|
|
}
|
|
|
|
|
2020-06-30 17:51:26 +03:00
|
|
|
func (r *random) Record(route router.Route, err error) error {
|
2020-06-30 16:54:38 +03:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *random) Close() error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *random) String() string {
|
|
|
|
return "random"
|
|
|
|
}
|
|
|
|
|
|
|
|
func newSelector(...Option) Selector {
|
|
|
|
return &random{}
|
|
|
|
}
|