func handleUpload(w http.ResponseWriter, r *http.Request) { contentType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type")) if err != nil || !strings.HasPrefix(contentType, "multipart/") { http.Error(w, "Expected multipart/form-data", http.StatusBadRequest) return } mr := multipart.NewReader(r.Body, params["boundary"]) for { part, err := mr.NextPart() if err == io.EOF { break } if err != nil { log.Fatal(err) } fileName := part.FileName() log.Printf("Received file %s", fileName) // ... } }
buf := new(bytes.Buffer) w := multipart.NewWriter(buf) part, _ := w.CreateFormFile("file", fileName) _, _ = io.Copy(part, file) w.Close() resp.Body = ioutil.NopCloser(buf) resp.Header.Set("Content-Type", w.FormDataContentType())In this example, we use the mime.multipart package to build a multipart response containing a single file part. We set the filename of the part using the CreateFormFile() method and the fileName variable. Overall, the go mime.multipart package provides a convenient way to handle multipart requests and responses in HTTP, including the ability to work with file uploads and downloads.