-
Notifications
You must be signed in to change notification settings - Fork 0
/
addr.go
60 lines (48 loc) · 905 Bytes
/
addr.go
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
package main
import (
"fmt"
"net"
"strconv"
"strings"
)
type Addr struct {
listener net.Listener
value string
insecure bool
}
func (a *Addr) Set(value string) error {
if value == "" {
return nil
}
host, port, _ := strings.Cut(value, ":")
if host == "" {
host = "localhost"
}
if port == "" {
port = "0"
}
listener, err := net.Listen("tcp", ":"+port)
if err != nil {
return fmt.Errorf("listen on %v: %w", port, err)
}
port = strconv.Itoa(listener.Addr().(*net.TCPAddr).Port)
a.value = fmt.Sprintf("%v:%v", host, port)
a.listener = listener
return nil
}
func (a *Addr) Listener() (net.Listener, error) {
if a.listener == nil {
err := a.Set(":0")
if err != nil {
return nil, err
}
}
return a.listener, nil
}
func (a Addr) String() string {
protocol := "https"
if a.insecure {
protocol = "http"
}
return fmt.Sprintf("%v://%v", protocol, a.value)
}