Skip to content

Commit

Permalink
Use NewRequestWithContext instead of nil checking
Browse files Browse the repository at this point in the history
  • Loading branch information
moredure committed Apr 2, 2022
1 parent c0c7ebb commit 923458b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 10 deletions.
13 changes: 3 additions & 10 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ func (c *Client) Production() *Client {
//
// Use PushWithContext if you need better cancellation and timeout control.
func (c *Client) Push(n *Notification) (*Response, error) {
return c.PushWithContext(nil, n)
return c.PushWithContext(context.Background(), n)
}

// PushWithContext sends a Notification to the APNs gateway. Context carries a
Expand All @@ -162,7 +162,7 @@ func (c *Client) PushWithContext(ctx Context, n *Notification) (*Response, error
}

url := fmt.Sprintf("%v/3/device/%v", c.Host, n.DeviceToken)
req, err := http.NewRequest("POST", url, bytes.NewReader(payload))
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewReader(payload))
if err != nil {
return nil, err
}
Expand All @@ -173,7 +173,7 @@ func (c *Client) PushWithContext(ctx Context, n *Notification) (*Response, error

setHeaders(req, n)

httpRes, err := c.requestWithContext(ctx, req)
httpRes, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -226,10 +226,3 @@ func setHeaders(r *http.Request, n *Notification) {
}

}

func (c *Client) requestWithContext(ctx Context, req *http.Request) (*http.Response, error) {
if ctx != nil {
req = req.WithContext(ctx)
}
return c.HTTPClient.Do(req)
}
15 changes: 15 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,21 @@ func TestClientPushWithContext(t *testing.T) {
assert.Equal(t, res.ApnsID, apnsID)
}

func TestClientPushWithNilContext(t *testing.T) {
n := mockNotification()
var apnsID = "02ABC856-EF8D-4E49-8F15-7B8A61D978D6"
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("apns-id", apnsID)
w.WriteHeader(http.StatusOK)
}))
defer server.Close()

res, err := mockClient(server.URL).PushWithContext(nil, n)
assert.EqualError(t, err, "net/http: nil Context")
assert.Nil(t, res)
}

func TestHeaders(t *testing.T) {
n := mockNotification()
n.ApnsID = "84DB694F-464F-49BD-960A-D6DB028335C9"
Expand Down

0 comments on commit 923458b

Please sign in to comment.