You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

45 lines
886 B

package random
import (
"context"
"git.diulo.com/mogfee/kit/selector"
"math/rand"
)
type Option func(o *options)
type options struct {
}
type Balancer struct {
}
func New(opts ...Option) selector.Selector {
return NewBuilder(opts...).Build()
}
func (b *Balancer) Pick(ctx context.Context, nodes []selector.WeightedNode) (selector.WeightedNode, selector.DoneFunc, error) {
if len(nodes) == 0 {
return nil, nil, selector.ErrNoAvailable
}
cut := rand.Intn(len(nodes))
selected := nodes[cut]
d := selected.Pick()
return selected, d, nil
}
func NewBuilder(opts ...Option) selector.Builder {
var option options
for _, opt := range opts {
opt(&option)
}
return &selector.DefaultBuilder{
Balancer: &Builder{},
Node: &direct.Builder{},
}
}
// Builder is random builder
type Builder struct{}
func (b *Builder) Builder() selector.Balancer {
return &Balancer{}
}