1
0
mirror of https://github.com/alice-lg/alice-lg.git synced 2024-05-11 05:55:03 +00:00

72 lines
1.4 KiB
Go
Raw Normal View History

2017-05-19 17:40:22 +02:00
package birdwatcher
// Http Birdwatcher Client
import (
2022-03-17 15:15:23 +01:00
"context"
2017-05-19 17:40:22 +02:00
"encoding/json"
"io/ioutil"
"net/http"
)
2022-06-15 14:36:22 +02:00
// ClientResponse is a json key value mapping
2017-05-19 17:40:22 +02:00
type ClientResponse map[string]interface{}
2021-10-15 19:31:15 +02:00
// A Client uses the http client to talk
// to the birdwatcher API.
2017-05-19 17:40:22 +02:00
type Client struct {
2021-10-15 19:31:15 +02:00
api string
2017-05-19 17:40:22 +02:00
}
2021-10-15 19:31:15 +02:00
// NewClient creates a new client instance
2017-05-19 17:40:22 +02:00
func NewClient(api string) *Client {
client := &Client{
2021-10-15 19:31:15 +02:00
api: api,
2017-05-19 17:40:22 +02:00
}
return client
}
2022-03-17 15:15:23 +01:00
// GetEndpoint makes an API request and returns the
// response. The response body will be parsed further
// downstream.
func (c *Client) GetEndpoint(
ctx context.Context,
endpoint string,
) (*http.Response, error) {
2022-06-15 14:36:22 +02:00
client := &http.Client{}
2022-03-17 16:44:51 +01:00
url := c.api + endpoint
2022-06-15 14:36:22 +02:00
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
2022-03-17 16:44:51 +01:00
if err != nil {
return nil, err
}
2022-03-17 16:44:51 +01:00
return client.Do(req)
2022-03-17 15:15:23 +01:00
}
2022-06-15 14:36:22 +02:00
// GetJSON makes an API request.
// Parse JSON response and return map or error.
func (c *Client) GetJSON(
ctx context.Context,
endpoint string,
2021-10-15 19:31:15 +02:00
) (ClientResponse, error) {
2022-06-15 14:36:22 +02:00
res, err := c.GetEndpoint(ctx, endpoint)
2017-05-19 17:40:22 +02:00
if err != nil {
return ClientResponse{}, err
}
// Read body
defer res.Body.Close()
payload, err := ioutil.ReadAll(res.Body)
if err != nil {
return ClientResponse{}, err
}
// Decode json payload
result := make(ClientResponse)
err = json.Unmarshal(payload, &result)
if err != nil {
return ClientResponse{}, err
}
return result, nil
}