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
86 lines (73 loc) · 2.2 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
85
86
package main
import (
"io"
"mime"
"net/http"
"os"
"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
}
const maxMemory = 10 << 20 // 10 MB
r.ParseMultipartForm(maxMemory)
file, header, err := r.FormFile("thumbnail")
if err != nil {
respondWithError(w, http.StatusBadRequest, "Unable to parse form file", err)
return
}
defer file.Close()
mediaType, _, err := mime.ParseMediaType(header.Header.Get("Content-Type"))
if err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid Content-Type", err)
return
}
if mediaType != "image/jpeg" && mediaType != "image/png" {
respondWithError(w, http.StatusBadRequest, "Invalid file type", nil)
return
}
assetPath := getAssetPath(mediaType)
assetDiskPath := cfg.getAssetDiskPath(assetPath)
dst, err := os.Create(assetDiskPath)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Unable to create file on server", err)
return
}
defer dst.Close()
if _, err = io.Copy(dst, file); err != nil {
respondWithError(w, http.StatusInternalServerError, "Error saving file", err)
return
}
video, err := cfg.db.GetVideo(videoID)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't find video", err)
return
}
if video.UserID != userID {
respondWithError(w, http.StatusUnauthorized, "Not authorized to update this video", nil)
return
}
url := cfg.getAssetURL(assetPath)
video.ThumbnailURL = &url
err = cfg.db.UpdateVideo(video)
if err != nil {
respondWithError(w, http.StatusInternalServerError, "Couldn't update video", err)
return
}
respondWithJSON(w, http.StatusOK, video)
}