newsbot-portal/apiclient/util.go

69 lines
1.3 KiB
Go
Raw Normal View History

2024-05-12 09:21:20 -07:00
package apiclient
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
)
func PostUrlForm(client http.Client, endpoint string, param url.Values, t any) error {
payload := bytes.NewBufferString(param.Encode())
req, err := http.NewRequest(http.MethodPost, endpoint, payload)
if err != nil {
return err
}
req.Header.Set(HeaderContentType, MIMEApplicationForm)
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&t)
if err != nil {
return err
}
return nil
}
2024-05-26 09:59:31 -07:00
func PostUrl(client http.Client, endpoint string, t any) error {
response, err := http.Post(endpoint, ApplicationJson, nil)
if err != nil {
return err
}
defer response.Body.Close()
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&t)
if err != nil {
return err
}
return nil
}
func PostBodyUrl(client http.Client, endpoint string, body any, t any) error {
jsonBody, err := json.Marshal(body)
if err != nil {
return err
}
response, err := http.Post(endpoint, ApplicationJson, bytes.NewBuffer(jsonBody))
if err != nil {
return err
}
defer response.Body.Close()
decoder := json.NewDecoder(response.Body)
err = decoder.Decode(&t)
if err != nil {
return err
}
return nil
}