bottin-agenda/data/apiclient.go

96 lines
2 KiB
Go
Raw Normal View History

2023-05-29 17:58:23 -04:00
package data
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
)
type ApiClient struct {
Key string
Host string
Port int
Protocol string
}
func NewApiClient(key, host, protocol string, port int) *ApiClient {
return &ApiClient{
Key: key,
Host: host,
Port: port,
Protocol: protocol,
}
}
func (a *ApiClient) Call(method, route string, requestBody io.Reader, useKey bool) (*http.Response, error) {
var response *http.Response
endpoint := fmt.Sprintf("%s://%s:%d%s",
a.Protocol, a.Host, a.Port, route,
)
// Create client
client := &http.Client{}
// Create request
request, err := http.NewRequest(method, endpoint, requestBody)
if err != nil {
return response, err
}
if useKey {
if a.Key == "" {
return response, fmt.Errorf("Call to API required a key but none was provided. See --help for instructions on providing an API key.")
}
request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", a.Key))
}
if requestBody != nil {
request.Header.Add("Content-Type", "application/json")
}
// Fetch Request
response, err = client.Do(request)
if err != nil {
return response, err
}
return response, nil
}
2023-06-03 19:48:37 -04:00
// BottinHealthResponse is the response type for GetBottinHealth
type BottinHealthResponse struct {
Message string `json:"message"`
}
// GetHealth allows checking for API server health
func (a *ApiClient) GetBottinHealth() (string, error) {
var healthResponse BottinHealthResponse
2023-05-29 17:58:23 -04:00
2023-06-03 19:48:37 -04:00
response, err := a.Call(http.MethodGet, "/v4/health", nil, true)
2023-05-29 17:58:23 -04:00
if err != nil {
2023-06-03 19:48:37 -04:00
return healthResponse.Message, err
2023-05-29 17:58:23 -04:00
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
2023-06-03 19:48:37 -04:00
return healthResponse.Message, err
2023-05-29 17:58:23 -04:00
}
2023-06-03 19:48:37 -04:00
if err := json.Unmarshal(body, &healthResponse); err != nil {
return healthResponse.Message, err
2023-05-29 17:58:23 -04:00
}
2023-06-03 19:48:37 -04:00
if healthResponse.Message == "" {
return healthResponse.Message, errors.New("Could not confirm that API server is up, no response message")
2023-05-29 17:58:23 -04:00
}
2023-06-03 19:48:37 -04:00
return healthResponse.Message, nil
2023-05-29 17:58:23 -04:00
}