81 lines
1.6 KiB
Go
81 lines
1.6 KiB
Go
package api
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/tls"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
)
|
|
|
|
type HttpClient struct {
|
|
baseURL string
|
|
userAgent string
|
|
}
|
|
|
|
func NewHttpClient(baseURL string) *HttpClient {
|
|
return &HttpClient{baseURL: baseURL, userAgent: "internal-http-client"}
|
|
}
|
|
|
|
func (c *HttpClient) SendGet(url string, data, out any) error {
|
|
fmt.Printf("Sending req to: %s%s\n", c.baseURL, url)
|
|
res, err := c.sendRequest(url, http.MethodGet, data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
decoder := json.NewDecoder(res.Body)
|
|
err = decoder.Decode(&out)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (c *HttpClient) SendPost(url string, data, out any) (any, error) {
|
|
res, err := c.sendRequest(url, http.MethodPost, data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
decoder := json.NewDecoder(res.Body)
|
|
err = decoder.Decode(out)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return out, nil
|
|
}
|
|
|
|
func (c *HttpClient) sendRequest(url, method string, data any) (*http.Response, error) {
|
|
apiUrl := c.baseURL + url
|
|
|
|
tr := &http.Transport{
|
|
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // FIXME dev mode
|
|
}
|
|
|
|
// Create an HTTP client with the custom transport
|
|
client := &http.Client{Transport: tr} // FIXME dev mode
|
|
|
|
json, err := json.Marshal(&data)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
req, err := http.NewRequest(method, apiUrl, bytes.NewBuffer(json))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("User-Agent", c.userAgent)
|
|
res, err := client.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer res.Body.Close()
|
|
|
|
return res, nil
|
|
}
|