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.

46 lines
886 B

2 years ago
package random
import (
"context"
"git.diulo.com/mogfee/kit/selector"
"math/rand"
2 years ago
)
type Option func(o *options)
2 years ago
type options struct {
2 years ago
}
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) {
2 years ago
if len(nodes) == 0 {
return nil, nil, selector.ErrNoAvailable
}
cut := rand.Intn(len(nodes))
selected := nodes[cut]
2 years ago
d := selected.Pick()
return selected, d, nil
}
func NewBuilder(opts ...Option) selector.Builder {
var option options
for _, opt := range opts {
opt(&option)
}
2 years ago
return &selector.DefaultBuilder{
Balancer: &Builder{},
Node: &direct.Builder{},
2 years ago
}
}
// Builder is random builder
type Builder struct{}
2 years ago
func (b *Builder) Builder() selector.Balancer {
2 years ago
return &Balancer{}
}