diff --git a/cmd/main.go b/cmd/main.go index 36369c7..faa332b 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -1,6 +1,7 @@ package main import ( + "context" "fmt" "os" "strconv" @@ -10,6 +11,7 @@ import ( func main() { // usage: aisegopher + ctx := context.Background() if len(os.Args) != 2 { fmt.Println("usage: aisegopher ") @@ -23,7 +25,7 @@ func main() { os.Exit(1) } - priceHistory, err := aislegopher.GetPriceHistory(productId) + priceHistory, err := aislegopher.GetPriceHistory(ctx, productId) if err != nil { fmt.Println("Error getting price history: ", err) diff --git a/pricehistory.go b/pricehistory.go index 3b66a4a..f97c37c 100644 --- a/pricehistory.go +++ b/pricehistory.go @@ -1,7 +1,9 @@ package aislegopher import ( + "context" "encoding/json" + "io" "net/http" "strconv" ) @@ -24,11 +26,17 @@ var DefaultConfig = Config{ Client: http.DefaultClient, } -func GetPriceHistory(productId int) (PriceHistory, error) { - return DefaultConfig.GetPriceHistory(productId) +func GetPriceHistory(ctx context.Context, productId int) (PriceHistory, error) { + return DefaultConfig.GetPriceHistory(ctx, productId) } -func (c Config) GetPriceHistory(productId int) (PriceHistory, error) { +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 { @@ -41,6 +49,8 @@ func (c Config) GetPriceHistory(productId int) (PriceHistory, error) { return PriceHistory{}, err } + req = req.WithContext(ctx) + req.Header.Set("Accept", "application/json") res, err := cl.Do(req) @@ -48,7 +58,7 @@ func (c Config) GetPriceHistory(productId int) (PriceHistory, error) { if err != nil { return PriceHistory{}, err } - defer res.Body.Close() + defer deferClose(res.Body) var priceHistory PriceHistory