From 5ab4a83098d32097a11a42ab74211f84027faa63 Mon Sep 17 00:00:00 2001 From: Levi Olson Date: Fri, 4 Jan 2019 14:43:27 -0600 Subject: [PATCH] Adding caching to the Dark Sky API call --- main.go | 16 +++++++++++++--- rest.go | 4 ---- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/main.go b/main.go index 560ef24..e2be7f0 100644 --- a/main.go +++ b/main.go @@ -5,7 +5,10 @@ import ( "net/http" "os" "strconv" + "time" + "github.com/gin-contrib/cache" + "github.com/gin-contrib/cache/persistence" "github.com/gin-gonic/autotls" "github.com/gin-gonic/gin" ) @@ -29,7 +32,10 @@ func main() { c.String(http.StatusOK, "pong") }) - router.GET("/current_weather/:lat/:long", func(c *gin.Context) { + cacheDuration := time.Minute * 15 + cacheStore := persistence.NewInMemoryStore(cacheDuration) + + router.GET("/current_weather/:lat/:long", cache.CachePage(cacheStore, cacheDuration, func(c *gin.Context) { lat, err := strconv.ParseFloat(c.Params.ByName("lat"), 64) long, err := strconv.ParseFloat(c.Params.ByName("long"), 64) if err != nil { @@ -44,9 +50,13 @@ func main() { } c.Header("Access-Control-Allow-Origin", "*") c.JSON(http.StatusOK, gin.H{"weather": response}) - }) + })) - log.Fatal(autotls.Run(router, "weather.l3vi.co")) + if os.Getenv("GIN_MODE") == "release" { + log.Fatal(autotls.Run(router, "weather.l3vi.co")) + } else { + log.Fatal(router.Run(":80")) + } } func currentWeather(lat, long float64, apikey string) (ForecastResponse, error) { diff --git a/rest.go b/rest.go index 496967b..4275e44 100644 --- a/rest.go +++ b/rest.go @@ -11,7 +11,6 @@ import ( func get(client *http.Client, url string, output interface{}) error { req, err := http.NewRequest("GET", url, nil) - if err != nil { return err } @@ -20,7 +19,6 @@ func get(client *http.Client, url string, output interface{}) error { req.Header.Add("Accept-Encoding", "gzip") response, err := client.Do(req) - if err != nil { return err } @@ -28,13 +26,11 @@ func get(client *http.Client, url string, output interface{}) error { defer response.Body.Close() err = checkErrors(response) - if err != nil { return err } body, err := decompress(response) - if err != nil { return err }