2024-07-02 02:19:48 +00:00
|
|
|
package rest
|
2023-07-21 21:35:18 +00:00
|
|
|
|
2023-07-25 20:34:11 +00:00
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"mime/multipart"
|
|
|
|
"net/http"
|
|
|
|
)
|
2023-07-21 21:35:18 +00:00
|
|
|
|
2023-07-25 20:34:11 +00:00
|
|
|
// SendRequest sends an HTTP request to a URL and includes the specified headers and body.
|
|
|
|
// A body can be nil for GET requests, a map[string]string for multipart/form-data requests,
|
|
|
|
// or a struct for JSON requests
|
|
|
|
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) {
|
2023-07-26 18:09:01 +00:00
|
|
|
case nil:
|
|
|
|
reqBody = bytes.NewBuffer([]byte(""))
|
2023-07-25 20:34:11 +00:00
|
|
|
case map[string]string:
|
|
|
|
reqBody = &bytes.Buffer{}
|
|
|
|
writer := multipart.NewWriter(reqBody)
|
|
|
|
for key, value := range v {
|
2023-08-03 17:13:15 +00:00
|
|
|
err := writer.WriteField(key, value)
|
|
|
|
if err != nil {
|
|
|
|
return http.Response{}, err
|
|
|
|
}
|
2023-07-25 20:34:11 +00:00
|
|
|
}
|
2023-08-03 17:13:15 +00:00
|
|
|
|
|
|
|
err := writer.Close()
|
|
|
|
if err != nil {
|
|
|
|
return http.Response{}, err
|
|
|
|
}
|
|
|
|
|
2023-07-25 20:34:11 +00:00
|
|
|
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)
|
2023-07-21 21:35:18 +00:00
|
|
|
if err != nil {
|
|
|
|
return http.Response{}, err
|
|
|
|
}
|
|
|
|
|
2023-07-25 20:34:11 +00:00
|
|
|
if contentType != "" {
|
|
|
|
req.Header.Set("Content-Type", contentType)
|
2023-07-21 21:35:18 +00:00
|
|
|
}
|
|
|
|
|
2023-07-25 20:34:11 +00:00
|
|
|
for key, value := range headers {
|
|
|
|
req.Header.Add(key, value)
|
2023-07-21 21:35:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
client := &http.Client{}
|
|
|
|
resp, err := client.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
return http.Response{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return *resp, nil
|
|
|
|
}
|