-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathslack-payload-handler.go
174 lines (141 loc) · 4.57 KB
/
slack-payload-handler.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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"net/http/httputil"
"os"
"strconv"
"time"
log "github.com/sirupsen/logrus"
"github.com/gorilla/mux"
)
var (
listenPort int // port to listen on (flag opt)
debugRequest bool = false // dumps raw request from slack to STDOUT
debugResponse bool = false // dumps returned/modified response to STDOUT
)
// Struct for JSON we retun to caller
type actionsResponse struct {
Whatever string `json:"whatever"`
}
type mutatedPayload struct {
ActionsPressed []string
}
func init() {
// cmd line args
flag.IntVar(&listenPort, "listen-port", 8080, "Optional, port to listen on, default 8080")
flag.BoolVar(&debugRequest, "debug-request", false, "Optional, print requests to STDOUT, default false")
flag.BoolVar(&debugResponse, "debug-response", false, "Optional, print responses to STDOUT, default false")
// logging options
log.SetFormatter(&log.JSONFormatter{})
log.SetOutput(os.Stdout)
log.SetLevel(log.DebugLevel)
}
func main() {
flag.Parse()
// setup our REST routes
router := mux.NewRouter()
router.Path("/").
Methods("POST").
Schemes("http").
HandlerFunc(ProcessSlackRequest)
// fire up the http server
srv := &http.Server{
Handler: router,
Addr: (":" + strconv.Itoa(listenPort)),
WriteTimeout: 20 * time.Second,
ReadTimeout: 20 * time.Second,
}
log.Fatal(srv.ListenAndServe())
}
// writes an HTTP response w/ code + json result
func writeHTTPResponse(resWriter http.ResponseWriter, result string, httpStatus int) {
resWriter.Header().Set("Content-Type", "application/json")
resWriter.WriteHeader(httpStatus)
json.NewEncoder(resWriter).Encode(&actionsResponse{Whatever: result})
}
// validates the request signature (TODO)
func validateRequestSignature(req *http.Request) (bool, error) {
return true, nil
}
// ProcessSlackRequest ... http handler for processing the inbound slack POST payload
func ProcessSlackRequest(resWriter http.ResponseWriter, req *http.Request) {
// Save a copy of this request for debugging?
if debugRequest {
requestDump, err := httputil.DumpRequest(req, true)
if err != nil {
fmt.Println(err)
}
fmt.Println(string(requestDump))
}
// first lets get the credentials off the request
validated, err := validateRequestSignature(req)
if err != nil || !validated {
writeHTTPResponse(resWriter, "Bad Request: security check failed", http.StatusBadRequest)
return
}
// what we will return
responseMap := make(map[string]interface{})
// is the POST for an slack interactive message? if so
// then the POST body is payload={data}
payloadVal := req.FormValue("payload")
if payloadVal != "" {
// extract json from the payload
var rawData []byte = []byte(req.FormValue("payload"))
if rawData != nil && len(rawData) > 0 {
if debugRequest {
fmt.Printf("\nJSON RECEIVED: \n%s\n\n", rawData)
}
// map all json data on the RHS of payload= into
// our responseMap
err = json.Unmarshal(rawData, &responseMap)
if err != nil {
fmt.Printf("Could not parse Slack 'payload' into JSON: \n%v\n\n", err)
}
} else {
log.Error("HTTP POST contained no FormData body where payload=[data]")
return
}
if responseMap["actions"] == nil {
log.Error("HTTP POST JSON contained no 'actions' element'")
return
}
var actionValuesArr []string
var actionsArr []interface{} = responseMap["actions"].([]interface{})
for i := 0; i < len(actionsArr); i++ {
var actionMap map[string]interface{} = actionsArr[i].(map[string]interface{})
var theval string = actionMap["value"].(string)
actionValuesArr = append(actionValuesArr, theval)
}
responseMap["action_values"] = actionValuesArr
// is the POST for an slack slash command? if so
// then the POST body should contain ...&command=N&...
} else if req.FormValue("command") != "" {
for k, v := range req.PostForm {
responseMap[k] = v[0]
}
jsonStr, err := json.Marshal(&responseMap)
if err != nil {
fmt.Printf("Failed to process slack POST: \n %v", err)
} else {
fmt.Printf("ONE: %s", jsonStr)
}
} else {
fmt.Printf("POSTed body is unrecognized POST body contains neither: 'payload={}' OR '...&command=N&...' content")
}
if debugResponse {
jsonStr, err := json.Marshal(&responseMap)
if err != nil {
fmt.Printf("Failed to process slack POST: \n %v", err)
} else if jsonStr != nil {
fmt.Printf("RESPONSE: \n%s", jsonStr)
} else {
fmt.Printf("RESPONSE: \njsonstr nil? jsonStr=%s", jsonStr)
}
}
resWriter.Header().Set("Content-Type", "application/json")
resWriter.WriteHeader(http.StatusOK)
json.NewEncoder(resWriter).Encode(responseMap)
}