Post-Migrator/utilities/http-utilities.go

62 lines
1.5 KiB
Go
Raw Permalink Normal View History

2024-05-07 22:03:15 +00:00
package utilities
import (
"encoding/json"
2024-05-17 18:49:55 +00:00
"errors"
2024-05-07 22:03:15 +00:00
"io"
"net/http"
"strings"
)
func GetHttpRequestToWordpress(url, user, pass string) []byte {
request, err := http.NewRequest("GET", url, nil)
2024-05-07 22:03:15 +00:00
addAuth(user, pass, request)
CheckError(err)
2024-05-17 18:49:55 +00:00
body, _ := requestToWordpress(request, user, pass)
2024-05-07 22:03:15 +00:00
return body
}
2024-05-17 18:49:55 +00:00
func PostHttpRequestToWordpress(url, user, pass string, parameters any) ([]byte, error) {
2024-05-07 22:03:15 +00:00
requestBodyBytes, err := json.Marshal(parameters)
requestBody := string(requestBodyBytes)
2024-05-17 18:49:55 +00:00
if err != nil {
return make([]byte, 0), err
}
2024-05-07 22:03:15 +00:00
request, err := http.NewRequest("POST", url, strings.NewReader(requestBody))
2024-05-17 18:49:55 +00:00
if err != nil {
return make([]byte, 0), err
}
body, err := requestToWordpress(request, user, pass)
return body, err
2024-05-07 22:03:15 +00:00
}
2024-05-17 18:49:55 +00:00
func requestToWordpress(request *http.Request, user, pass string) ([]byte, error) {
2024-05-07 22:03:15 +00:00
client := &http.Client{}
addAuth(user, pass, request)
response, err := client.Do(request)
2024-05-17 18:49:55 +00:00
if err != nil {
return make([]byte, 0), err
}
2024-05-07 22:03:15 +00:00
defer CloseBodyAndCheckError(response.Body)
2024-05-17 18:49:55 +00:00
err = checkHttpResponseStatus(response)
if err != nil {
return make([]byte, 0), err
}
2024-05-07 22:03:15 +00:00
body, err := io.ReadAll(response.Body)
CheckError(err)
2024-05-17 18:49:55 +00:00
return body, nil
2024-05-07 22:03:15 +00:00
}
func addAuth(user, pass string, request *http.Request) {
request.SetBasicAuth(user, pass)
request.Header.Add("content-type", "application/json")
}
2024-05-17 18:49:55 +00:00
func checkHttpResponseStatus(response *http.Response) error {
if response.StatusCode >= 200 && response.StatusCode < 300 {
return nil
} else {
return errors.New("Status Code:" + response.Status + http.StatusText(response.StatusCode))
2024-05-07 22:03:15 +00:00
}
}