Skip to content

Commit

Permalink
Add KeepAlive Support
Browse files Browse the repository at this point in the history
This adds support for KeepAlive to queries.
Each query must set KeepAlive to keep the connection open. The
connection will be closed on the first Query without KeepAlive
set.
  • Loading branch information
tcolgate committed Jul 1, 2016
1 parent 042c140 commit 8865d67
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 5 deletions.
14 changes: 14 additions & 0 deletions livestatus.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,24 @@ type Livestatus struct {
network string
address string
dialer func() (net.Conn, error)

keepalive bool
keepConn net.Conn
}

// Close any open connection from a KeepAlive
func (l *Livestatus) Close() error {
l.keepalive = false
if l.keepConn != nil {
l.keepConn = nil
return l.keepConn.Close()
}
return nil
}

// Query creates a new query instance on a spacific table.
func (l *Livestatus) Query(table string) *Query {
l.keepalive = false
return newQuery(table, l)
}

Expand Down
29 changes: 24 additions & 5 deletions query.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ func (q *Query) Columns(names ...string) *Query {
return q
}

// KeepAlive keeps the connection open after the query, for re-use
func (q *Query) KeepAlive() *Query {
q.headers = append(q.headers, "KeepAlive: on")
return q
}

// Filter sets a new filter to apply to the query.
func (q *Query) Filter(rule string) *Query {
q.headers = append(q.headers, "Filter: "+rule)
Expand Down Expand Up @@ -108,12 +114,25 @@ func (q *Query) WaitTimeout(t time.Duration) *Query {
func (q *Query) Exec() (*Response, error) {
resp := &Response{}

// Connect to socket
conn, err := q.dial()
if err != nil {
return nil, err
var err error
var conn net.Conn

if q.ls.keepConn != nil {
conn = q.ls.keepConn
} else {
// Connect to socket
conn, err = q.dial()
if err != nil {
return nil, err
}
}

if !q.ls.keepalive {
q.ls.keepConn = nil
defer conn.Close()
} else {
q.ls.keepConn = conn
}
defer conn.Close()

// Send command data
conn.Write([]byte(q.buildCmd()))
Expand Down

0 comments on commit 8865d67

Please sign in to comment.