Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Utilised json.Unmarshal instead of json.NewDecoder #206

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import (
"context"
"crypto/tls"
"encoding/json"
"io"
"net"
"net/http"
"strconv"
"sync"
"time"

"github.com/sideshow/apns2/token"
Expand Down Expand Up @@ -183,13 +183,28 @@ func (c *Client) PushWithContext(ctx Context, n *Notification) (*Response, error
r.StatusCode = response.StatusCode
r.ApnsID = response.Header.Get("apns-id")

decoder := json.NewDecoder(response.Body)
if err := decoder.Decode(r); err != nil && err != io.EOF {
buffer := buffers.Get().(*bytes.Buffer)
buffer.Reset()
defer buffers.Put(buffer)

if _, err := buffer.ReadFrom(response.Body); err != nil {
return nil, err
}
if buffer.Len() == 0 {
return r, nil
}
if err := json.Unmarshal(buffer.Bytes(), r); err != nil {
return &Response{}, err
}
return r, nil
}

var buffers = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}

// 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.
Expand Down
11 changes: 11 additions & 0 deletions client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,17 @@ func TestMalformedJSONResponse(t *testing.T) {
assert.Equal(t, false, res.Sent())
}

func TestUnexpectedEOF(t *testing.T) {
n := mockNotification()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", "1")
}))
defer server.Close()
res, err := mockClient(server.URL).Push(n)
assert.Error(t, err)
assert.Nil(t, res)
}

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

Expand Down