From fc8bedd4744a0a2642f39091f858082026fd87ca Mon Sep 17 00:00:00 2001 From: Steve Dudenhoeffer Date: Wed, 13 Nov 2024 22:08:24 -0500 Subject: [PATCH] initial commit --- cmd/main.go | 44 +++++++++++++++++++++++++++++++++++ go.mod | 3 +++ pricehistory.go | 62 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 109 insertions(+) create mode 100644 cmd/main.go create mode 100644 go.mod create mode 100644 pricehistory.go diff --git a/cmd/main.go b/cmd/main.go new file mode 100644 index 0000000..0e12ed0 --- /dev/null +++ b/cmd/main.go @@ -0,0 +1,44 @@ +package main + +import ( + "aislegopher" + "fmt" + "os" + "strconv" +) + +func main() { + // usage: aisegopher + + if len(os.Args) != 2 { + fmt.Println("usage: aisegopher ") + os.Exit(1) + } + + productId, err := strconv.Atoi(os.Args[1]) + + if err != nil { + fmt.Println("Invalid product ID: ", os.Args[1], " error:", err) + os.Exit(1) + } + + priceHistory, err := aislegopher.GetPriceHistory(productId) + + if err != nil { + fmt.Println("Error getting price history: ", err) + os.Exit(1) + } + + fmt.Println("Regular Prices:") + + for _, dp := range priceHistory.RegularPrices { + fmt.Println(dp.Date, dp.Price) + } + + if len(priceHistory.ThirdPartyPrices) > 0 { + fmt.Println("Third Party Prices:") + for _, dp := range priceHistory.ThirdPartyPrices { + fmt.Println(dp.Date, dp.Price) + } + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..a283455 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module aislegopher + +go 1.23.2 diff --git a/pricehistory.go b/pricehistory.go new file mode 100644 index 0000000..3b66a4a --- /dev/null +++ b/pricehistory.go @@ -0,0 +1,62 @@ +package aislegopher + +import ( + "encoding/json" + "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(productId int) (PriceHistory, error) { + return DefaultConfig.GetPriceHistory(productId) +} + +func (c Config) GetPriceHistory(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.Header.Set("Accept", "application/json") + + res, err := cl.Do(req) + + if err != nil { + return PriceHistory{}, err + } + defer res.Body.Close() + + var priceHistory PriceHistory + + err = json.NewDecoder(res.Body).Decode(&priceHistory) + + if err != nil { + return PriceHistory{}, err + } + + return priceHistory, nil +}