Skip to content

Commit

Permalink
Added caching mechanism and cache duration flag to openmeteo backend.
Browse files Browse the repository at this point in the history
  • Loading branch information
VinVorteX committed Oct 6, 2024
1 parent e0113bf commit 5b6d45c
Showing 1 changed file with 42 additions and 11 deletions.
53 changes: 42 additions & 11 deletions backends/open-meteo.com.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import (
"io"
"log"
"net/http"
"os"
"regexp"
"strings"
"sync"
"time"

"github.com/schachmat/wego/iface"
Expand Down Expand Up @@ -119,7 +119,39 @@ func (opmeteo *openmeteoConfig) Setup() {
flag.StringVar(&opmeteo.apiKey, "openmeteo-api-key", "", "openmeteo backend: the api `KEY` to use if commercial usage")
flag.BoolVar(&opmeteo.debug, "openmeteo-debug", false, "openmeteo backend: print raw requests and responses")
opmeteo.cache = make(map[string]cachedData) // initializing a cache
opmeteo.cacheDuration = 1 * time.Hour // setting the cache duation to 1 hour
flag.DurationVar(&opmeteo.cacheDuration, "openmeteo-cache-duration", 1*time.Hour, "openmeteo backend: duration for caching weather data") // adding the cache duration flag
opmeteo.LoadCacheFromDisk()
}

func (opmeteo *openmeteoConfig) SaveCacheToDisk() {
file, err := os.Create("/tmp/wego_cache.json")

if err != nil {
log.Fatal(err)
}

defer file.Close()

json.NewEncoder(file).Encode(opmeteo.cache)
}

func (opmeteo *openmeteoConfig) LoadCacheFromDisk() {
file, err := os.Open("/tmp/wego_cache.json")

if os.IsNotExist(err) {
log.Println("Cache file not found")
return
}

if err != nil {
log.Fatal(err)
}

defer file.Close()

if err := json.NewDecoder(file).Decode(&opmeteo.cache); err != nil {
log.Println("Failed to load cache from disk, starting with an empty cache:", err)
}
}

func (opmeteo *openmeteoConfig) parseDaily(dailyInfo Hourly) []iface.Day {
Expand Down Expand Up @@ -171,21 +203,17 @@ func parseCurCond(current curCond) (ret iface.Cond) {

}

var mu sync.Mutex

func (opmeteo *openmeteoConfig) Fetch(location string, numdays int) iface.Data {
var ret iface.Data
var params []string
var loc string

//checking cache before fething the data
mu.Lock()
if cached, ok := opmeteo.cache[location]; ok {
if time.Since(cached.Timestamp) < opmeteo.cacheDuration {
return cached.Data
}
}
mu.Unlock()

if numdays <= 0 {
log.Fatal("Number of days less than 1 ")
Expand All @@ -207,9 +235,11 @@ func (opmeteo *openmeteoConfig) Fetch(location string, numdays int) iface.Data {

res, err := http.Get(requri)
if err != nil {
log.Fatal("Unable to get weather data: ", err)
log.Println("Unable to get weather data: ", err)
return ret
} else if res.StatusCode != 200 {
log.Fatal("Unable to get weather data: http status ", res.StatusCode)
log.Println("Unable to get weather data: http status ", res.StatusCode)
return ret
}
defer res.Body.Close()

Expand All @@ -226,7 +256,8 @@ func (opmeteo *openmeteoConfig) Fetch(location string, numdays int) iface.Data {

var resp openmeteoResponse
if err = json.Unmarshal(body, &resp); err != nil {
log.Println(err)
log.Println("Failed to unmarshal weather data:", err)
return ret
}

ret.Current = parseCurCond(resp.Current)
Expand All @@ -240,12 +271,12 @@ func (opmeteo *openmeteoConfig) Fetch(location string, numdays int) iface.Data {
ret.Forecast = forecast
}

mu.Lock()
opmeteo.cache[location] = cachedData{
Data: ret, //store the fetched data in the cache
Timestamp: time.Now(), // store the current time in the cache
}
mu.Unlock()

opmeteo.SaveCacheToDisk()

return ret
}
Expand Down

0 comments on commit 5b6d45c

Please sign in to comment.