Let's work with some files already!
So you might already be familiar with simple JSON/HTML form POST requests. That works great for small structured data (small strings, integers, etc.), but what about large files?
We don't typically send massive files as single JSON payloads or forms. Instead, we use a different encoding format called multipart/form-data. In a nutshell, it's a way to send multiple pieces of data in a single request and is commonly used for file uploads. It's the "default" way to send files to a server from an HTML form.
Luckily, the Go standard library's net/http package has built-in support for parsing multipart/form-data requests. The http.Request struct has a method called ParseMultipartForm.
func (cfg *apiConfig) handlerUploadThumbnail(w http.ResponseWriter, r *http.Request) {
// validate the request
const maxMemory = 10 << 20
r.ParseMultipartForm(maxMemory)
// "thumbnail" should match the HTML form input name
file, header, err := r.FormFile("thumbnail")
if err != nil {
respondWithError(w, http.StatusBadRequest, "Unable to parse form file", err)
return
}
defer file.Close()
// `file` is an `io.Reader` that we can read from to get the image data
The handler for uploading thumbnails is currently a no-op. Let's get it working. We're going to keep it simple and store all image data in-memory.
main.go there is a global map of video IDs to thumbnail structs called videoThumbnails. This is where we're going to store the thumbnail data.handlerThumbnailGet function. It serves the thumbnail file back to the UI, but it assumes that images exist in the videoThumbnails map (which they don't yet!)Complete the handlerUploadThumbnail function. It handles a multipart form upload of a thumbnail image and stores it in the videoThumbnails map:
Bit shifting is a way to multiply by powers of 2. 10 << 20 is the same as 10 * 1024 * 1024, which is 10MB.
http.StatusUnauthorized responsehttp://localhost:<port>/api/thumbnails/{videoID}
This will all work because the /api/thumbnails/{videoID} endpoint serves thumbnails from that global map.
Run and submit the CLI tests.
If you try to upload a different image, the browser might cache and show the old one. We'll deal with that later.