This repository was archived by the owner on Sep 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
87 lines (79 loc) · 1.92 KB
/
main.go
File metadata and controls
87 lines (79 loc) · 1.92 KB
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
package main
import (
"bytes"
"io/ioutil"
"os"
"fmt"
"log"
"net/http"
)
var wrongMsg string
var tokens map[string]string
var authorizationKey string
func main() {
authorizationKey = os.Args[1]
tokens = make(map[string]string)
http.HandleFunc("/addToken/", handleAddToken)
http.HandleFunc("/sendMessage/", handleSendMessage)
log.Fatal(http.ListenAndServe(":65000", nil))
}
func sendMessageToFirebase(token string, msg string) {
var jsonStr = []byte(`{
"data": {
"msg": "`+msg+`"
},
"to" : "`+token+`"
}`)
req, err := http.NewRequest(
"POST",
"https://fcm.googleapis.com/fcm/send",
bytes.NewBuffer(jsonStr))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "key="+authorizationKey)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
}
func handleAddToken(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "POST requests only", http.StatusMethodNotAllowed)
return
} else {
var token string;
token = r.FormValue("id")
_,ok := tokens[token]
if (ok == false) {
tokens[token] = token
log.Println("addToken: " + token)
} else {
log.Println("Token still exists")
}
}
fmt.Fprintf(w, "Hallo Client")
}
func handleSendMessage(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "POST requests only", http.StatusMethodNotAllowed)
return
} else {
var toToken string;
var msg string;
toToken = r.FormValue("to")
msg = r.FormValue("msg")
log.Println("SendMessage: " + toToken + " -> " + msg)
_,ok := tokens[toToken]
if (ok == false) {
log.Println("Token not exists")
} else {
sendMessageToFirebase(toToken, msg)
}
}
fmt.Fprintf(w, "Hallo Client")
}