/
register_handler.go
54 lines (42 loc) · 1.14 KB
/
register_handler.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
package main
import (
"encoding/json"
"net/http"
gonanoid "github.com/matoous/go-nanoid/v2"
)
const defaultIdLen = 7
type webhookRegisterRequest struct {
Url string `json:"url" validate:"required,url"`
Token string `json:"token" validate:"required"`
}
type WebhookRegisterHandler struct {
webhooks webhookLocalStorage
}
func (h WebhookRegisterHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch r.Method {
case http.MethodPost:
var whData webhookRegisterRequest
if err := validateRequest(r.Body, &whData); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
id := generateNanoId()
wh := webhook{
Id: id,
Url: whData.Url,
Token: whData.Token,
}
// Persist webhook inside the map.
h.webhooks[id] = wh
// Return webhook data as JSON with webhook ID in place.
json.NewEncoder(w).Encode(wh)
default:
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
}
}
// generateNanoId generates alphanumeric string with defined length.
func generateNanoId() string {
id, _ := gonanoid.New(defaultIdLen)
return id
}