How to handle and process multipart/form-data submissions from HTML forms in Go?

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:

  1. Import the necessary packages:
import ( "mime/multipart" "net/http" )
  1. In your HTTP handler, check the request method to ensure it's a POST request, and set the appropriate maximum request size and parsing limits:
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 }
  1. Access the multipart/form-data form fields using 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 }
  1. Access the uploaded files using 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.