-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers_webhook.go
43 lines (40 loc) · 1018 Bytes
/
handlers_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
package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
)
func (apiConfig *apiConfig) handleWebhook(w http.ResponseWriter, req *http.Request) {
apiString := req.Header.Get("Authorization")
apiKey, canCut := strings.CutPrefix(apiString, "ApiKey ")
fmt.Println(apiKey)
if !canCut || apiKey != apiConfig.apiKey {
respondWithError(w, http.StatusUnauthorized, "Unauthorized request")
return
}
type parameter struct {
Event string `json:"event"`
Data struct {
UserID int `json:"user_id"`
} `json:"data"`
}
decoder := json.NewDecoder(req.Body)
param := parameter{}
err := decoder.Decode(¶m)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Malformed request")
return
}
if param.Event == "user.upgraded" {
user, err := apiConfig.DB.UpdateWebhook(param.Data.UserID)
if err != nil {
respondWithError(w, http.StatusNotFound, "User not found")
return
}
respondWithJSON(w, http.StatusOK, user)
return
}
respondWithJSON(w, http.StatusOK, "")
return
}