Skip to content
This repository was archived by the owner on Jun 6, 2023. It is now read-only.

Commit

Permalink
check payload size before hitting Apple (#67)
Browse files Browse the repository at this point in the history
closes #65

it was documented and I tested it to be 4096 bytes
  • Loading branch information
nathany authored Jun 15, 2016
1 parent b5f0854 commit 259170c
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
10 changes: 10 additions & 0 deletions push/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ const (
Production2197 = "https://api.push.apple.com:2197"
)

const maxPayload = 4096 // 4KB at most

// Service is the Apple Push Notification Service that you send notifications to.
type Service struct {
Host string
Expand Down Expand Up @@ -52,6 +54,14 @@ func NewClient(cert tls.Certificate) (*http.Client, error) {

// Push sends a notification and waits for a response.
func (s *Service) Push(deviceToken string, headers *Headers, payload []byte) (string, error) {
// check payload length before even hitting Apple.
if len(payload) > maxPayload {
return "", &Error{
Reason: ErrPayloadTooLarge,
Status: http.StatusRequestEntityTooLarge,
}
}

urlStr := fmt.Sprintf("%v/3/device/%v", s.Host, deviceToken)

req, err := http.NewRequest("POST", urlStr, bytes.NewReader(payload))
Expand Down
22 changes: 22 additions & 0 deletions push/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -141,3 +142,24 @@ func TestTimestampError(t *testing.T) {
t.Errorf("Expected timestamp %v, got %v.", expected, e.Timestamp)
}
}

func TestPayloadTooLarge(t *testing.T) {
payload := []byte(strings.Repeat("0123456789abcdef", 256) + "x")

service := push.NewService(http.DefaultClient, "host")
_, err := service.Push("device-token", nil, payload)
if err == nil {
t.Fatal("Expected error, got none")
}
if _, ok := err.(*push.Error); !ok {
t.Fatalf("Expected push error, got %v.", err)
}

e := err.(*push.Error)
if e.Reason != push.ErrPayloadTooLarge {
t.Errorf("Expected PayloadTooLarge, got reason %q.", e.Reason)
}
if e.Status != http.StatusRequestEntityTooLarge {
t.Errorf("Expected status %v, got %v.", http.StatusRequestEntityTooLarge, e.Status)
}
}

0 comments on commit 259170c

Please sign in to comment.