forked from bootdotdev/learn-file-storage-s3-golang-starter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_upload_thumbnail.go
84 lines (69 loc) · 2.12 KB
/
handler_upload_thumbnail.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
package main
import (
"fmt"
"io"
"net/http"
"github.com/bootdotdev/learn-file-storage-s3-golang-starter/internal/auth"
"github.com/google/uuid"
)
func (cfg *apiConfig) handlerUploadThumbnail(w http.ResponseWriter, r *http.Request) {
videoIDString := r.PathValue("videoID")
videoID, err := uuid.Parse(videoIDString)
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid ID", err)
return
}
token, err := auth.GetBearerToken(r.Header)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't find JWT", err)
return
}
userID, err := auth.ValidateJWT(token, cfg.jwtSecret)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Couldn't validate JWT", err)
return
}
fmt.Println("uploading thumbnail for video", videoID, "by user", userID)
const maxMemory = 10 << 20
if err = r.ParseMultipartForm(maxMemory); err != nil {
respondWithError(w, http.StatusBadRequest, "Couldn't parse multipart form", err)
return
}
file, header, err := r.FormFile("thumbnail")
if err != nil {
respondWithError(w, http.StatusBadRequest, "Unable to parse form file", err)
return
}
defer file.Close()
mediaType := header.Header.Get("Content-Type")
if mediaType == "" {
respondWithError(w, http.StatusBadRequest, "Missing Content-Type for thumbnail", nil)
return
}
data, err := io.ReadAll(file)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't read file", err)
return
}
video, err := cfg.db.GetVideo(videoID)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't get video", err)
return
}
if video.UserID != userID {
respondWithError(w, http.StatusUnauthorized, "Not authorized to update this video", nil)
return
}
videoThumbnails[videoID] = thumbnail{
data: data,
mediaType: mediaType,
}
url := fmt.Sprintf("localhost:%s/api/thumbnails/%s", cfg.port, videoID)
video.ThumbnailURL = &url
if err = cfg.db.UpdateVideo(video); err != nil {
delete(videoThumbnails, videoID)
respondWithError(w, http.StatusInternalServerError, "Couldn't update video", err)
return
}
respondWithJSON(w, http.StatusOK, video)
}