@@ -7,9 +7,11 @@ import (
77 "log"
88 "net/http"
99 "strconv"
10+ "time"
1011
1112 "github.com/PuerkitoBio/goquery"
1213 "github.com/gorilla/mux"
14+ "github.com/robertoduessmann/weather-api/cache"
1315 "github.com/robertoduessmann/weather-api/model"
1416 "github.com/robertoduessmann/weather-api/parser"
1517)
@@ -30,6 +32,19 @@ func CurrentWeather(w http.ResponseWriter, r *http.Request) {
3032 var err error
3133
3234 city := getCity (r )
35+ cacheKey := fmt .Sprintf ("html-%s" , city )
36+
37+ cacheManager := cache .NewCacheManager ()
38+ weatherCache := cacheManager .NewCache ("weather-html" , 10 * time .Minute )
39+
40+ if cached , found := weatherCache .Get (cacheKey ); found {
41+ log .Printf ("[CACHE HIT] key=%s" , cacheKey )
42+ w .Header ().Set ("Content-Type" , "application/json" )
43+ w .Write (cached .([]byte ))
44+ return
45+ }
46+
47+ log .Printf ("[CACHE MISS] key=%s" , cacheKey )
3348 resp := getExternalWeather (city )
3449 if resp == nil {
3550 w .Header ().Set ("Content-Type" , "application/json" )
@@ -49,9 +64,10 @@ func CurrentWeather(w http.ResponseWriter, r *http.Request) {
4964 fmt .Fprintf (w , string (toJSON (model.ErrorMessage {Message : "NOT_FOUND" })))
5065 } else {
5166 w .WriteHeader (http .StatusOK )
52- fmt .Fprintf (w , string (toJSON (weather )))
67+ result := toJSON (weather )
68+ weatherCache .Put (cacheKey , result )
69+ w .Write (result )
5370 }
54-
5571}
5672
5773func getCity (r * http.Request ) string {
@@ -66,7 +82,6 @@ func getExternalWeather(city string) *http.Response {
6682 return nil
6783 }
6884
69- // Optional: check for non-200 status codes and log them
7085 if resp .StatusCode != http .StatusOK {
7186 log .Printf ("Warning: weather API for %s returned status %d" , city , resp .StatusCode )
7287 resp .Body .Close ()
@@ -112,17 +127,13 @@ func parse(resp *http.Response, weather *model.Weather) error {
112127}
113128
114129func notFound (weather * model.Weather ) bool {
115- if len (weather .Description ) == 0 {
116- return true
117- }
118-
119- return false
130+ return len (weather .Description ) == 0
120131}
121132
122133func toJSON (object interface {}) []byte {
123- respose , err := json .Marshal (object )
134+ response , err := json .Marshal (object )
124135 if err != nil {
125136 fmt .Println (err )
126137 }
127- return respose
138+ return response
128139}
0 commit comments