This repository has been archived by the owner on Feb 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
78 lines (63 loc) · 1.76 KB
/
router.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
package teledisq
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"google.golang.org/appengine"
"google.golang.org/appengine/log"
)
const (
HookTypeParam = "type"
DiscourseValue = "discourse"
)
func SetupRouter() {
http.HandleFunc("/", healthHandler)
http.HandleFunc(fmt.Sprintf("/hook/%s/", os.Getenv("DISCOURSE_WEBHOOK")), hookHandler)
http.HandleFunc(fmt.Sprintf("/telegram/%s/", os.Getenv("TELEGRAM_WEBHOOK")), telegramHandler)
}
func healthHandler(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "All your base are belong to us!")
}
func hookHandler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Errorf(ctx, "hookHandler error: %s", err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var notification ExternalNotification
switch r.URL.Query().Get(HookTypeParam) {
case DiscourseValue:
notification, err = HandleDiscourseEvent(ctx, r.Header, body)
default:
return
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if notification == nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
NotifySubscribersByTheme(ctx, ThemeDiscourse, func(chat int64) {
SendFormattedMessage(ctx, chat, notification.Message(), HTMLFormatting)
})
w.WriteHeader(http.StatusOK)
}
func telegramHandler(w http.ResponseWriter, r *http.Request) {
ctx := appengine.NewContext(r)
u := Update{}
err := json.NewDecoder(r.Body).Decode(&u)
if err != nil {
log.Errorf(ctx, "Telegram update decoding error: %s", err.Error())
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
HandleTelegramUpdate(ctx, u)
w.WriteHeader(http.StatusOK)
}