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

80 lines
1.5 KiB
Go
Raw Normal View History

2017-05-19 17:40:22 +02:00
package birdwatcher
// Http Birdwatcher Client
import (
"encoding/json"
"io/ioutil"
"net/http"
"time"
2017-05-19 17:40:22 +02:00
)
2021-10-15 19:31:15 +02:00
// ClientResponse is a 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
}
2021-10-15 19:31:15 +02:00
// Get makes an API request.
// Parse response and return map or error.
func (c *Client) Get(
client *http.Client,
url string,
) (ClientResponse, error) {
res, err := client.Get(url)
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
}
2021-10-15 19:31:15 +02:00
// GetJSON makes an API request.
// Parse JSON response and return map or error.
func (c *Client) GetJSON(
endpoint string,
) (ClientResponse, error) {
client := &http.Client{}
2021-10-15 19:31:15 +02:00
return c.Get(client, c.api+endpoint)
}
2021-10-15 19:31:15 +02:00
// GetJSONTimeout make an API request, parses the
// JSON response and returns the result or an error.
//
// This will all go away one we use the new context.
func (c *Client) GetJSONTimeout(
timeout time.Duration,
endpoint string,
) (ClientResponse, error) {
client := &http.Client{
Timeout: timeout,
}
2021-10-15 19:31:15 +02:00
return c.Get(client, c.api+endpoint)
}