strategy_random.go 1006 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package router
  2. import (
  3. "github.com/v2fly/v2ray-core/v4/common/dice"
  4. "github.com/v2fly/v2ray-core/v4/features/routing"
  5. )
  6. // RandomStrategy represents a random balancing strategy
  7. type RandomStrategy struct{}
  8. // GetInformation implements the routing.BalancingStrategy.
  9. func (s *RandomStrategy) GetInformation(tags []string) *routing.StrategyInfo {
  10. items := make([]*routing.OutboundInfo, 0)
  11. for _, tag := range tags {
  12. items = append(items, &routing.OutboundInfo{Tag: tag})
  13. }
  14. return &routing.StrategyInfo{
  15. Settings: []string{"random"},
  16. ValueTitles: nil,
  17. Selects: items,
  18. Others: nil,
  19. }
  20. }
  21. // SelectAndPick implements the routing.BalancingStrategy.
  22. func (s *RandomStrategy) SelectAndPick(candidates []string) string {
  23. return s.Pick(candidates)
  24. }
  25. // Pick implements the routing.BalancingStrategy.
  26. func (s *RandomStrategy) Pick(candidates []string) string {
  27. count := len(candidates)
  28. if count == 0 {
  29. // goes to fallbackTag
  30. return ""
  31. }
  32. return candidates[dice.Roll(count)]
  33. }