-
Notifications
You must be signed in to change notification settings - Fork 26
/
slackline.go
76 lines (62 loc) · 1.44 KB
/
slackline.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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"github.com/codegangsta/martini"
"io"
"io/ioutil"
"net/http"
)
const postMessageURL = "/services/hooks/incoming-webhook?token="
type slackMessage struct {
Channel string `json:"channel"`
Username string `json:"username"`
Text string `json:"text"`
}
func (s slackMessage) payload() io.Reader {
content := []byte("payload=")
json, _ := json.Marshal(s)
content = append(content, json...)
return bytes.NewReader(content)
}
func (s slackMessage) sendTo(domain, token string) (err error) {
payload := s.payload()
res, err := http.Post(
"https://"+domain+postMessageURL+token,
"application/x-www-form-urlencoded",
payload,
)
if res.StatusCode != 200 {
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
return errors.New(res.Status + " - " + string(body))
}
return
}
func main() {
m := martini.Classic()
m.Post("/bridge", func(res http.ResponseWriter, req *http.Request) {
username := req.PostFormValue("user_name")
text := req.PostFormValue("text")
if username == "slackbot" {
// Avoid infinite loop
return
}
msg := slackMessage{
Username: username,
Text: text,
}
domain := req.URL.Query().Get("domain")
token := req.URL.Query().Get("token")
err := msg.sendTo(domain, token)
if err != nil {
fmt.Printf("Error: %s\n", err.Error())
res.WriteHeader(500)
} else {
fmt.Println("Message sent")
}
})
m.Run()
}