forked from vbatoufflet/go-livestatus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
59 lines (50 loc) · 1.16 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
package livestatus
import (
"net"
)
// Client represents a Livestatus client instance.
type Client struct {
network string
address string
dialer *net.Dialer
conn net.Conn
}
// NewClient creates a new Livestatus client instance.
func NewClient(network, address string) *Client {
return NewClientWithDialer(network, address, new(net.Dialer))
}
// NewClientWithDialer creates a new Livestatus client instance using a provided network dialer.
func NewClientWithDialer(network, address string, dialer *net.Dialer) *Client {
return &Client{
network: network,
address: address,
dialer: dialer,
}
}
// Close closes any remaining connection.
func (c *Client) Close() {
if c.conn != nil {
c.conn.Close()
c.conn = nil
}
}
// Exec executes a given Livestatus query.
func (c *Client) Exec(r Request) (*Response, error) {
var err error
// Initialize connection if none available
if c.conn == nil {
c.conn, err = c.dialer.Dial(c.network, c.address)
if err != nil {
return nil, err
}
if r.keepAlive() {
switch c.network {
case "tcp":
c.conn.(*net.TCPConn).SetKeepAlive(true)
}
} else {
defer c.Close()
}
}
return r.handle(c.conn)
}