2024-09-20 17:54:17 +03:00
|
|
|
package random
|
2020-06-30 14:54:38 +01:00
|
|
|
|
|
|
|
import (
|
2021-10-02 19:55:07 +03:00
|
|
|
"go.unistack.org/micro/v3/selector"
|
|
|
|
"go.unistack.org/micro/v3/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
|
|
|
|
}
|
|
|
|
|
2024-12-09 13:06:43 +03:00
|
|
|
func (r *random) Record(_ string, _ error) error {
|
2020-08-17 22:44:45 +01:00
|
|
|
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
|
|
|
}
|