56 lines
1.4 KiB
Go
56 lines
1.4 KiB
Go
|
package utilities
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"io"
|
||
|
"net/http"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
func GetHttpRequestToWordpress(url, user, pass string) []byte {
|
||
|
request, err := http.NewRequest("GET", url, strings.NewReader(""))
|
||
|
addAuth(user, pass, request)
|
||
|
CheckError(err)
|
||
|
body := RequestToWordpress(request, user, pass)
|
||
|
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)
|
||
|
return body
|
||
|
}
|
||
|
|
||
|
func RequestToWordpress(request *http.Request, user, pass string) []byte {
|
||
|
client := &http.Client{}
|
||
|
addAuth(user, pass, request)
|
||
|
//send
|
||
|
response, err := client.Do(request)
|
||
|
CheckError(err)
|
||
|
//make sure to close body
|
||
|
defer CloseBodyAndCheckError(response.Body)
|
||
|
|
||
|
CheckHttpResponseStatus(response)
|
||
|
|
||
|
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) {
|
||
|
if response.StatusCode != 200 {
|
||
|
fmt.Println("Status Code:", response.Status, http.StatusText(response.StatusCode))
|
||
|
}
|
||
|
}
|