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))
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?