-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebhook.go
55 lines (43 loc) · 1019 Bytes
/
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
package api
import (
"encoding/json"
"io"
"net/http"
"slices"
"starter/internal/database"
"strings"
)
const eventUserUpgraded = "user.upgraded"
type whBody struct {
Event string `json:"event"`
Data struct {
UserId int `json:"user_id"`
} `json:"data"`
}
func (c *ApiConfig) WebhookHandler(w http.ResponseWriter, r *http.Request) {
apiKey := strings.ReplaceAll(strings.TrimSpace(r.Header.Get("Authorization")), "ApiKey ", "")
if apiKey != c.PolkaApiKey {
respondWithJSON(w, 401, "unauthorized")
return
}
body, _ := io.ReadAll(r.Body)
var wh whBody
json.Unmarshal(body, &wh)
if wh.Event != eventUserUpgraded {
respondWithJSON(w, 204, nil)
return
}
userId := wh.Data.UserId
users := database.GetUsers()
index := slices.IndexFunc(users, func(user database.User) bool {
return user.Id == userId
})
if index == -1 {
respondWithJSON(w, 404, "user not found")
return
}
user := &users[index]
user.IsChirpyRed = true
database.SaveUsers(users)
respondWithJSON(w, 204, nil)
}