forked from go-gremlin/gremlin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.go
71 lines (66 loc) · 1.67 KB
/
connection.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
package gremlin
import (
"errors"
"net"
"net/url"
"os"
"strings"
"time"
)
type Cluster struct {
servers []*url.URL
}
func NewCluster(s ...string) (cluster *Cluster, err error) {
cluster = &Cluster{}
// If no arguments use environment variable
if len(s) == 0 {
connString := strings.TrimSpace(os.Getenv("GREMLIN_SERVERS"))
if connString == "" {
err = errors.New("No servers set. Configure servers to connect to using the GREMLIN_SERVERS environment variable.")
return
}
cluster.servers, err = SplitServers(connString)
return
}
// Else use the supplied servers
for _, v := range s {
var u *url.URL
if u, err = url.Parse(v); err != nil {
return
}
cluster.servers = append(cluster.servers, u)
}
return
}
func SplitServers(connString string) (servers []*url.URL, err error) {
serverStrings := strings.Split(connString, ",")
if len(serverStrings) < 1 {
err = errors.New("Connection string is not in expected format. An example of the expected format is 'ws://server1:8182, ws://server2:8182'.")
return
}
for _, serverString := range serverStrings {
var u *url.URL
if u, err = url.Parse(strings.TrimSpace(serverString)); err != nil {
return
}
servers = append(servers, u)
}
return
}
func (cluster *Cluster) CreateConnection() (conn net.Conn, server *url.URL, err error) {
connEstablished := false
for _, s := range cluster.servers {
c, err := net.DialTimeout("tcp", s.Host, 1*time.Second)
if err != nil {
continue
}
connEstablished = true
conn = c
server = s
break
}
if !connEstablished {
err = errors.New("Could not establish connection. Please check your connection string and ensure at least one server is up.")
}
return
}