Skip to content
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
15 changes: 12 additions & 3 deletions fcm.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package fcm

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
Expand Down Expand Up @@ -154,8 +155,7 @@ func (this *FcmClient) apiKeyHeader() string {
}

// sendOnce send a single request to fcm
func (this *FcmClient) sendOnce() (*FcmResponseStatus, error) {

func (this *FcmClient) sendOnce(ctx context.Context) (*FcmResponseStatus, error) {
fcmRespStatus := new(FcmResponseStatus)

jsonByte, err := this.Message.toJsonByte()
Expand All @@ -167,6 +167,10 @@ func (this *FcmClient) sendOnce() (*FcmResponseStatus, error) {
request.Header.Set("Authorization", this.apiKeyHeader())
request.Header.Set("Content-Type", "application/json")

if ctx != nil {
request = request.WithContext(ctx)
}

client := &http.Client{}
response, err := client.Do(request)

Expand Down Expand Up @@ -199,8 +203,13 @@ func (this *FcmClient) sendOnce() (*FcmResponseStatus, error) {

// Send to fcm
func (this *FcmClient) Send() (*FcmResponseStatus, error) {
return this.sendOnce()
return this.sendOnce(nil)

}

// SendWithContext sends the request to FCM with a context
func (this *FcmClient) SendWithContext(ctx context.Context) (*FcmResponseStatus, error) {
return this.sendOnce(ctx)
}

// toJsonByte converts FcmMsg to a json byte
Expand Down
37 changes: 37 additions & 0 deletions fcm_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package fcm

import (
"context"
"fmt"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -159,6 +160,42 @@ func TestRegIdHandle_2(t *testing.T) {
}
}

func TestSendWithContext(t *testing.T) {

srv := httptest.NewServer(http.HandlerFunc(regIdHandle))
chgUrl(srv)
defer srv.Close()

c := NewFcmClient("key")

data := map[string]string{
"msg": "Hello World",
"sum": "Happy Day",
}

c.NewFcmMsgTo("/topics/topicName", data)

ctx, cancel := context.WithCancel(context.Background())
defer cancel()

res, err := c.SendWithContext(ctx)
if err != nil {
t.Error("Response Error : ", err)
}
if res == nil {
t.Error("Res is nil")
}

// After the cancellation the request is expected to fail.
cancel()

_, err = c.SendWithContext(ctx)
if err == nil {
t.Errorf("expected context error, got %v", err)
}

}

func chgUrl(ts *httptest.Server) {
fcmServerUrl = ts.URL
}
Expand Down