-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfcm.go
116 lines (100 loc) · 2.39 KB
/
fcm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package fcm
import (
"errors"
"net/http"
"strings"
"fmt"
"io/ioutil"
"encoding/json"
)
type Fcm struct{
auth string
to string
title string
body string
data []byte
}
type Response1 struct{
Mid uint64 `json:"message_id"`
}
type Res struct{
MessageId string `json:"message_id"`
}
type Response2 struct{
MultiCast uint64 `json:"multicast_id"`
Success int `json:"success"`
Failure int `json:"failure"`
CanonicalIds int `json:"canonical_ids"`
Results []Res `json:"results"`
}
func(f *Fcm)Init (auth string ,to string ,title string ,body string,data []byte)(){
f.auth=auth;
f.to=to
f.title=title
f.body=body
f.data=data
return
}
func (f Fcm)SendNotif()(err error,resi []byte){
if(f.auth==""){
err=errors.New("App not Initialized properly");
}else{
url := "https://gcm-http.googleapis.com/gcm/send"
if(strings.HasPrefix(f.auth,"key=")){
f.auth=strings.Replace(f.auth,"key=","",1)
}
payload := strings.NewReader("{\n \"to\":\""+f.to+"\",\n \"data\": \n"+string(f.data)+",\n \"notification\": {\n \"title\":\""+f.title+"\",\n \"body\": \""+f.body+"\"\n }\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("authorization", "key="+f.auth)
req.Header.Add("content-type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, err2 := ioutil.ReadAll(res.Body)
if err2 != nil {
panic(err.Error())
}
if(strings.HasPrefix((strings.ToLower(f.to)),"/topics/")){
//fmt.Println(string(body))
r, err3 := getRes1([]byte(body))
if err3 != nil {
panic(err.Error())
}
ret, err3 := json.Marshal(r)
if err3 != nil {
panic(err.Error())
} else{
resi=[]byte( ret);}
}else{
//fmt.Println(string(body))
r, err3 := getRes2([]byte(body))
if err3 != nil {
panic(err.Error())
}
if(r.Success>=1&&r.Failure<=0){
ret, err3 := json.Marshal(r)
if err3 != nil {
panic(err.Error())
} else{resi=[]byte( ret);}
}else{
resi=[]byte(`{error:"Something went Wrong"}`);
}
}
}
return
}
func getRes1(body []byte) (*Response1, error) {
var s = new(Response1)
err := json.Unmarshal(body, &s)
if(err != nil){
fmt.Println("whoops:", err)
}
return s, err
}
func getRes2(body []byte) (*Response2, error) {
var s = new(Response2)
err := json.Unmarshal(body, &s)
if(err != nil){
fmt.Println("whoops:", err)
}
return s, err
}