-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpush.go
57 lines (50 loc) · 1.23 KB
/
push.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
package led
import (
"encoding/json"
"io"
"net/http"
"path/filepath"
"github.com/SherClockHolmes/webpush-go"
"github.com/joho/godotenv"
)
func (f *FileHandler) webPush(w http.ResponseWriter, req *http.Request) {
d := map[string]string{
"title": req.FormValue("title"),
"body": req.FormValue("body"),
"data": req.FormValue("data"),
}
m, err := json.Marshal(d)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
var s webpush.Subscription
subs := req.FormValue("subs")
if err := json.Unmarshal([]byte(subs), &s); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(err.Error()))
return
}
envs, err := godotenv.Read(filepath.Join(f.Root, "env"))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
o := webpush.Options{
TTL: 86400,
Subscriber: envs["PUSH_SUBSCRIBER"],
VAPIDPublicKey: envs["PUSH_VAPID_PUB"],
VAPIDPrivateKey: envs["PUSH_VAPID_PRI"],
}
r, err := webpush.SendNotification(m, &s, &o)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
defer r.Body.Close()
w.WriteHeader(r.StatusCode)
io.Copy(w, r.Body)
}