/
webhook.go
85 lines (71 loc) · 2.32 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
81
82
83
84
85
package webhook
import (
"encoding/json"
"io/ioutil"
"net/http"
"github.com/julienschmidt/httprouter"
"github.com/agoda-com/samsahai/internal"
s2herrors "github.com/agoda-com/samsahai/internal/errors"
)
func (h *handler) readRequestBody(w http.ResponseWriter, r *http.Request) ([]byte, error) {
data, err := ioutil.ReadAll(r.Body)
if err != nil {
logger.Error(err, "cannot read from req.body")
h.error(w, http.StatusInternalServerError, s2herrors.ErrInternalError)
return nil, err
}
return data, nil
}
var pluginWebhookFunc = func(h *handler, plugin internal.Plugin) func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
return func(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
data, err := h.readRequestBody(w, r)
if err != nil {
return
}
var jsonData newComponentEventJSON
err = json.Unmarshal(data, &jsonData)
if err != nil {
h.error(w, http.StatusBadRequest, s2herrors.ErrInvalidJSONData)
return
}
compName := plugin.GetComponentName(jsonData.Component)
if compName != "" {
logger.Debug("webhook request",
"plugin", plugin.GetName(),
"reqData", string(data),
"component", jsonData.Component,
"output", compName)
h.samsahai.NotifyComponentChanged(compName, "", "")
}
w.WriteHeader(http.StatusNoContent)
}
}
type newComponentEventJSON struct {
TeamName string `json:"teamName,omitempty"`
Component string `json:"component"`
Repository string `json:"repository,omitempty"`
}
// newComponentWebhook godoc
// @Summary Webhook New Component
// @Description Endpoint for manually triggering new component update
// @Tags POST
// @Accept json
// @Produce json
// @Param newComponentEventJSON body webhook.newComponentEventJSON true "New Component"
// @Success 204 {string} string
// @Failure 400 {object} errResp "Invalid JSON"
// @Router /webhook/component [post]
func (h *handler) newComponentWebhook(w http.ResponseWriter, r *http.Request, params httprouter.Params) {
data, err := h.readRequestBody(w, r)
if err != nil {
return
}
var jsonData newComponentEventJSON
err = json.Unmarshal(data, &jsonData)
if err != nil {
h.error(w, http.StatusBadRequest, s2herrors.ErrInvalidJSONData)
return
}
h.samsahai.NotifyComponentChanged(jsonData.Component, jsonData.Repository, jsonData.TeamName)
w.WriteHeader(http.StatusNoContent)
}