Post-Migrator/utilities/http-utilities.go

51 lines
1.3 KiB
Go
Raw Normal View History

2024-05-07 22:03:15 +00:00
package utilities
import (
"encoding/json"
"fmt"
"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)
body := requestToWordpress(request, user, pass)
2024-05-07 22:03:15 +00:00
return body
}
func PostHttpRequestToWordpress(url, user, pass string, parameters any) []byte {
requestBodyBytes, err := json.Marshal(parameters)
requestBody := string(requestBodyBytes)
CheckError(err)
request, err := http.NewRequest("POST", url, strings.NewReader(requestBody))
CheckError(err)
body := requestToWordpress(request, user, pass)
2024-05-07 22:03:15 +00:00
return body
}
func requestToWordpress(request *http.Request, user, pass string) []byte {
2024-05-07 22:03:15 +00:00
client := &http.Client{}
addAuth(user, pass, request)
response, err := client.Do(request)
CheckError(err)
defer CloseBodyAndCheckError(response.Body)
checkHttpResponseStatus(response)
2024-05-07 22:03:15 +00:00
body, err := io.ReadAll(response.Body)
CheckError(err)
return body
}
func addAuth(user, pass string, request *http.Request) {
request.SetBasicAuth(user, pass)
request.Header.Add("content-type", "application/json")
}
func checkHttpResponseStatus(response *http.Response) {
2024-05-07 22:03:15 +00:00
if response.StatusCode != 200 {
fmt.Println("Status Code:", response.Status, http.StatusText(response.StatusCode))
}
}