make a http request with a custom body as form data in go

main.go
package main

import (
    "bytes"
    "mime/multipart"
    "net/http"
)

func makeHttpPostRequestWithFormData(url string, data map[string]string) (*http.Response, error) {
    requestBody := new(bytes.Buffer)
    writer := multipart.NewWriter(requestBody)
    for key, value := range data {
        _ = writer.WriteField(key, value)
    }
    err := writer.Close()
    if err != nil {
        return nil, err
    }
    client := &http.Client{}
    req, err := http.NewRequest("POST", url, requestBody)
    if err != nil {
        return nil, err
    }
    req.Header.Add("Content-Type", writer.FormDataContentType())
    resp, err := client.Do(req)
    if err != nil {
        return nil, err
    }
    return resp, nil
}
723 chars
31 lines

This is a simple function that takes url as string and data as a map of string key-value pairs to be sent as form data in the request. It returns the http Response object and an error, if any. It uses the "mime/multipart" package in Go to create form data from the received map data, and the http.Client to make the Http request.

gistlibby LogSnag