-
Notifications
You must be signed in to change notification settings - Fork 0
/
handle_chirps_create.go
95 lines (80 loc) · 2.03 KB
/
handle_chirps_create.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
package main
import (
"encoding/json"
"errors"
"net/http"
"strconv"
"strings"
"github.com/ClemSK/chirpy/internal/auth"
)
type Chirp struct {
ID int `json:"id"`
AuthorID int `json:"author_id"`
Body string `json:"body"`
}
func (cfg *apiConfig) handlerChirpsCreate(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Body string `json:"body"`
}
token, err := auth.GetBearerToken(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't find JWT")
return
}
subject, err := auth.ValidateJWT(token, cfg.jwtSecret)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't validate JWT")
return
}
userID, err := strconv.Atoi(subject)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Couldn't parse user ID")
return
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err = decoder.Decode(¶ms)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Could not decode parameter")
return
}
cleaned, err := validateChirp(params.Body)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
chirp, err := cfg.DB.CreateChirp(cleaned, userID)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Could not create chirp")
return
}
respondWithJSON(w, http.StatusCreated, Chirp{
AuthorID: chirp.AuthorID,
Body: chirp.Body,
ID: chirp.ID,
})
}
func validateChirp(body string) (string, error) {
const maxChirpLength = 150
if len(body) > maxChirpLength {
return "", errors.New("Chirp is too long")
}
badWords := map[string]struct{}{
"kerfuffle": {},
"sharbert": {},
"fornax": {},
}
cleaned := getCleanedBody(body, badWords)
return cleaned, nil
}
func getCleanedBody(body string, badWords map[string]struct{}) string {
words := strings.Split(body, " ")
for i, word := range words {
loweredWord := strings.ToLower(word)
if _, ok := badWords[loweredWord]; ok {
words[i] = "****"
}
}
cleaned := strings.Join(words, " ")
return cleaned
}