-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchirp.go
205 lines (182 loc) · 4.93 KB
/
chirp.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"github.com/erwaen/Chirpy/auth"
"github.com/erwaen/Chirpy/database"
)
type returnError struct {
Error string `json:"error"`
}
type returnValid struct {
Id int `json:"id"`
Body string `json:"body"`
}
func respondWithError(w http.ResponseWriter, code int, msg string) {
log.Printf(msg)
error := returnError{
Error: msg,
}
respondWithJson(w, code, error)
}
func respondWithJson(w http.ResponseWriter, code int, payload interface{}) {
data, err := json.Marshal(payload)
if err != nil {
log.Printf("Error marshalling JSON: %s", err)
w.WriteHeader(500)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(data)
}
func respondWithoutJson(w http.ResponseWriter, code int) {
w.WriteHeader(code)
}
func (cfg *apiConfig) handlerReadChirps(w http.ResponseWriter, r *http.Request) {
idString := r.PathValue("id")
if idString != "" {
id, err := strconv.Atoi(idString)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid ID parameter")
return
}
chirp, err := cfg.db.GetChirp(id)
if err != nil {
if err == database.ErrNotExist {
respondWithError(w, http.StatusNotFound, "Chirp Not found")
} else {
respondWithError(w, http.StatusInternalServerError, fmt.Sprintf("error retrieving chirp: %s", err))
}
return
}
respondWithJson(w, http.StatusOK, chirp)
return
}
s := r.URL.Query().Get("author_id")
sort := r.URL.Query().Get("sort")
authorID, err := strconv.Atoi(s)
if err != nil {
authorID = 0
}
chirps, err := cfg.db.GetChirps(authorID, sort)
if err != nil {
respondWithError(w, http.StatusInternalServerError, fmt.Sprintf("Error getting chirps: %s", err))
return
}
respondWithJson(w, 200, chirps)
}
func (cfg *apiConfig) handlerDeleteChirp(w http.ResponseWriter, r *http.Request) {
token, err := auth.GetBearerToken(r.Header)
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.StatusInternalServerError, "Couldn't parse user ID")
return
}
idString := r.PathValue("id")
chirpID, err := strconv.Atoi(idString)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid ID parameter")
return
}
chirp, err := cfg.db.GetChirp(chirpID)
if err != nil {
if err == database.ErrNotExist {
respondWithError(w, http.StatusNotFound, "Chirp Not found")
} else {
respondWithError(w, http.StatusInternalServerError, "Couldn't get the chirp")
}
return
}
if chirp.AuthorID != userID {
respondWithError(w, http.StatusForbidden, "You are not allowed to delete this chirp")
return
}
_, err = cfg.db.DeleteChirp(chirpID)
if err != nil {
if err == database.ErrNotExist {
respondWithError(w, http.StatusNotFound, "Chirp Not found when trying to delete")
} else {
respondWithError(w, http.StatusInternalServerError, "Couldn't delete the chirp")
}
}
respondWithoutJson(w, http.StatusNoContent)
}
func (cfg *apiConfig) handlerNewChirp(w http.ResponseWriter, r *http.Request) {
type parameters struct {
Body string `json:"body"`
}
type response struct {
ID int `json:"id"`
Body string `json:"body"`
AuthorID int `json:"author_id"`
}
token, err := auth.GetBearerToken(r.Header)
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.StatusInternalServerError, "Couldn't parse user ID")
return
}
decoder := json.NewDecoder(r.Body)
params := parameters{}
err = decoder.Decode(¶ms)
if err != nil {
respondWithError(w, 500, "Couldn't decode parameters")
return
}
cleaned, err := validateChirp(params.Body)
if err != nil {
respondWithError(w, http.StatusBadRequest, err.Error())
return
}
// Save the chirp to the database
newChirp, err := cfg.db.CreateChirp(cleaned, userID)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't create chirp")
return
}
respondWithJson(w, http.StatusCreated, response{
ID: newChirp.Id,
Body: newChirp.Body,
AuthorID: newChirp.AuthorID,
})
}
func validateChirp(body string) (string, error) {
const maxChirpLength = 140
if len(body) > maxChirpLength {
return "", errors.New("Chirp is too long")
}
BLACK_WORDS := map[string]struct{}{
"kerfuffle": {},
"sharbert": {},
"fornax": {},
}
cleaned := getCleanedBody(body, BLACK_WORDS)
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
}