/
main.go
71 lines (59 loc) · 1.33 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
package main
import (
"net/http"
"net/url"
"os"
"strconv"
"github.com/narqo/go-dice/Godeps/_workspace/src/github.com/apex/log"
logfmt "github.com/narqo/go-dice/Godeps/_workspace/src/github.com/apex/log/handlers/logfmt"
"github.com/narqo/go-dice/dice"
)
var token string
func checkAuth(intoken string) bool {
return intoken == token
}
func rollDice(w http.ResponseWriter, req *http.Request) {
q, _ := url.ParseQuery(req.URL.RawQuery)
intoken, ok := q["token"]
if !ok {
w.WriteHeader(http.StatusUnauthorized)
return
}
if !checkAuth(intoken[0]) {
w.WriteHeader(http.StatusForbidden)
return
}
dn, ok := q["text"]
if !ok {
w.WriteHeader(http.StatusBadRequest)
return
}
dc, err := dice.Parse(dn[0])
if err != nil {
log.WithError(err).Debug("parse")
w.WriteHeader(http.StatusBadRequest)
return
}
w.Write([]byte(strconv.Itoa(dc.Roll())))
}
func main() {
log.SetHandler(logfmt.New(os.Stderr))
log.SetLevel(log.DebugLevel)
port := os.Getenv("PORT")
if port == "" {
log.Fatal("$PORT was not set")
}
token = os.Getenv("SLACK_TOKEN")
if token == "" {
log.Info("$SLACK_TOKEN was not set")
} else {
log.WithFields(log.Fields{
"token": token,
}).Debug("token")
}
http.HandleFunc("/roll", rollDice)
err := http.ListenAndServe(":"+port, nil)
if err != nil {
log.WithError(err).Fatal("Cannot listen")
}
}