-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
381 lines (309 loc) · 9.26 KB
/
Copy pathmain.go
File metadata and controls
381 lines (309 loc) · 9.26 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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package main
import (
"database/sql"
"encoding/json"
"log"
"net/http"
"os"
"strings"
"sync/atomic"
"time"
"github.com/google/uuid"
"github.com/jasonicarter/bootdev-http-server/internal/auth"
"github.com/jasonicarter/bootdev-http-server/internal/database"
"github.com/joho/godotenv"
_ "github.com/lib/pq"
)
type apiConfig struct {
fileserverHits atomic.Int32
dbQueries *database.Queries
platform string
}
var bannedWords = map[string]bool{
"kerfuffle": true,
"sharbert": true,
"fornax": true,
}
func main() {
godotenv.Load()
dbURL := os.Getenv("DB_URL")
env := os.Getenv("PLATFORM")
db, err := sql.Open("postgres", dbURL)
if err != nil {
log.Printf("Error connecting to database: %v", err)
os.Exit(1)
}
apiCfg := apiConfig{
// fileserverHits: // The zero value is zero
dbQueries: database.New(db),
platform: env,
}
mux := http.NewServeMux()
mux.Handle("/app/",
apiCfg.middlewareMetricsInc(
http.StripPrefix("/app", http.FileServer(http.Dir("."))),
),
)
mux.HandleFunc("GET /admin/metrics", apiCfg.getMetrics)
mux.HandleFunc("POST /admin/reset", apiCfg.resetMetrics)
mux.HandleFunc("GET /api/healthz", handlerHealthz)
mux.HandleFunc("POST /api/chirps", apiCfg.handlerAddChirp)
mux.HandleFunc("GET /api/chirps", apiCfg.handlerGetChirps)
mux.HandleFunc("GET /api/chirps/{chirpID}", apiCfg.handlerGetChirpByID)
mux.HandleFunc("POST /api/users", apiCfg.handlerAddUsers)
mux.HandleFunc("POST /api/login", apiCfg.handlerUserLogin)
server := http.Server{
Addr: ":8080",
Handler: mux,
}
// Start things up and exist if it fails
err = server.ListenAndServe()
if err != nil {
log.Printf("Error starting up the server: %v", err)
os.Exit(1)
}
}
func replaceProfanity(msg string, bannedWords map[string]bool) string {
words := strings.Fields(msg)
for _, word := range words {
// check if word in msg is a key in bannedWords and return value with is boolean
if bannedWords[strings.ToLower(word)] {
msg = strings.ReplaceAll(msg, word, "****")
}
}
return msg
}
func respondWithError(w http.ResponseWriter, httpStatusCode int, msg string) {
errorResponse := struct {
Error string `json:"error"`
}{Error: msg}
respondWithJSON(w, httpStatusCode, errorResponse)
}
func respondWithJSON(w http.ResponseWriter, httpStatusCode int, payload any) {
data, err := json.Marshal(payload)
if err != nil {
log.Printf("Error marshalling JSON: %s", err)
w.WriteHeader(http.StatusInternalServerError)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"error": "Something went wrong"}`))
return
}
w.WriteHeader(httpStatusCode)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(data))
}
func handlerHealthz(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
func (cfg *apiConfig) handlerAddChirp(w http.ResponseWriter, req *http.Request) {
type parameters struct {
Body string `json:"body"`
UserID string `json:"user_id"`
}
// get json body into struct
decoder := json.NewDecoder(req.Body)
params := parameters{}
err := decoder.Decode(¶ms)
// handle error parsing parameters
if err != nil {
log.Printf("Error decoding parameters: %s", err)
respondWithError(w, http.StatusInternalServerError, "Something went wrong")
return
}
// handle chirpy - validate length and respond
// len() returns bytes not characters
chirpLength := len([]rune(params.Body))
// TODO: Consider moving this out into it's own func
if chirpLength > 140 {
errorResponse := struct {
Error string `json:"error"`
}{Error: "Chirp is too long"}
respondWithJSON(w, http.StatusOK, errorResponse)
return
}
if chirpLength <= 140 {
chirpCleaned := replaceProfanity(params.Body, bannedWords)
user_id, err := uuid.Parse(params.UserID)
if err != nil {
log.Printf("Error decoding parameters: %s", err)
respondWithError(w, http.StatusInternalServerError, "Something went wrong")
}
newChirp := database.CreateChirpParams{
Body: chirpCleaned,
UserID: user_id,
}
// Save chirp in database
createdChirp, err := cfg.dbQueries.CreateChirp(req.Context(), newChirp)
if err != nil {
log.Printf("Error creating new chirp: %s", err)
respondWithError(w, http.StatusInternalServerError, "Something went wrong")
return
}
// Respond
type JSONResponse struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Body string `json:"body"`
UserID uuid.UUID `json:"user_id"`
}
reqResponse := JSONResponse{
ID: createdChirp.ID,
CreatedAt: createdChirp.CreatedAt,
UpdatedAt: createdChirp.UpdatedAt,
Body: createdChirp.Body,
UserID: createdChirp.UserID,
}
respondWithJSON(w, http.StatusCreated, reqResponse)
return
}
}
func (cfg *apiConfig) handlerAddUsers(w http.ResponseWriter, req *http.Request) {
type parameters struct {
Email string `json:"email"`
Password string `json:"password"`
}
decoder := json.NewDecoder(req.Body)
params := parameters{}
err := decoder.Decode(¶ms)
if err != nil {
log.Printf("Error decoding parameters: %s", err)
respondWithError(w, http.StatusInternalServerError, "Something went wrong")
return
}
hashedPassword, err := auth.HashPassword(params.Password)
if err != nil {
log.Printf("Error hashing password: %v", err)
respondWithError(w, http.StatusInternalServerError, "Something went wrong")
}
newUser := database.CreateUserParams{
Email: params.Email,
HashedPassword: hashedPassword,
}
// create user
user, err := cfg.dbQueries.CreateUser(req.Context(), newUser)
if err != nil {
log.Printf("Error creating user: %v", err)
respondWithError(w, http.StatusInternalServerError, "Something went wrong")
}
// User struct allows for better control on the keys which database.user defaults
type User struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Email string `json:"email"`
}
userCreated := User{
ID: user.ID,
CreatedAt: user.CreatedAt,
UpdatedAt: user.UpdatedAt,
Email: user.Email,
}
respondWithJSON(w, http.StatusCreated, userCreated)
}
func (cfg *apiConfig) handlerGetChirps(w http.ResponseWriter, req *http.Request) {
// Get chirps
chirps, err := cfg.dbQueries.AllChirps(req.Context())
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Something went wrong")
return
}
// Respond
type JSONResponse struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Body string `json:"body"`
UserID uuid.UUID `json:"user_id"`
}
var allChirps = []JSONResponse{}
for _, c := range chirps {
//add c variables into struct variable
//append c to struct variable
chirp := JSONResponse{
ID: c.ID,
CreatedAt: c.CreatedAt,
UpdatedAt: c.UpdatedAt,
Body: c.Body,
UserID: c.UserID,
}
allChirps = append(allChirps, chirp)
}
respondWithJSON(w, http.StatusOK, allChirps)
}
func (cfg *apiConfig) handlerGetChirpByID(w http.ResponseWriter, req *http.Request) {
chirpId := req.PathValue("chirpID")
if len(chirpId) == 0 {
//TODO: respond with error
return
}
log.Printf("%v", chirpId)
id, err := uuid.Parse(chirpId)
if err != nil {
//TODO: respond with error
return
}
chirp, err := cfg.dbQueries.GetChirpByID(req.Context(), id)
if err != nil {
log.Printf("%v", err)
respondWithError(w, http.StatusInternalServerError, "Something went wrong")
return
}
// Respond
type JSONResponse struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Body string `json:"body"`
UserID uuid.UUID `json:"user_id"`
}
chirpByID := JSONResponse{
ID: chirp.ID,
CreatedAt: chirp.CreatedAt,
UpdatedAt: chirp.UpdatedAt,
Body: chirp.Body,
UserID: chirp.ID,
}
respondWithJSON(w, http.StatusOK, chirpByID)
}
func (cfg *apiConfig) handlerUserLogin(w http.ResponseWriter, req *http.Request) {
// TODO: Maybe consolidate this in one place instead of multiple
type parameters struct {
Email string `json:"email"`
Password string `json:"password"`
}
decoder := json.NewDecoder(req.Body)
params := parameters{}
err := decoder.Decode(¶ms)
if err != nil {
log.Printf("Error decoding parameters: %s", err)
respondWithError(w, http.StatusInternalServerError, "Something went wrong")
return
}
// new query to create
user, err := cfg.dbQueries.LoginUser(req.Context(), params.Email)
if err != nil {
log.Printf("Error decoding parameters: %s", err)
respondWithError(w, http.StatusInternalServerError, "Something went wrong")
return
}
if auth.CheckPasswordHash(params.Password, user.HashedPassword) != nil {
respondWithError(w, http.StatusUnauthorized, "Incorrect email or password")
return
}
type JSONResponse struct {
ID uuid.UUID `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Email string `json:"email"`
}
loggedInUser := JSONResponse{
ID: user.ID,
CreatedAt: user.CreatedAt,
UpdatedAt: user.UpdatedAt,
Email: user.Email,
}
respondWithJSON(w, http.StatusOK, loggedInUser)
}