From c7e5ee6d3094efa93c5ea992fa8826cc9d636944 Mon Sep 17 00:00:00 2001 From: Sosokker Date: Sun, 2 Feb 2025 08:56:21 +0700 Subject: [PATCH] feat: add caching --- cmd/go.mod | 2 ++ cmd/go.sum | 2 ++ cmd/main.go | 20 +++++++++++++++++++- 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/cmd/go.mod b/cmd/go.mod index cf77a3e..23bf989 100644 --- a/cmd/go.mod +++ b/cmd/go.mod @@ -3,3 +3,5 @@ module github.com/Sosokker/openweather-dashboard go 1.23.5 require github.com/rs/cors v1.11.1 + +require github.com/patrickmn/go-cache v2.1.0+incompatible diff --git a/cmd/go.sum b/cmd/go.sum index 014abec..3cfc033 100644 --- a/cmd/go.sum +++ b/cmd/go.sum @@ -1,2 +1,4 @@ +github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= +github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA= github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= diff --git a/cmd/main.go b/cmd/main.go index a8976c0..63e2988 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -10,10 +10,19 @@ import ( "os" "strconv" "strings" + "time" + "github.com/patrickmn/go-cache" "github.com/rs/cors" ) +var c *cache.Cache + +func init() { + c = cache.New(30*time.Minute, 60*time.Minute) + // c.Set("coordinate", "entry", cache.DefaultExpiration) +} + type Coordinate struct { Place string `json:"place"` Lon float32 `json:"lon"` @@ -67,6 +76,12 @@ func loadEnv() string { // Fetch weather data with specific latitude and longitude and decode into struct func fetchWeatherData(lat, lon float32, apiKey string) DataEntry { var url = fmt.Sprintf("https://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&appid=%s", lat, lon, strings.TrimSpace(apiKey)) + + coordstr := fmt.Sprintf("%f, %f", lat, lon) + if data, found := c.Get(coordstr); found { + return data.(DataEntry) + } + fmt.Println(url) resp, err := http.Get(url) if err != nil { @@ -85,6 +100,9 @@ func fetchWeatherData(lat, lon float32, apiKey string) DataEntry { log.Fatalln("Error: error decode json to struct", err) } + // cache + c.Set(coordstr, entry, cache.DefaultExpiration) + return entry } @@ -132,7 +150,7 @@ func rawDataHandler(w http.ResponseWriter, r *http.Request) { apiKey := loadEnv() coordCh := make(chan Coordinate) - go readCoordData("data/test.csv", coordCh) + go readCoordData("data/data.csv", coordCh) var max float32 = 0.0 var min float32 = 10000000.0