Refactored GetPriceHistory to accept a context parameter, enabling better control over request lifecycle and cancellation. Updated the main function and deferred body close logic to align with the new context usage. This improves code robustness and readability.
73 lines
1.3 KiB
Go
73 lines
1.3 KiB
Go
package aislegopher
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"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)
|
|
}
|
|
|
|
func deferClose(c io.Closer) {
|
|
if c != nil {
|
|
_ = c.Close()
|
|
}
|
|
}
|
|
|
|
func (c Config) GetPriceHistory(ctx context.Context, productId int) (PriceHistory, error) {
|
|
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)
|
|
|
|
req.Header.Set("Accept", "application/json")
|
|
|
|
res, err := cl.Do(req)
|
|
|
|
if err != nil {
|
|
return PriceHistory{}, err
|
|
}
|
|
defer deferClose(res.Body)
|
|
|
|
var priceHistory PriceHistory
|
|
|
|
err = json.NewDecoder(res.Body).Decode(&priceHistory)
|
|
|
|
if err != nil {
|
|
return PriceHistory{}, err
|
|
}
|
|
|
|
return priceHistory, nil
|
|
}
|