From d24a5c93073678e99a6fb3327be4ec217389627b Mon Sep 17 00:00:00 2001 From: PhatPhuckDave Date: Sat, 24 Aug 2024 16:28:46 +0200 Subject: [PATCH] Implement writing price to db --- main.go | 35 +++++++++++++++++------------------ service.go | 9 +++++++++ 2 files changed, 26 insertions(+), 18 deletions(-) create mode 100644 service.go diff --git a/main.go b/main.go index 6d51e4d..91b3e77 100644 --- a/main.go +++ b/main.go @@ -1,6 +1,7 @@ package main import ( + _ "embed" "fmt" "io" "log" @@ -8,8 +9,6 @@ import ( "os" "regexp" "strconv" - "time" - _ "embed" "github.com/PuerkitoBio/goquery" ) @@ -56,20 +55,24 @@ func main() { return } - price := Price{ - Price: 100, - Timestamp: time.Now(), + log.Printf("Fetching price from url %s", url) + price, err := GetPrice(url) + if err != nil { + Error.Fatalf("Error getting price: %v", err) + return } - log.Printf("%#v", price) + log.Printf("Fetched price as '%d' from url %q", price, url) + + err = SavePrice(&db, price) + if err != nil { + Error.Fatalf("Error saving price: %v", err) + return + } + log.Printf("Price '%d' saved to db", price) } -type Price struct { - Price int - Timestamp time.Time -} - -func GetPrice() (Price, error) { - price := Price{Timestamp: time.Now()} +func GetPrice(url string) (int, error) { + price := 0 res, err := http.Get(url) if err != nil { @@ -93,7 +96,7 @@ func GetPrice() (Price, error) { Error.Fatalf("failed parsing price: %q", res) return } - price.Price, err = strconv.Atoi(res[0]) + price, err = strconv.Atoi(res[0]) if err != nil { Error.Fatalf("failed converting price to int: %v", err) return @@ -102,7 +105,3 @@ func GetPrice() (Price, error) { return price, nil } - -func SavePrice(price Price) error { - return nil -} diff --git a/service.go b/service.go new file mode 100644 index 0000000..c11d5c4 --- /dev/null +++ b/service.go @@ -0,0 +1,9 @@ +package main + +func SavePrice(db *DB, price int) error { + _, err := db.writeConn.Exec("INSERT INTO price(price) VALUES (?)", price) + if err != nil { + return err + } + return nil +}