forked from mailgun/mailgun-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock_webhooks.go
83 lines (70 loc) · 2.01 KB
/
mock_webhooks.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
package mailgun
import (
"net/http"
"github.com/go-chi/chi"
)
func (ms *MockServer) addWebhookRoutes(r chi.Router) {
r.Route("/domains/{domain}/webhooks", func(r chi.Router) {
r.Get("/", ms.listWebHooks)
r.Post("/", ms.postWebHook)
r.Get("/{webhook}", ms.getWebHook)
r.Put("/{webhook}", ms.putWebHook)
r.Delete("/{webhook}", ms.deleteWebHook)
})
ms.webhooks = WebHooksListResponse{
Webhooks: map[string]UrlOrUrls{
"new-webhook": {
Urls: []string{"http://example.com/new"},
},
"legacy-webhook": {
Url: "http://example.com/legacy",
},
},
}
}
func (ms *MockServer) listWebHooks(w http.ResponseWriter, _ *http.Request) {
toJSON(w, ms.webhooks)
}
func (ms *MockServer) getWebHook(w http.ResponseWriter, r *http.Request) {
resp := WebHookResponse{
Webhook: UrlOrUrls{
Urls: ms.webhooks.Webhooks[chi.URLParam(r, "webhook")].Urls,
},
}
toJSON(w, resp)
}
func (ms *MockServer) postWebHook(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
w.WriteHeader(http.StatusBadRequest)
toJSON(w, okResp{Message: err.Error()})
return
}
var urls []string
for _, url := range r.Form["url"] {
urls = append(urls, url)
}
ms.webhooks.Webhooks[r.FormValue("id")] = UrlOrUrls{Urls: urls}
toJSON(w, okResp{Message: "success"})
}
func (ms *MockServer) putWebHook(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
w.WriteHeader(http.StatusBadRequest)
toJSON(w, okResp{Message: err.Error()})
return
}
var urls []string
for _, url := range r.Form["url"] {
urls = append(urls, url)
}
ms.webhooks.Webhooks[chi.URLParam(r, "webhook")] = UrlOrUrls{Urls: urls}
toJSON(w, okResp{Message: "success"})
}
func (ms *MockServer) deleteWebHook(w http.ResponseWriter, r *http.Request) {
_, ok := ms.webhooks.Webhooks[chi.URLParam(r, "webhook")]
if !ok {
w.WriteHeader(http.StatusNotFound)
toJSON(w, okResp{Message: "webhook not found"})
}
delete(ms.webhooks.Webhooks, chi.URLParam(r, "webhook"))
toJSON(w, okResp{Message: "success"})
}