feat: add caching

This commit is contained in:
Sosokker 2025-02-02 08:56:21 +07:00
parent 191b1bdbd6
commit c7e5ee6d30
3 changed files with 23 additions and 1 deletions

View File

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

View File

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

View File

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