protocol.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package edgediscovery
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net"
  6. "strings"
  7. )
  8. const (
  9. protocolRecord = "protocol-v2.argotunnel.com"
  10. )
  11. var (
  12. errNoProtocolRecord = fmt.Errorf("No TXT record found for %s to determine connection protocol", protocolRecord)
  13. )
  14. type PercentageFetcher func() (ProtocolPercents, error)
  15. // ProtocolPercent represents a single Protocol Percentage combination.
  16. type ProtocolPercent struct {
  17. Protocol string `json:"protocol"`
  18. Percentage int32 `json:"percentage"`
  19. }
  20. // ProtocolPercents represents the preferred distribution ratio of protocols when protocol isn't specified.
  21. type ProtocolPercents []ProtocolPercent
  22. // GetPercentage returns the threshold percentage of a single protocol.
  23. func (p ProtocolPercents) GetPercentage(protocol string) int32 {
  24. for _, protocolPercent := range p {
  25. if strings.ToLower(protocolPercent.Protocol) == strings.ToLower(protocol) {
  26. return protocolPercent.Percentage
  27. }
  28. }
  29. return 0
  30. }
  31. // ProtocolPercentage returns the ratio of protocols and a specification ratio for their selection.
  32. func ProtocolPercentage() (ProtocolPercents, error) {
  33. records, err := net.LookupTXT(protocolRecord)
  34. if err != nil {
  35. return nil, err
  36. }
  37. if len(records) == 0 {
  38. return nil, errNoProtocolRecord
  39. }
  40. var protocolsWithPercent ProtocolPercents
  41. err = json.Unmarshal([]byte(records[0]), &protocolsWithPercent)
  42. return protocolsWithPercent, err
  43. }