Files

114 lines
2.8 KiB
Go

package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/joho/godotenv"
"github.com/redis/go-redis/v9"
)
type CurrentConditions struct {
DateTime string `json:"datetime" redis:"datetime"`
Temp float64 `json:"temp" redis:"temp"`
Feelslike float64 `json:"feelslike" redis:"feelslike"`
Humidity float64 `json:"humidity" redis:"humidity"`
Precip float64 `json:"precip" redis:"precip"`
Precipprob float64 `json:"precipprob" redis:"precipprob"`
Conditions string `json:"conditions" redis:"conditions"`
}
type Weather struct {
ResolvedAddress string `json:"resolvedAddress" redis:"resolvedAddress"`
Address string `json:"address" redis:"address"`
Timezone string `json:"timezone" redis:"timezone"`
CurrentConditions CurrentConditions `json:"currentConditions" redis:"currentConditions"`
}
func getNewWeatherStruct(ctx context.Context, rdb *redis.Client) (Weather, error) {
var cachedWeather Weather
raw, err := rdb.Get(ctx, "weather").Bytes()
if err != nil {
return cachedWeather, err
}
if err := json.Unmarshal(raw, &cachedWeather); err != nil {
return cachedWeather, err
}
return cachedWeather, nil
}
func refreshRedisCache(ctx context.Context, rdb *redis.Client) error {
_ = godotenv.Load()
address := os.Getenv("LOCAL_ADDRESS")
cachedWeather, err := getNewWeatherStruct(ctx, rdb)
if err != nil && !errors.Is(err, redis.Nil) {
return err
} else if errors.Is(err, redis.Nil) || cachedWeather.Address != address {
log.Println("Fetching New Data...")
resp, err := http.Get(os.Getenv("API_ADDRESS") + address + os.Getenv("EXTENSION"))
if err != nil {
return err
}
defer resp.Body.Close()
log.Println("Caching data to redis...")
var obj Weather
if err := json.NewDecoder(resp.Body).Decode(&obj); err != nil {
return err
}
data, err := json.Marshal(obj)
if err != nil {
return err
}
if err := rdb.Set(ctx, "weather", data, 30*time.Minute).Err(); err != nil {
return err
}
log.Println("Successfully fetched and cached data...")
fmt.Println()
}
return nil
}
func main() {
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
Protocol: 2,
})
defer rdb.Close()
ctx := context.Background()
exists := refreshRedisCache(ctx, rdb)
if exists != nil {
log.Fatal(exists)
}
w, exists := getNewWeatherStruct(ctx, rdb)
if exists != nil {
log.Fatal(exists)
}
fmt.Printf("%s @ %s\n\nConditions: %s\nTemp: %.1f\nFeels Like: %.1f\nHumidity: %.1f\nHeight of Rain: %.1f\nRain Chance: %.1f\n",
w.ResolvedAddress,
w.CurrentConditions.DateTime,
w.CurrentConditions.Conditions,
w.CurrentConditions.Temp,
w.CurrentConditions.Feelslike,
w.CurrentConditions.Humidity,
w.CurrentConditions.Precip,
w.CurrentConditions.Precipprob)
}