From 9da603f937973af7c36d904ecfb42d38a77682b6 Mon Sep 17 00:00:00 2001 From: Steve Dudenhoeffer Date: Sun, 19 Jan 2025 23:54:17 -0500 Subject: [PATCH] Add context support to GetPriceHistory function 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. --- cmd/main.go | 4 +++- pricehistory.go | 18 ++++++++++++++---- 2 files changed, 17 insertions(+), 5 deletions(-) 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