forked from mailgun/mailgun-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock_webhooks.go
98 lines (79 loc) · 2.35 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package mailgun
import (
"net/http"
"github.com/gorilla/mux"
)
func (ms *mockServer) addWebhookRoutes(r *mux.Router) {
sr := r.PathPrefix("/domains/{domain}/webhooks").Subrouter()
sr.HandleFunc("", ms.listWebHooks).Methods(http.MethodGet)
sr.HandleFunc("", ms.postWebHook).Methods(http.MethodPost)
sr.HandleFunc("/{webhook}", ms.getWebHook).Methods(http.MethodGet)
sr.HandleFunc("/{webhook}", ms.putWebHook).Methods(http.MethodPut)
sr.HandleFunc("/{webhook}", ms.deleteWebHook).Methods(http.MethodDelete)
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) {
defer ms.mutex.Unlock()
ms.mutex.Lock()
toJSON(w, ms.webhooks)
}
func (ms *mockServer) getWebHook(w http.ResponseWriter, r *http.Request) {
defer ms.mutex.Unlock()
ms.mutex.Lock()
resp := WebHookResponse{
Webhook: UrlOrUrls{
Urls: ms.webhooks.Webhooks[mux.Vars(r)["webhook"]].Urls,
},
}
toJSON(w, resp)
}
func (ms *mockServer) postWebHook(w http.ResponseWriter, r *http.Request) {
defer ms.mutex.Unlock()
ms.mutex.Lock()
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) {
defer ms.mutex.Unlock()
ms.mutex.Lock()
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[mux.Vars(r)["webhook"]] = UrlOrUrls{Urls: urls}
toJSON(w, okResp{Message: "success"})
}
func (ms *mockServer) deleteWebHook(w http.ResponseWriter, r *http.Request) {
defer ms.mutex.Unlock()
ms.mutex.Lock()
_, ok := ms.webhooks.Webhooks[mux.Vars(r)["webhook"]]
if !ok {
w.WriteHeader(http.StatusNotFound)
toJSON(w, okResp{Message: "webhook not found"})
}
delete(ms.webhooks.Webhooks, mux.Vars(r)["webhook"])
toJSON(w, okResp{Message: "success"})
}