Skip to content

Instantly share code, notes, and snippets.

@thrawn01
Created September 18, 2023 16:14
Show Gist options
  • Save thrawn01/6ff075ea3bd88ec2785fb831d03bdad0 to your computer and use it in GitHub Desktop.
Save thrawn01/6ff075ea3bd88ec2785fb831d03bdad0 to your computer and use it in GitHub Desktop.
HTTP gzip multipart form data client
package main
import (
"bytes"
"compress/gzip"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"strings"
)
func main() {
// URL and credentials
url := "https://api.mailgun.net/v3/%s/messages"
username := "api"
password := "<snip>"
domain := "example.com"
to := "[email protected]"
// Create a buffer to write our multipart form
var formBuffer bytes.Buffer
formWriter := multipart.NewWriter(&formBuffer)
// Add form fields
if err := formWriter.WriteField("from", fmt.Sprintf("Your Mom <root@%s>", domain)); err != nil {
log.Fatal(err)
}
if err := formWriter.WriteField("to", fmt.Sprintf("admin@%s", domain)); err != nil {
log.Fatal(err)
}
if err := formWriter.WriteField("to", to); err != nil {
log.Fatal(err)
}
if err := formWriter.WriteField("subject", "My emotional state"); err != nil {
log.Fatal(err)
}
if err := formWriter.WriteField("text", "I like people like I like my tea, in a bag and underwater"); err != nil {
log.Fatal(err)
}
// Close the multipart writer
if err := formWriter.Close(); err != nil {
log.Fatal(err)
}
// Gzip compress the form data
var gzipBuffer bytes.Buffer
gzipWriter := gzip.NewWriter(&gzipBuffer)
if _, err := gzipWriter.Write(formBuffer.Bytes()); err != nil {
log.Fatal(err)
}
if err := gzipWriter.Close(); err != nil {
log.Fatal(err)
}
// Create the HTTP request
req, err := http.NewRequest("POST", fmt.Sprintf(url, domain), &gzipBuffer)
if err != nil {
log.Fatal(err)
}
// Set headers and basic authentication
req.Header.Set("Content-Type", formWriter.FormDataContentType())
req.Header.Set("Content-Encoding", "gzip")
req.Header.Set("Accept-Encoding", "gzip")
req.SetBasicAuth(username, password)
// Create HTTP client and execute the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// Read and print the response
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
log.Println("Response:", strings.TrimSpace(string(body)))
}
Response: {"message":"malformed multipart/form-data request"}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment