-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.go
115 lines (91 loc) · 2.48 KB
/
server.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
)
type Handshake struct {
Type string `json:"type"`
Challenge string `json:"challenge"`
}
func setupServer() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/text")
})
mux.HandleFunc("/healthcheck", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/text")
w.Write([]byte("OK"))
fmt.Println("healthcheck")
})
mux.HandleFunc("/gitlab-webhook", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/text")
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatalln(err)
}
receivedSignature := r.Header.Get("X-Gitlab-Token")
if receivedSignature != GITLAB_WEBHOOK_SECRET_TOKEN {
fmt.Printf("Invalid secret token, received ''%v'', expected ''%v''\n", receivedSignature, GITLAB_WEBHOOK_SECRET_TOKEN)
w.WriteHeader(http.StatusUnauthorized)
return
}
var webhookEvent GitLabWebhookEvent
json.Unmarshal(body, &webhookEvent)
err = handleGitLabWebhook(webhookEvent)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusNoContent)
}
fmt.Println("---------------")
})
mux.HandleFunc("/slack-events", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/text")
if r.Method != "POST" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
var payload SlackPayload
body, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatalln(err)
}
json.Unmarshal(body, &payload)
if payload.Type == "event_callback" {
err = handleSlackEvent(payload.Event)
if err != nil {
log.Println(err)
w.WriteHeader(http.StatusNoContent)
}
} else if payload.Type == "url_verification" {
w.WriteHeader(http.StatusOK)
w.Write([]byte(payload.Challenge))
}
fmt.Println("---------------")
})
fmt.Println("Starting server...")
// Determine port for HTTP service.
port := PORT
if port == 0 {
port = 8080
fmt.Printf("Defaulting to port %v\n", port)
}
server := &http.Server{
Addr: fmt.Sprintf(":%v", port),
Handler: mux,
}
server.SetKeepAlivesEnabled(false)
fmt.Printf("Server listening on localhost:%v\n", port)
err := server.ListenAndServe()
if err != nil {
log.Fatalln(err)
}
}