How to Handle File Uploads in a Go HTTP Server

Web
Handle file uploads in Go by parsing multipart forms with ParseMultipartForm and saving the file stream using FormFile.

Use http.Request.ParseMultipartForm to parse the incoming request and access the uploaded file via r.FormFile.

func uploadHandler(w http.ResponseWriter, r *http.Request) {
    r.ParseMultipartForm(32 << 20) // 32 MB max memory
    file, handler, err := r.FormFile("file")
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }
    defer file.Close()
    // Save file to disk or process stream
    dst, _ := os.Create("/tmp/" + handler.Filename)
    io.Copy(dst, file)
}

Ensure your HTML form has enctype="multipart/form-data" and an input named file.