@@ -7,9 +7,11 @@ import (
7
7
"log"
8
8
"net/http"
9
9
"strconv"
10
+ "time"
10
11
11
12
"github.com/PuerkitoBio/goquery"
12
13
"github.com/gorilla/mux"
14
+ "github.com/robertoduessmann/weather-api/cache"
13
15
"github.com/robertoduessmann/weather-api/model"
14
16
"github.com/robertoduessmann/weather-api/parser"
15
17
)
@@ -30,6 +32,19 @@ func CurrentWeather(w http.ResponseWriter, r *http.Request) {
30
32
var err error
31
33
32
34
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 )
33
48
resp := getExternalWeather (city )
34
49
if resp == nil {
35
50
w .Header ().Set ("Content-Type" , "application/json" )
@@ -49,9 +64,10 @@ func CurrentWeather(w http.ResponseWriter, r *http.Request) {
49
64
fmt .Fprintf (w , string (toJSON (model.ErrorMessage {Message : "NOT_FOUND" })))
50
65
} else {
51
66
w .WriteHeader (http .StatusOK )
52
- fmt .Fprintf (w , string (toJSON (weather )))
67
+ result := toJSON (weather )
68
+ weatherCache .Put (cacheKey , result )
69
+ w .Write (result )
53
70
}
54
-
55
71
}
56
72
57
73
func getCity (r * http.Request ) string {
@@ -66,7 +82,6 @@ func getExternalWeather(city string) *http.Response {
66
82
return nil
67
83
}
68
84
69
- // Optional: check for non-200 status codes and log them
70
85
if resp .StatusCode != http .StatusOK {
71
86
log .Printf ("Warning: weather API for %s returned status %d" , city , resp .StatusCode )
72
87
resp .Body .Close ()
@@ -112,17 +127,13 @@ func parse(resp *http.Response, weather *model.Weather) error {
112
127
}
113
128
114
129
func 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
120
131
}
121
132
122
133
func toJSON (object interface {}) []byte {
123
- respose , err := json .Marshal (object )
134
+ response , err := json .Marshal (object )
124
135
if err != nil {
125
136
fmt .Println (err )
126
137
}
127
- return respose
138
+ return response
128
139
}
0 commit comments