-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler_chirps_create.go
More file actions
98 lines (82 loc) · 2.17 KB
/
Copy pathhandler_chirps_create.go
File metadata and controls
98 lines (82 loc) · 2.17 KB
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
96
97
98
package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
"time"
"github.com/darginmathi/Chirpy/internal/auth"
"github.com/darginmathi/Chirpy/internal/database"
"github.com/google/uuid"
)
type Chirp struct {
ID uuid.UUID `json:"id"`
Body string `json:"body"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
UserID uuid.UUID `json:"user_id"`
}
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, "Couldnt get authorization token", err)
return
}
userID, err := auth.ValidateJWT(token, cfg.jwt_secret)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Unauthorized", err)
return
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err = decoder.Decode(¶ms)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't decode parameters", err)
return
}
cleaned, err := validateChirp(params.Body)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Chirp too long", err)
return
}
chirp, err := cfg.db.CreateChirp(r.Context(), database.CreateChirpParams{
Body: cleaned,
UserID: userID,
})
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't create chirp", err)
return
}
respondWithJSON(w, http.StatusCreated, Chirp{
ID: chirp.ID,
CreatedAt: chirp.CreatedAt,
UpdatedAt: chirp.UpdatedAt,
Body: chirp.Body,
UserID: chirp.UserID,
})
}
func validateChirp(chirp string) (string, error) {
const maxChirpLength = 140
if len(chirp) > maxChirpLength {
return chirp, fmt.Errorf("chirp too long")
}
badWords := map[string]struct{}{
"kerfuffle": {},
"sharbert": {},
"fornax": {},
}
return getCleanBody(chirp, badWords), nil
}
func getCleanBody(body string, badWords map[string]struct{}) string {
words := strings.Split(body, " ")
for i, word := range words {
lowerWord := strings.ToLower(word)
if _, ok := badWords[lowerWord]; ok {
words[i] = "****"
}
}
return strings.Join(words, " ")
}