github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/selector/random/random.go (about)

     1  // Licensed under the Apache License, Version 2.0 (the "License");
     2  // you may not use this file except in compliance with the License.
     3  // You may obtain a copy of the License at
     4  //
     5  //     https://www.apache.org/licenses/LICENSE-2.0
     6  //
     7  // Unless required by applicable law or agreed to in writing, software
     8  // distributed under the License is distributed on an "AS IS" BASIS,
     9  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    10  // See the License for the specific language governing permissions and
    11  // limitations under the License.
    12  //
    13  // Original source: github.com/micro/go-micro/v3/selector/random/random.go
    14  
    15  package random
    16  
    17  import (
    18  	"math/rand"
    19  
    20  	"github.com/tickoalcantara12/micro/v3/util/selector"
    21  )
    22  
    23  type random struct{}
    24  
    25  func (r *random) Select(routes []string, opts ...selector.SelectOption) (selector.Next, error) {
    26  	// we can't select from an empty pool of routes
    27  	if len(routes) == 0 {
    28  		return nil, selector.ErrNoneAvailable
    29  	}
    30  
    31  	// return the next func
    32  	return func() string {
    33  		// if there is only one route provided we'll select it
    34  		if len(routes) == 1 {
    35  			return routes[0]
    36  		}
    37  
    38  		// select a random route from the slice
    39  		return routes[rand.Intn(len(routes))]
    40  	}, nil
    41  }
    42  
    43  func (r *random) Record(addr string, err error) error {
    44  	return nil
    45  }
    46  
    47  func (r *random) Reset() error {
    48  	return nil
    49  }
    50  
    51  func (r *random) String() string {
    52  	return "random"
    53  }
    54  
    55  // NewSelector returns a random selector
    56  func NewSelector(opts ...selector.Option) selector.Selector {
    57  	return new(random)
    58  }