This repository was archived by the owner on Nov 4, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathmain.go
78 lines (65 loc) · 1.52 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
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
const botID = "brackets-bot"
type event struct {
Text string `json:"text"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
}
type response struct {
Text string `json:"text"`
Bot string `json:"bot"`
}
func main() {
log.Printf("brackets-bot")
reportErr := func(err error, w http.ResponseWriter) {
w.WriteHeader(http.StatusExpectationFailed)
fmt.Fprintf(w, "%v", err)
}
http.HandleFunc("/event", func(w http.ResponseWriter, r *http.Request) {
st := time.Now()
body, err := ioutil.ReadAll(r.Body)
if err != nil {
reportErr(err, w)
return
}
ev := event{}
if err = json.Unmarshal(body, &ev); err != nil {
reportErr(err, w)
return
}
text_resp, err := processString(ev.Text)
if err != nil {
reportErr(err, w)
return
}
if text_resp == "" {
reportErr(errors.New("Empty result"), w)
return
}
resp := response{
Bot: botID,
Text: fmt.Sprintf("%s\nЗакрывай скобки, @%s !!!", text_resp, ev.Username),
}
bresp, err := json.Marshal(resp)
if err != nil {
reportErr(err, w)
return
}
log.Printf("%+v - %v - %s - %s", ev, time.Since(st), r.RemoteAddr, r.UserAgent())
w.Header().Set("Content-Type", "application/json; charset=UTF-8")
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, "%s", string(bresp))
})
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalf("failed to start server, %v", err)
}
}