forked from koding/kite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
registerurl.go
96 lines (82 loc) · 1.81 KB
/
registerurl.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package kite
import (
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
)
const publicEcho = "http://echoip.com"
// RegisterURL returns a URL that is either local or public. It's an helper
// method to get a Registration URL that can be passed to Kontrol (via the
// methods Register(), RegisterToProxy(), etc.) It needs to be called after all
// configurations are done (like TLS, Port,etc.). If local is true a local IP
// is used, otherwise a public IP is being used.
func (k *Kite) RegisterURL(local bool) *url.URL {
var ip net.IP
var err error
if local {
ip, err = localIP()
if err != nil {
return nil
}
} else {
ip, err = publicIP()
if err != nil {
return nil
}
}
scheme := "http"
if k.TLSConfig != nil {
scheme = "https"
}
return &url.URL{
Scheme: scheme,
Host: ip.String() + ":" + strconv.Itoa(k.Config.Port),
Path: "/" + k.name + "-" + k.version + "/kite",
}
}
// localIp returns a local IP from one of the local interfaces.
func localIP() (net.IP, error) {
tt, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, t := range tt {
aa, err := t.Addrs()
if err != nil {
return nil, err
}
for _, a := range aa {
ipnet, ok := a.(*net.IPNet)
if !ok {
continue
}
v4 := ipnet.IP.To4()
if v4 == nil || v4[0] == 127 { // loopback address
continue
}
return v4, nil
}
}
return nil, errors.New("cannot find local IP address")
}
// publicIP returns an IP that is supposed to be Public.
func publicIP() (net.IP, error) {
resp, err := http.Get(publicEcho)
if err != nil {
return nil, err
}
defer resp.Body.Close()
out, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
n := net.ParseIP(string(out))
if n == nil {
return nil, fmt.Errorf("cannot parse ip %s", string(out))
}
return n, nil
}