How do I handle multipart forms and large uploads?

In Go, handling multipart forms and large file uploads is straightforward with the standard library. The `http` package provides built-in functionality to process file uploads with ease. When dealing with large uploads, it's important to carefully manage memory and handle potential errors gracefully.

Here’s an example that demonstrates how to handle multipart file uploads in Go:

package main import ( "net/http" "fmt" "log" ) func uploadFile(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodPost { // Parse the multipart form err := r.ParseMultipartForm(10 << 20) // Limit your file size to 10 MB if err != nil { http.Error(w, "Unable to parse form", http.StatusBadRequest) return } // Retrieve the file from the form file, _, err := r.FormFile("file") if err != nil { http.Error(w, "Unable to retrieve file", http.StatusBadRequest) return } defer file.Close() // Process the file (e.g., save it to disk or handle it) // For demonstration, we're just going to log the file size fmt.Fprintf(w, "Uploaded file successfully! Size: %v bytes", r.ContentLength) } else { http.ServeFile(w, r, "upload.html") // Serve an upload form } } func main() { http.HandleFunc("/upload", uploadFile) log.Println("Server starting at :8080...") log.Fatal(http.ListenAndServe(":8080", nil)) }

keywords: Go multipart forms file uploads large file handling Go web server HTTP file upload