forked from JamesClonk/backman
-
Notifications
You must be signed in to change notification settings - Fork 20
/
binding.go
91 lines (81 loc) · 2.06 KB
/
binding.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
package redis
import (
"net"
"net/url"
"strconv"
"strings"
"github.com/cloudfoundry-community/go-cfenv"
)
type Credentials struct {
Hostname string
Port string
Password string
}
func IsRedisBinding(binding *cfenv.Service) bool {
c := GetCredentials(binding)
if len(c.Hostname) > 0 &&
len(c.Password) > 0 &&
len(c.Port) > 0 {
for key := range binding.Credentials {
switch key {
case "host", "hostname", "master", "database_uri", "jdbcUrl", "jdbc_url", "url", "uri":
if uri, _ := binding.CredentialString(key); len(uri) > 0 && strings.Contains(uri, "redis://") {
return true
}
}
}
}
return false
}
func GetCredentials(binding *cfenv.Service) *Credentials {
host, _ := binding.CredentialString("host")
hostname, _ := binding.CredentialString("hostname")
password, _ := binding.CredentialString("password")
port, _ := binding.CredentialString("port")
if len(port) == 0 {
switch p := binding.Credentials["port"].(type) {
case float64:
port = strconv.Itoa(int(p))
case int, int32, int64:
port = strconv.Itoa(p.(int))
}
}
if len(hostname) == 0 && !strings.Contains(host, ":") {
hostname = host
}
// figure out hostname & port from host if still missing
if len(hostname) == 0 || len(port) == 0 {
if len(host) > 0 && strings.Contains(host, ":") {
if u, err := url.Parse(host); err == nil {
hostname = u.Hostname()
port = u.Port()
}
}
}
// figure out credentials from URL if still missing
for key := range binding.Credentials {
switch key {
case "host", "hostname", "master", "database_uri", "jdbcUrl", "jdbc_url", "url", "uri":
if uri, _ := binding.CredentialString(key); len(uri) > 0 && strings.Contains(uri, "redis://") {
if u, err := url.Parse(uri); err == nil {
if len(password) == 0 {
p, _ := u.User.Password()
password = p
}
h, p, _ := net.SplitHostPort(u.Host)
if len(hostname) == 0 {
hostname = h
}
if len(port) == 0 {
port = p
}
}
}
}
}
return &Credentials{
Hostname: hostname,
Port: port,
Password: password,
}
}