aboutsummaryrefslogtreecommitdiff
path: root/echo/ports.go
blob: bdd97fea9a339ce15a01d970f21f3a22fb663218 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package echo

import (
	"fmt"
	"net"
	"strconv"
)

type AddressPortConfig struct {
	HttpPort  int
	TlsPort   int
	Addresses []string
}

func (c *AddressPortConfig) TlsBindings() []string {
	o := make([]string, len(c.Addresses))
	for i, a := range c.Addresses {
		o[i] = net.JoinHostPort(a, strconv.Itoa(c.TlsPort))
	}
	return o
}

func (c *AddressPortConfig) HttpBindings() []string {
	o := make([]string, len(c.Addresses))
	for i, a := range c.Addresses {
		o[i] = net.JoinHostPort(a, strconv.Itoa(c.HttpPort))
	}
	return o
}

func ParseAddressPortBindings(b []string) (*AddressPortConfig, error) {
	o := &AddressPortConfig{
		Addresses: make([]string, len(b)),
	}

	for i, a := range b {
		host, port, err := net.SplitHostPort(a)
		if err != nil {
			return nil, fmt.Errorf("ParseAddressPortBindings: error splitting address: %w", err)
		}

		o.Addresses[i] = host

		intPort, err := strconv.Atoi(port)
		if err != nil {
			return nil, fmt.Errorf("ParseAddressPortBindings: error parsing port to string: %w", err)
		}

		if o.HttpPort == 0 {
			o.HttpPort = intPort
		} else {
			if o.HttpPort != intPort {
				return nil, fmt.Errorf("ParseAddressPortBindings: all ports must be the same number")
			}
		}
	}

	if o.HttpPort == 0 {
		return nil, fmt.Errorf("ParseAddressPortBindings: no valid HTTP port was specified")
	}

	o.TlsPort = o.HttpPort + 1

	return o, nil
}