Files
tastytrade/api.go

95 lines
2.2 KiB
Go
Raw Permalink Normal View History

2024-05-14 21:50:57 -04:00
package tastytrade
import (
"encoding/json"
"fmt"
"net/http"
"time"
)
const (
baseURL = "https://api.tastytrade.com"
)
// TastytradeAPI represents the Tastytrade API client
type TastytradeAPI struct {
httpClient *http.Client
2025-05-07 23:50:46 -04:00
user string
2024-05-14 21:50:57 -04:00
authToken string
2025-05-07 23:50:46 -04:00
authExpire time.Time
remToken string
2024-05-14 21:50:57 -04:00
host string
}
// NewTastytradeAPI creates a new instance of TastytradeAPI
func NewTastytradeAPI(hosts ...string) *TastytradeAPI {
host := baseURL
if len(hosts) > 0 {
host = hosts[0]
}
return &TastytradeAPI{
httpClient: &http.Client{Timeout: 10 * time.Second},
host: host,
}
}
2025-05-07 23:50:46 -04:00
// get logged in User
func (api *TastytradeAPI) User() string {
return api.user
}
2024-05-14 21:50:57 -04:00
// fetchData sends a GET request to the specified URL with authorization
func (api *TastytradeAPI) fetchData(url string) (map[string]interface{}, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", api.authToken)
resp, err := api.httpClient.Do(req)
if err != nil {
return nil, err
}
defer func() { _ = resp.Body.Close() }()
2024-05-14 21:50:57 -04:00
if resp.StatusCode >= 400 && resp.StatusCode < 500 {
return nil, fmt.Errorf("client error occurred: status code %d", resp.StatusCode)
} else if resp.StatusCode >= 500 {
return nil, fmt.Errorf("server error occurred: status code %d", resp.StatusCode)
}
var data map[string]interface{}
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
return nil, err
}
return data, nil
}
// Helper function to fetch and unmarshal data
func (api *TastytradeAPI) fetchDataAndUnmarshal(urlVal string, v interface{}) error {
req, err := http.NewRequest("GET", urlVal, nil)
if err != nil {
return err
}
req.Header.Set("Authorization", api.authToken)
resp, err := api.httpClient.Do(req)
if err != nil {
return err
}
defer func() { _= resp.Body.Close() }()
2024-05-14 21:50:57 -04:00
if resp.StatusCode >= 400 && resp.StatusCode < 500 {
return fmt.Errorf("client error occurred: status code %d", resp.StatusCode)
} else if resp.StatusCode >= 500 {
return fmt.Errorf("server error occurred: status code %d", resp.StatusCode)
}
if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
return err
}
return nil
}