-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
126 lines (100 loc) · 2.45 KB
/
main.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
117
118
119
120
121
122
123
124
125
126
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/spec-tacles/go/tree/master/broker"
)
type VoteData struct {
BotID string `json:"bot"`
UserID string `json:"user"`
Type string `json:"type"`
IsWeekend bool `json:"isWeekend"`
Query string `json:"query"`
}
func (d *VoteData) Bytes() []byte {
buffer := new(bytes.Buffer)
json.NewEncoder(buffer).Encode(d)
return buffer.Bytes()
}
var (
endpoint = os.Getenv("ENDPOINT")
address = os.Getenv("ADDRESS")
secret = os.Getenv("DBL_SECRET")
amqpURL = os.Getenv("AMQP_URL")
amqpGroup = os.Getenv("AMQP_GROUP")
)
var rabbit *broker.AMQP
func main() {
validateEnv()
rabbit = broker.NewAMQP(amqpGroup, "", nil)
go rabbit.Connect(amqpURL)
http.HandleFunc(endpoint, handleIncoming())
log.Printf("webhook serevr started at %+s%+s", address, endpoint)
err := http.ListenAndServe(address, nil)
log.Panicf("server crashed with error: %+v", err)
os.Exit(1)
}
func handleIncoming() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusForbidden)
fmt.Fprintf(w, "Forbidden")
return
}
auth := r.Header.Get("Authorization")
if auth == "" {
log.Printf("incoming request from %+s had no authorization header", r.RemoteAddr)
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintf(w, "Unauthorized")
return
}
if auth != secret {
log.Printf("incoming request from %+s had a mismatched authorization header", r.RemoteAddr)
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprint(w, "Unauthorized")
return
}
var payload *VoteData
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&payload)
if err != nil {
log.Printf("incoming request from %+s sent malformed vote data", r.RemoteAddr)
w.WriteHeader(http.StatusBadRequest)
fmt.Fprint(w, "Bad Request")
log.Println(err)
return
}
rabbit.PublishOptions(broker.PublishOptions{
Event: "VOTE",
Data: payload.Bytes(),
Timeout: 2 * time.Minute,
})
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "OK")
return
}
}
func validateEnv() bool {
if endpoint == "" {
endpoint = "/webhook/vote"
}
if address == "" {
address = ":4500"
}
if amqpGroup == "" {
amqpGroup = "votes"
}
if amqpURL == "" {
amqpURL = "amqp://localhost//"
}
if secret == "" {
log.Panicf("required environment variable 'DBL_SECRET' was not provided")
os.Exit(1)
}
return true
}