diff options
Diffstat (limited to 'echo/ports.go')
-rw-r--r-- | echo/ports.go | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/echo/ports.go b/echo/ports.go new file mode 100644 index 0000000..bdd97fe --- /dev/null +++ b/echo/ports.go | |||
@@ -0,0 +1,65 @@ | |||
1 | package echo | ||
2 | |||
3 | import ( | ||
4 | "fmt" | ||
5 | "net" | ||
6 | "strconv" | ||
7 | ) | ||
8 | |||
9 | type AddressPortConfig struct { | ||
10 | HttpPort int | ||
11 | TlsPort int | ||
12 | Addresses []string | ||
13 | } | ||
14 | |||
15 | func (c *AddressPortConfig) TlsBindings() []string { | ||
16 | o := make([]string, len(c.Addresses)) | ||
17 | for i, a := range c.Addresses { | ||
18 | o[i] = net.JoinHostPort(a, strconv.Itoa(c.TlsPort)) | ||
19 | } | ||
20 | return o | ||
21 | } | ||
22 | |||
23 | func (c *AddressPortConfig) HttpBindings() []string { | ||
24 | o := make([]string, len(c.Addresses)) | ||
25 | for i, a := range c.Addresses { | ||
26 | o[i] = net.JoinHostPort(a, strconv.Itoa(c.HttpPort)) | ||
27 | } | ||
28 | return o | ||
29 | } | ||
30 | |||
31 | func ParseAddressPortBindings(b []string) (*AddressPortConfig, error) { | ||
32 | o := &AddressPortConfig{ | ||
33 | Addresses: make([]string, len(b)), | ||
34 | } | ||
35 | |||
36 | for i, a := range b { | ||
37 | host, port, err := net.SplitHostPort(a) | ||
38 | if err != nil { | ||
39 | return nil, fmt.Errorf("ParseAddressPortBindings: error splitting address: %w", err) | ||
40 | } | ||
41 | |||
42 | o.Addresses[i] = host | ||
43 | |||
44 | intPort, err := strconv.Atoi(port) | ||
45 | if err != nil { | ||
46 | return nil, fmt.Errorf("ParseAddressPortBindings: error parsing port to string: %w", err) | ||
47 | } | ||
48 | |||
49 | if o.HttpPort == 0 { | ||
50 | o.HttpPort = intPort | ||
51 | } else { | ||
52 | if o.HttpPort != intPort { | ||
53 | return nil, fmt.Errorf("ParseAddressPortBindings: all ports must be the same number") | ||
54 | } | ||
55 | } | ||
56 | } | ||
57 | |||
58 | if o.HttpPort == 0 { | ||
59 | return nil, fmt.Errorf("ParseAddressPortBindings: no valid HTTP port was specified") | ||
60 | } | ||
61 | |||
62 | o.TlsPort = o.HttpPort + 1 | ||
63 | |||
64 | return o, nil | ||
65 | } | ||