-
Notifications
You must be signed in to change notification settings - Fork 0
/
deleteChirps.go
52 lines (42 loc) · 1.17 KB
/
deleteChirps.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 (
"log"
"net/http"
"strconv"
"github.com/adamhu714/chirpy/internal/database"
)
func (cfg *apiConfig) handlerDeleteChirpsId(w http.ResponseWriter, r *http.Request) {
authorId, err := cfg.GetIDFromAccessToken(w, r)
if err != nil {
log.Printf("handlerDeleteChirpsId - Error getting id from token: %s", err.Error())
return
}
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
log.Printf("handlerDeleteChirpsId: Error while converting id")
}
// connect database
db, err := database.NewDB("database.json")
if err != nil {
log.Printf("handlerDeleteChirpsId: Error connecting database: %s", err.Error())
w.WriteHeader(http.StatusInternalServerError)
return
}
chirps, err := db.GetChirps()
if err != nil {
log.Printf("handlerDeleteChirpsId: Error getting chirps")
return
}
if id < 1 || id > len(chirps) {
log.Printf("handlerDeleteChirpsId: invalid chirp id provided")
w.WriteHeader(http.StatusBadRequest)
return
}
if chirps[id-1].AuthorId != authorId {
log.Printf("handlerDeleteChirpsId: wrong user attempting to delete chirp")
w.WriteHeader(http.StatusForbidden)
return
}
db.DeleteChirp(id)
w.WriteHeader(http.StatusOK)
}