85 lines
2.0 KiB
Go
Raw Normal View History

2023-11-13 11:52:45 -07:00
package staticjsonYahooFinance
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
2025-05-07 12:16:55 -06:00
const apiBaseURL = "https://query1.finance.yahoo.com/v8/finance"
2023-11-13 11:52:45 -07:00
// 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 {
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 {
req, err := http.NewRequest("GET", apiBaseURL+endpoint+"?"+query.Encode(), nil)
if err != nil {
return err
}
// Yahoo finance requires user agent string now?
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:138.0) Gecko/20100101 Firefox/138.0")
2023-11-13 11:52:45 -07:00
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 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 {
body, err := io.ReadAll(res.Body)
res.Body.Close()
if err != nil {
return err
}
if res.StatusCode != 200 {
return fmt.Errorf("got http response status '%d' but expected 200 for request at URL '%s'", res.StatusCode, res.Request.URL)
2023-11-13 11:52:45 -07:00
}
err = json.Unmarshal(body, out)
if err != nil {
return err
}
return nil
}
// newClient is the factory function for clients - takes an API token
func newClient() (*client, error) {
transport := &http.Transport{
ResponseHeaderTimeout: 5 * time.Second,
}
httpClient := &http.Client{
Transport: transport,
}
// Create a new client
c := &client{
httpClient: httpClient,
transport: transport,
}
return c, nil
}