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