// Parse a multipart request from r func parseMultipartRequest(r io.Reader) error { // Create a new MultipartReader mr, err := multipart.NewReader(r, boundary) if err != nil { return err } // Loop through each part of the message for { part, err := mr.NextPart() if err == io.EOF { break } if err != nil { return err } // Handle the part content contentType := part.Header.Get("Content-Type") switch contentType { case "text/plain": // Handle plain text part case "image/png": // Handle image part default: // Handle unknown part } } return nil }
// Send a multipart request to a server func sendMultipartRequest() error { // Create a new multipart message body := &bytes.Buffer{} writer := multipart.NewWriter(body) // Add a plain text part part, _ := writer.CreatePart(textproto.MIMEHeader{}) part.Write([]byte("Hello, world!")) // Add an image part part, _ = writer.CreateFormFile("image", "image.png") file, _ := os.Open("image.png") defer file.Close() io.Copy(part, file) // Close the multipart message writer.Close() // Create a new request req, _ := http.NewRequest("POST", "http://example.com/upload", body) req.Header.Set("Content-Type", writer.FormDataContentType()) // Send the request and read the response client := &http.Client{} resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() // Do something with the response return nil }This example shows how to create and send a multipart request using the `MultipartWriter` and `http.NewRequest` functions. The `MultipartWriter` is used to create a multipart message with both a plain text and image part. The `FormDataContentType()` method is used to set the `Content-Type` header of the request to the appropriate value for a multipart request. The `http.NewRequest` function is used to create a new request with the body of the multipart message. The `http.Client` is used to send the request, and the response is read and processed.