forked from bcicen/go-haproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
78 lines (65 loc) · 1.56 KB
/
client.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
// Package haproxy provides a minimal client for communicating with, and issuing commands to, HAproxy over a network or file socket.
package haproxy
import (
"bytes"
"fmt"
"io"
"net"
"strings"
"time"
)
const (
socketSchema = "unix://"
tcpSchema = "tcp://"
)
// HAProxyClient is the main structure of the library.
type HAProxyClient struct {
Addr string
Timeout int
conn net.Conn
}
// RunCommand is the entrypoint to the client. Sends an arbitray command string to HAProxy.
func (h *HAProxyClient) RunCommand(cmd string) (*bytes.Buffer, error) {
err := h.dial()
if err != nil {
return nil, err
}
defer h.conn.Close()
result := bytes.NewBuffer(nil)
_, err = h.conn.Write([]byte(cmd + "\n"))
if err != nil {
return nil, err
}
_, err = io.Copy(result, h.conn)
if err != nil {
return nil, err
}
if strings.HasPrefix(result.String(), "Unknown command") {
return nil, fmt.Errorf("Unknown command: %s", cmd)
}
return result, nil
}
func (h *HAProxyClient) dial() (err error) {
if h.Timeout == 0 {
h.Timeout = 30
}
timeout := time.Duration(h.Timeout) * time.Second
switch h.schema() {
case "socket":
h.conn, err = net.DialTimeout("unix", strings.Replace(h.Addr, socketSchema, "", 1), timeout)
case "tcp":
h.conn, err = net.DialTimeout("tcp", strings.Replace(h.Addr, tcpSchema, "", 1), timeout)
default:
return fmt.Errorf("unknown schema")
}
return err
}
func (h *HAProxyClient) schema() string {
if strings.HasPrefix(h.Addr, socketSchema) {
return "socket"
}
if strings.HasPrefix(h.Addr, tcpSchema) {
return "tcp"
}
return ""
}