To handle and process multipart/form-data submissions from HTML forms in Go, you can use the multipart
package from the standard library. Follow these steps:
import (
"mime/multipart"
"net/http"
)
func handleSubmit(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
r.ParseMultipartForm(32 << 20) // Set the maximum request size to 32MB
}
r.FormValue()
or r.PostFormValue()
. For example, to retrieve the value of an input field with a name attribute of "name":func handleSubmit(w http.ResponseWriter, r *http.Request) {
// ...
name := r.FormValue("name")
// process the value of the "name" field
}
r.FormFile()
. This function returns a multipart.File
and a multipart.FileHeader
. Read the file using the Read()
method, and process it as needed. Make sure to close the file when finished using it:func handleSubmit(w http.ResponseWriter, r *http.Request) {
// ...
file, header, err := r.FormFile("file")
if err != nil {
// handle the error
}
defer file.Close()
// process the file
// e.g., save it to disk, extract metadata, etc.
}
That's it! You can now handle and process multipart/form-data submissions from HTML forms in Go.