Implement writing price to db

This commit is contained in:
2024-08-24 16:28:46 +02:00
parent b799e1bbf7
commit d24a5c9307
2 changed files with 26 additions and 18 deletions

35
main.go
View File

@@ -1,6 +1,7 @@
package main package main
import ( import (
_ "embed"
"fmt" "fmt"
"io" "io"
"log" "log"
@@ -8,8 +9,6 @@ import (
"os" "os"
"regexp" "regexp"
"strconv" "strconv"
"time"
_ "embed"
"github.com/PuerkitoBio/goquery" "github.com/PuerkitoBio/goquery"
) )
@@ -56,20 +55,24 @@ func main() {
return return
} }
price := Price{ log.Printf("Fetching price from url %s", url)
Price: 100, price, err := GetPrice(url)
Timestamp: time.Now(), 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 { func GetPrice(url string) (int, error) {
Price int price := 0
Timestamp time.Time
}
func GetPrice() (Price, error) {
price := Price{Timestamp: time.Now()}
res, err := http.Get(url) res, err := http.Get(url)
if err != nil { if err != nil {
@@ -93,7 +96,7 @@ func GetPrice() (Price, error) {
Error.Fatalf("failed parsing price: %q", res) Error.Fatalf("failed parsing price: %q", res)
return return
} }
price.Price, err = strconv.Atoi(res[0]) price, err = strconv.Atoi(res[0])
if err != nil { if err != nil {
Error.Fatalf("failed converting price to int: %v", err) Error.Fatalf("failed converting price to int: %v", err)
return return
@@ -102,7 +105,3 @@ func GetPrice() (Price, error) {
return price, nil return price, nil
} }
func SavePrice(price Price) error {
return nil
}

9
service.go Normal file
View File

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