Skip to content

Commit d8025ed

Browse files
authored
Add CloseIdleConnections method to close tcp connections (#92)
1 parent 0700d12 commit d8025ed

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

client.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,10 @@ type Client struct {
4545
Host string
4646
}
4747

48+
type connectionCloser interface {
49+
CloseIdleConnections()
50+
}
51+
4852
// NewClient returns a new Client with an underlying http.Client configured with
4953
// the correct APNs HTTP/2 transport settings. It does not connect to the APNs
5054
// until the first Notification is sent via the Push method.
@@ -142,6 +146,13 @@ func (c *Client) PushWithContext(ctx Context, n *Notification) (*Response, error
142146
return response, nil
143147
}
144148

149+
// CloseIdleConnections closes any underlying connections which were previously
150+
// connected from previous requests but are now sitting idle. It will not
151+
// interrupt any connections currently in use.
152+
func (c *Client) CloseIdleConnections() {
153+
c.HTTPClient.Transport.(connectionCloser).CloseIdleConnections()
154+
}
155+
145156
func setHeaders(r *http.Request, n *Notification) {
146157
r.Header.Set("Content-Type", "application/json; charset=utf-8")
147158
if n.Topic != "" {

client_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,15 @@ func mockClient(url string) *apns.Client {
3535
return &apns.Client{Host: url, HTTPClient: http.DefaultClient}
3636
}
3737

38+
type mockTransport struct {
39+
*http2.Transport
40+
closed bool
41+
}
42+
43+
func (c *mockTransport) CloseIdleConnections() {
44+
c.closed = true
45+
}
46+
3847
// Unit Tests
3948

4049
func TestClientDefaultHost(t *testing.T) {
@@ -231,3 +240,14 @@ func TestMalformedJSONResponse(t *testing.T) {
231240
assert.Error(t, err)
232241
assert.Equal(t, false, res.Sent())
233242
}
243+
244+
func TestCloseIdleConnections(t *testing.T) {
245+
transport := &mockTransport{}
246+
247+
client := mockClient("")
248+
client.HTTPClient.Transport = transport
249+
250+
assert.Equal(t, false, transport.closed)
251+
client.CloseIdleConnections()
252+
assert.Equal(t, true, transport.closed)
253+
}

0 commit comments

Comments
 (0)