Implement price fetching

This commit is contained in:
2024-08-24 15:58:40 +02:00
parent 8cc84e75d0
commit 11dac10072
3 changed files with 118 additions and 19 deletions

94
main.go
View File

@@ -5,11 +5,16 @@ import (
"fmt"
"io"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
_ "embed"
"github.com/PuerkitoBio/goquery"
"github.com/joho/godotenv"
"github.com/redis/go-redis/v9"
)
@@ -39,6 +44,10 @@ func init() {
var env string
var ctx = context.Background()
var rdb *redis.Client
var priceRegex = regexp.MustCompile(`\d+`)
const url = "https://jysk.hr/spavaca-soba/madraci/madraci-s-oprugama/madrac-s-oprugama-140x200-gold-s110-dreamzone"
func main() {
envvar, err := godotenv.Parse(strings.NewReader(env))
@@ -58,31 +67,78 @@ func main() {
return
}
rdb := redis.NewClient(&redis.Options{
rdb = redis.NewClient(&redis.Options{
Addr: redisHost,
Password: redisPassword,
DB: 0,
})
err = rdb.Set(ctx, "key", "value", 0).Err()
if err != nil {
panic(err)
}
// rdb.ZAdd(ctx)
val, err := rdb.Get(ctx, "key").Result()
if err != nil {
panic(err)
}
fmt.Println("key", val)
// err = rdb.Set(ctx, "key", "value", 0).Err()
// if err != nil {
// panic(err)
// }
val2, err := rdb.Get(ctx, "key2").Result()
if err == redis.Nil {
fmt.Println("key2 does not exist")
} else if err != nil {
panic(err)
} else {
fmt.Println("key2", val2)
// val, err := rdb.Get(ctx, "key").Result()
// if err != nil {
// panic(err)
// }
// fmt.Println("key", val)
// val2, err := rdb.Get(ctx, "key2").Result()
// if err == redis.Nil {
// fmt.Println("key2 does not exist")
// } else if err != nil {
// panic(err)
// } else {
// fmt.Println("key2", val2)
// }
price, err := GetPrice()
if err != nil {
Error.Fatalf("Error getting price: %v", err)
return
}
// Output: key value
// key2 does not exist
log.Printf("%#v", price)
}
type Price struct {
Price int
Timestamp time.Time
}
func GetPrice() (Price, error) {
price := Price{Timestamp: time.Now()}
res, err := http.Get(url)
if err != nil {
return price, fmt.Errorf("failed querying url %s with error %w", url, err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return price, fmt.Errorf("failed getting data from %s with status: %s", url, res.Status)
}
doc, err := goquery.NewDocumentFromReader(res.Body)
if err != nil {
log.Fatal(err)
}
doc.Find("span.ssr-product-price__value").Each(func(i int, s *goquery.Selection) {
log.Printf("Found price element with text: %s", s.Text())
res := priceRegex.FindStringSubmatch(s.Text())
if len(res) != 1 {
Error.Fatalf("failed parsing price: %q", res)
return
}
price.Price, err = strconv.Atoi(res[0])
if err != nil {
Error.Fatalf("failed converting price to int: %v", err)
return
}
})
return price, nil
}