newsbot-portal/apiclient/util.go

104 lines
2.0 KiB
Go

package apiclient
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
)
const (
HeaderAuthorization = "Authorization"
)
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
}
func PostUrlAuthorized(client http.Client, endpoint, jwtToken string, t any) error {
req, err := http.NewRequest(http.MethodPost, endpoint, nil)
if err != nil {
return err
}
req.Header.Add(HeaderAuthorization, fmt.Sprintf("%s %s", "Bearer", jwtToken))
response, err := client.Do(req)
//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
}
func Get(client http.Client, endpoint, jwt string, t any) (int, error) {
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
if err != nil {
return -1, err
}
req.Header.Set(HeaderContentType, ApplicationJson)
req.Header.Set(HeaderAuthorization, fmt.Sprintf("Bearer %s", jwt))
resp, err := client.Do(req)
if err != nil {
return -1, err
}
defer resp.Body.Close()
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&t)
if err != nil {
return -1, err
}
return resp.StatusCode, nil
}