oven-exporter/api/request.go

49 lines
906 B
Go
Raw Normal View History

2021-07-21 00:15:57 +02:00
package api
2021-07-20 12:18:00 +02:00
import (
2021-08-22 15:26:13 +02:00
"bytes"
2021-07-20 12:18:00 +02:00
"encoding/json"
2021-07-20 12:25:05 +02:00
"fmt"
2021-08-22 15:26:13 +02:00
"io"
2021-07-20 12:18:00 +02:00
"net/http"
2021-08-22 15:26:13 +02:00
"strings"
2021-07-20 12:18:00 +02:00
"time"
)
2021-07-21 00:15:57 +02:00
// Request to API and unmarshal result
2021-08-22 15:26:13 +02:00
func (c *Client) Request(method, url string, body, value interface{}) error {
2021-07-20 12:18:00 +02:00
netClient := &http.Client{
Timeout: time.Second * 20,
}
2021-08-22 15:26:13 +02:00
var jsonBody io.Reader
if body != nil {
if strBody, ok := body.(string); ok {
jsonBody = strings.NewReader(strBody)
} else {
jsonBodyArray, err := json.Marshal(body)
if err != nil {
return err
}
jsonBody = bytes.NewBuffer(jsonBodyArray)
}
}
req, err := http.NewRequest(method, c.URL+url, jsonBody)
2021-07-20 12:18:00 +02:00
if err != nil {
return err
}
req.Header = map[string][]string{
"authorization": {fmt.Sprintf("Basic %s", c.Token)},
}
resp, err := netClient.Do(req)
if err != nil {
return err
}
err = json.NewDecoder(resp.Body).Decode(&value)
resp.Body.Close()
if err != nil {
return err
}
return nil
}