ynab-portfolio-monitor/bitcoin/client.go

80 lines
2.0 KiB
Go
Raw Normal View History

2023-11-12 23:50:46 +00:00
package bitcoin
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
const apiBaseURL = "https://blockstream.info/api/"
// A client is the structure that will be used to consume the API
// endpoints. It holds the login credentials, http client/transport,
// rate limit information, and the login session timer.
type client struct {
2023-11-12 23:50:46 +00:00
httpClient *http.Client
transport *http.Transport
}
// Send an HTTP GET request, and return the processed response
func (c *client) get(endpoint string, out interface{}, query url.Values) error {
2023-11-12 23:50:46 +00:00
req, err := http.NewRequest("GET", apiBaseURL+endpoint+"?"+query.Encode(), nil)
if err != nil {
return fmt.Errorf("failed to create new GET request: %v", err)
}
res, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("http GET request failed: %v", err)
}
err = c.processResponse(res, out)
if err != nil {
return fmt.Errorf("failed to process response: %v", err)
}
return nil
}
// processResponse takes the body of an HTTP response, and either returns
// the error code, or unmarshalls the JSON response, extracts
// rate limit info, and places it into the object
// output parameter. This function closes the response body after reading it.
func (c *client) processResponse(res *http.Response, out interface{}) error {
2023-11-12 23:50:46 +00:00
body, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return fmt.Errorf("failed to read response body: %v", err)
}
if res.StatusCode != 200 && res.StatusCode != 201 {
return fmt.Errorf("unexpected http status code '%d': %v", res.StatusCode, err)
}
err = json.Unmarshal(body, out)
if err != nil {
return fmt.Errorf("failed to unmarshal response body: %v", err)
}
return nil
}
// newClient is the factory function for clients
func newClient() (*client, error) {
2023-11-12 23:50:46 +00:00
transport := &http.Transport{
ResponseHeaderTimeout: 5 * time.Second,
}
httpClient := &http.Client{
2023-11-12 23:50:46 +00:00
Transport: transport,
}
// Create a new client
c := &client{
httpClient: httpClient,
2023-11-12 23:50:46 +00:00
transport: transport,
}
return c, nil
}