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.
This commit is contained in:
Steve Dudenhoeffer 2025-01-19 23:54:17 -05:00
parent be3848d0b3
commit 9da603f937
2 changed files with 17 additions and 5 deletions

View File

@ -1,6 +1,7 @@
package main
import (
"context"
"fmt"
"os"
"strconv"
@ -10,6 +11,7 @@ import (
func main() {
// usage: aisegopher <product_id>
ctx := context.Background()
if len(os.Args) != 2 {
fmt.Println("usage: aisegopher <product_id>")
@ -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)

View File

@ -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