-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
84 lines (66 loc) · 1.71 KB
/
http.go
File metadata and controls
84 lines (66 loc) · 1.71 KB
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
package copilot
import (
"encoding/json"
"net/http"
"fmt"
"errors"
"strings"
"github.com/eirwin/copilot/pkg/config"
"github.com/eirwin/copilot/pkg/k8s"
)
type Server struct {
kubernetes k8s.Kubernetes
}
func NewServer(kubernetes k8s.Kubernetes) Server {
return Server{
kubernetes: kubernetes,
}
}
func (s Server) Handler(w http.ResponseWriter, r *http.Request) {
var output string
parser := CommandParser{}
// parse request text
text, err := parseText(config.SlackToken(), w, r)
if err != nil {
output = parser.HelpWitMessage(err.Error())
respond(output, w, r)
return
}
// parse command from text
cmd, err := parser.Parse(text)
if err != nil {
output = parser.Help()
respond(output, w, r)
return
}
// initialize copilot service
service := NewService(s.kubernetes)
output, err = service.Run(cmd)
if err != nil {
output = parser.Help()
respond(output, w, r)
}
respond(output, w, r)
}
func respond(output string, w http.ResponseWriter, r *http.Request) {
json, _ := json.Marshal(struct {
Type string `json:"response_type"`
Text string `json:"text"`
}{
Type: "in_channel",
Text: fmt.Sprintf("```%s```", output),
})
w.Header().Add("Content-Type", "application/json")
fmt.Fprintf(w, string(json))
}
func parseText(token string, w http.ResponseWriter, r *http.Request) (string, error) {
if r.Method != "POST" {
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
return "", errors.New("method not allowed")
}
if token != r.FormValue("token") {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
return "", errors.New("unauthorized")
}
return strings.Replace(r.FormValue("text"), "\r", "", -1), nil
}