Skip to content

Commit

Permalink
Add CloseIdleConnections method to close tcp connections (#92)
Browse files Browse the repository at this point in the history
  • Loading branch information
sideshow authored Sep 6, 2017
1 parent 0700d12 commit d8025ed
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
11 changes: 11 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ type Client struct {
Host string
}

type connectionCloser interface {
CloseIdleConnections()
}

// NewClient returns a new Client with an underlying http.Client configured with
// the correct APNs HTTP/2 transport settings. It does not connect to the APNs
// until the first Notification is sent via the Push method.
Expand Down Expand Up @@ -142,6 +146,13 @@ func (c *Client) PushWithContext(ctx Context, n *Notification) (*Response, error
return response, nil
}

// CloseIdleConnections closes any underlying connections which were previously
// connected from previous requests but are now sitting idle. It will not
// interrupt any connections currently in use.
func (c *Client) CloseIdleConnections() {
c.HTTPClient.Transport.(connectionCloser).CloseIdleConnections()
}

func setHeaders(r *http.Request, n *Notification) {
r.Header.Set("Content-Type", "application/json; charset=utf-8")
if n.Topic != "" {
Expand Down
20 changes: 20 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@ func mockClient(url string) *apns.Client {
return &apns.Client{Host: url, HTTPClient: http.DefaultClient}
}

type mockTransport struct {
*http2.Transport
closed bool
}

func (c *mockTransport) CloseIdleConnections() {
c.closed = true
}

// Unit Tests

func TestClientDefaultHost(t *testing.T) {
Expand Down Expand Up @@ -231,3 +240,14 @@ func TestMalformedJSONResponse(t *testing.T) {
assert.Error(t, err)
assert.Equal(t, false, res.Sent())
}

func TestCloseIdleConnections(t *testing.T) {
transport := &mockTransport{}

client := mockClient("")
client.HTTPClient.Transport = transport

assert.Equal(t, false, transport.closed)
client.CloseIdleConnections()
assert.Equal(t, true, transport.closed)
}

0 comments on commit d8025ed

Please sign in to comment.