github.com/go-graphite/carbonapi@v0.17.0/zipper/types/lbmethod.go (about)

     1  package types
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"strings"
     7  )
     8  
     9  var ErrUnknownLBMethodFmt = "unknown lb method: '%v', supported: %v"
    10  
    11  type LBMethod int
    12  
    13  const (
    14  	RoundRobinLB LBMethod = iota
    15  	BroadcastLB
    16  )
    17  
    18  func (p LBMethod) keys(m map[string]LBMethod) []string {
    19  	res := make([]string, 0)
    20  	for k := range m {
    21  		res = append(res, k)
    22  	}
    23  	return res
    24  }
    25  
    26  var supportedLBMethods = map[string]LBMethod{
    27  	"roundrobin": RoundRobinLB,
    28  	"rr":         RoundRobinLB,
    29  	"any":        RoundRobinLB,
    30  	"broadcast":  BroadcastLB,
    31  	"all":        BroadcastLB,
    32  }
    33  
    34  func (m *LBMethod) FromString(method string) error {
    35  	var ok bool
    36  	if *m, ok = supportedLBMethods[strings.ToLower(method)]; !ok {
    37  		return fmt.Errorf(ErrUnknownLBMethodFmt, method, m.keys(supportedLBMethods))
    38  	}
    39  	return nil
    40  }
    41  
    42  func (m *LBMethod) UnmarshalJSON(data []byte) error {
    43  	method := strings.ToLower(string(data))
    44  	return m.FromString(method)
    45  }
    46  
    47  func (m *LBMethod) UnmarshalYAML(unmarshal func(interface{}) error) error {
    48  	var method string
    49  	err := unmarshal(&method)
    50  	if err != nil {
    51  		return err
    52  	}
    53  
    54  	return m.FromString(method)
    55  }
    56  
    57  func (m LBMethod) MarshalJSON() ([]byte, error) {
    58  	switch m {
    59  	case RoundRobinLB:
    60  		return json.Marshal("RoundRobin")
    61  	case BroadcastLB:
    62  		return json.Marshal("Broadcast")
    63  	}
    64  
    65  	return nil, fmt.Errorf(ErrUnknownLBMethodFmt, m, m.keys(supportedLBMethods))
    66  }