aislegopher/pricehistory.go

73 lines
1.3 KiB
Go
Raw Normal View History

2024-11-13 22:08:24 -05:00
package aislegopher
import (
"context"
2024-11-13 22:08:24 -05:00
"encoding/json"
"io"
2024-11-13 22:08:24 -05:00
"net/http"
"strconv"
)
type DatePrice struct {
Date string
Price float64
}
type PriceHistory struct {
RegularPrices []DatePrice `json:"regularPrices,omitempty"`
ThirdPartyPrices []DatePrice `json:"3rdPartyPrices,omitempty"`
}
type Config struct {
Client *http.Client
}
var DefaultConfig = Config{
Client: http.DefaultClient,
}
func GetPriceHistory(ctx context.Context, productId int) (PriceHistory, error) {
return DefaultConfig.GetPriceHistory(ctx, productId)
2024-11-13 22:08:24 -05:00
}
func deferClose(c io.Closer) {
if c != nil {
_ = c.Close()
}
}
func (c Config) GetPriceHistory(ctx context.Context, productId int) (PriceHistory, error) {
2024-11-13 22:08:24 -05:00
cl := c.Client
if cl == nil {
cl = http.DefaultClient
}
req, err := http.NewRequest("GET", "https://aislegopher.com/Home/GetPriceHistoryData?productId="+strconv.Itoa(productId), nil)
if err != nil {
return PriceHistory{}, err
}
req = req.WithContext(ctx)
2024-11-13 22:08:24 -05:00
req.Header.Set("Accept", "application/json")
res, err := cl.Do(req)
if err != nil {
return PriceHistory{}, err
}
defer deferClose(res.Body)
2024-11-13 22:08:24 -05:00
var priceHistory PriceHistory
err = json.NewDecoder(res.Body).Decode(&priceHistory)
if err != nil {
return PriceHistory{}, err
}
return priceHistory, nil
}