Update client to handle GET (no body) requests, multipart requests, and JSON requests
This commit is contained in:
parent
2a32a1b3ce
commit
58514f4c5f
@ -1,26 +1,51 @@
|
|||||||
package restclient
|
package restclient
|
||||||
|
|
||||||
import "net/http"
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"mime/multipart"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
// SendRequest sends an HTTP request to a URL and includes the specified headers and body
|
// SendRequest sends an HTTP request to a URL and includes the specified headers and body.
|
||||||
func SendRequest(url string, method string, headers map[string]string, body map[string]string) (http.Response, error) {
|
// A body can be nil for GET requests, a map[string]string for multipart/form-data requests,
|
||||||
// Create request
|
// or a struct for JSON requests
|
||||||
req, err := http.NewRequest(method, url, nil)
|
func SendRequest(url string, method string, headers map[string]string, body interface{}) (http.Response, error) {
|
||||||
|
var reqBody *bytes.Buffer
|
||||||
|
var contentType string
|
||||||
|
|
||||||
|
switch v := body.(type) {
|
||||||
|
case nil: // Leave nil for GET requests
|
||||||
|
case map[string]string:
|
||||||
|
reqBody = &bytes.Buffer{}
|
||||||
|
writer := multipart.NewWriter(reqBody)
|
||||||
|
for key, value := range v {
|
||||||
|
writer.WriteField(key, value)
|
||||||
|
}
|
||||||
|
writer.Close()
|
||||||
|
contentType = writer.FormDataContentType()
|
||||||
|
default:
|
||||||
|
jsonBody, err := json.Marshal(body)
|
||||||
|
if err != nil {
|
||||||
|
return http.Response{}, err
|
||||||
|
}
|
||||||
|
reqBody = bytes.NewBuffer(jsonBody)
|
||||||
|
contentType = "application/json"
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequest(method, url, reqBody)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return http.Response{}, err
|
return http.Response{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add headers
|
if contentType != "" {
|
||||||
|
req.Header.Set("Content-Type", contentType)
|
||||||
|
}
|
||||||
|
|
||||||
for key, value := range headers {
|
for key, value := range headers {
|
||||||
req.Header.Add(key, value)
|
req.Header.Add(key, value)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add body
|
|
||||||
for key, value := range body {
|
|
||||||
req.Form.Add(key, value)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send request
|
|
||||||
client := &http.Client{}
|
client := &http.Client{}
|
||||||
resp, err := client.Do(req)
|
resp, err := client.Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
Loading…
Reference in New Issue
Block a user