-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpolka.go
52 lines (46 loc) · 1.13 KB
/
polka.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
package main
import (
"chirpy/internal/auth"
"chirpy/internal/database"
"encoding/json"
"errors"
"net/http"
)
func (cfg *apiConfig) handlePolkaWebhook(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Event string `json:"event"`
Data struct {
UserId int `json:"user_id"`
} `json:"data"`
}
type response struct{}
apiKey, err := auth.GetApiKey(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't find ApiKey")
return
}
if apiKey != cfg.polkaKey {
respondWithError(w, http.StatusUnauthorized, "Invalid ApiKey")
return
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err = decoder.Decode(¶ms)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters")
return
}
switch params.Event {
case "user.upgraded":
_, err = cfg.DB.UpgradeUser(params.Data.UserId)
if errors.Is(err, database.ErrNotExist) {
respondWithError(w, http.StatusNotFound, "User doesn't exist")
return
}
respondWithJSON(w, http.StatusOK, response{})
return
default:
respondWithJSON(w, http.StatusOK, response{})
return
}
}