forked from found-it/webhook-processor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebhook.go
80 lines (65 loc) · 1.66 KB
/
webhook.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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
)
var logging = logrus.New()
var log = logging.WithFields(logrus.Fields{"server": "0.0.0.0:9000"})
/*
* [ Handler ] Home landing page
*/
func homeLink(w http.ResponseWriter, r *http.Request) {
log.Info("Hit home")
fmt.Fprintf(w, "Welcome to webhook server!")
}
func authorized(w http.ResponseWriter, r *http.Request) bool {
if u, p, ok := r.BasicAuth(); ok {
if u == os.Getenv("WEBHOOK_USERNAME") && p == os.Getenv("WEBHOOK_PASSWORD") {
return true
}
log.WithFields(logrus.Fields{
"username": u,
}).Error("Unauthorized")
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintf(w, "Unauthorized")
return false
}
w.WriteHeader(http.StatusUnauthorized)
fmt.Fprintf(w, "Unauthorized")
log.Error("Parsing basic auth failed")
return false
}
/*
*/
func processor(w http.ResponseWriter, r *http.Request) {
if authorized(w, r) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Fprintf(w, "Incorrect request")
}
log.WithFields(logrus.Fields{
"url": r.URL,
}).Info("Received!")
log.Info(string(body))
w.WriteHeader(http.StatusOK)
}
}
/*
* Use Gorilla Mux to handle routes
*/
func main() {
if _, ok := os.LookupEnv("WEBHOOK_USERNAME"); !ok {
log.Fatal("Could not find WEBHOOK_USERNAME in environment")
}
if _, ok := os.LookupEnv("WEBHOOK_PASSWORD"); !ok {
log.Fatal("Could not find WEBHOOK_PASSWORD in environment")
}
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", homeLink)
router.HandleFunc("/v1/webhook", processor).Methods("POST")
log.Fatal(http.ListenAndServe(":9000", router))
}