-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformHandler.go
More file actions
300 lines (230 loc) · 7.14 KB
/
formHandler.go
File metadata and controls
300 lines (230 loc) · 7.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
)
type AddressAPIResponse struct {
apiName string
address string
statusCode int
status string
}
type WeatherAPIResponse struct {
apiName string
tempMax []float64
tempMin []float64
statusCode int
status string
}
type CalculationsResult struct {
minTemp1 float64
minTemp2 float64
avgMinTemp float64
maxTemp1 float64
maxTemp2 float64
avgMaxTemp float64
avgTemp1 float64
avgTemp2 float64
avgTemp float64
}
func fetchAddress(latitude, longitude string, ch chan AddressAPIResponse) {
var (
addressAPIResponse AddressAPIResponse = AddressAPIResponse{apiName: "nominatim.openstreetmap.org"}
url string = fmt.Sprintf("https://nominatim.openstreetmap.org/reverse?lat=%s&lon=%s&format=json", latitude, longitude)
)
resp, err := http.Get(url)
if err != nil {
addressAPIResponse.statusCode = http.StatusInternalServerError
addressAPIResponse.status = "Internal server error"
ch <- addressAPIResponse
return
}
addressAPIResponse.statusCode = resp.StatusCode
addressAPIResponse.status = resp.Status
if !isCodeSuccessful(resp.StatusCode) {
ch <- addressAPIResponse
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
addressAPIResponse.statusCode = http.StatusInternalServerError
addressAPIResponse.status = "Internal server error"
ch <- addressAPIResponse
return
}
var location struct {
Address struct {
City string `json:"city"`
Country string `json:"country"`
} `json:"address"`
}
if err = json.Unmarshal(body, &location); err != nil {
addressAPIResponse.statusCode = http.StatusInternalServerError
addressAPIResponse.status = "Internal server error"
ch <- addressAPIResponse
return
}
addressAPIResponse.address = location.Address.Country + " " + location.Address.City
ch <- addressAPIResponse
}
func fetchWeatherFromAPI1(latitude, longitude, days string, ch chan WeatherAPIResponse) {
var (
weatherAPIResponse WeatherAPIResponse = WeatherAPIResponse{apiName: "weatherapi"}
url string = fmt.Sprintf("http://api.weatherapi.com/v1/forecast.json?key=ef95ee45d3e94837b26195852230703&q=%s,%s&days=%s", latitude, longitude, days)
)
resp, err := http.Get(url)
if err != nil {
weatherAPIResponse.statusCode = http.StatusInternalServerError
weatherAPIResponse.status = "Internal server error"
ch <- weatherAPIResponse
return
}
weatherAPIResponse.statusCode = resp.StatusCode
weatherAPIResponse.status = resp.Status
if !isCodeSuccessful(resp.StatusCode) {
ch <- weatherAPIResponse
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
weatherAPIResponse.statusCode = http.StatusInternalServerError
weatherAPIResponse.status = "Internal server error"
ch <- weatherAPIResponse
return
}
var weatherData struct {
Forecast struct {
Forecastday []struct {
Date string `json:"date"`
Day struct {
MaxtempC float64 `json:"maxtemp_c"`
MintempC float64 `json:"mintemp_c"`
} `json:"day"`
} `json:"forecastday"`
} `json:"forecast"`
}
err = json.Unmarshal(body, &weatherData)
if err != nil {
weatherAPIResponse.statusCode = http.StatusInternalServerError
weatherAPIResponse.status = "Internal server error"
ch <- weatherAPIResponse
return
}
for _, forecast := range weatherData.Forecast.Forecastday {
weatherAPIResponse.tempMax = append(weatherAPIResponse.tempMax, forecast.Day.MaxtempC)
weatherAPIResponse.tempMin = append(weatherAPIResponse.tempMin, forecast.Day.MintempC)
}
ch <- weatherAPIResponse
}
func fetchWeatherFromAPI2(latitude, longitude, days string, ch chan WeatherAPIResponse) {
weatherAPIResponse := WeatherAPIResponse{apiName: "open-meteo"}
daysInt, _ := strconv.Atoi(days)
startDate := time.Now().AddDate(0, 0, 1).Format("2006-01-02")
endDate := time.Now().AddDate(0, 0, daysInt).Format("2006-01-02")
url := fmt.Sprintf("https://api.open-meteo.com/v1/forecast?latitude=%s&longitude=%s", latitude, longitude) + "&daily=temperature_2m_max,temperature_2m_min&timezone=Europe%2FBerlin&start_date=" + fmt.Sprintf("%s&end_date=%s", startDate, endDate)
resp, err := http.Get(url)
if err != nil {
weatherAPIResponse.statusCode = http.StatusInternalServerError
weatherAPIResponse.status = "Internal server error"
ch <- weatherAPIResponse
return
}
weatherAPIResponse.statusCode = resp.StatusCode
weatherAPIResponse.status = resp.Status
if !isCodeSuccessful(resp.StatusCode) {
ch <- weatherAPIResponse
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
weatherAPIResponse.statusCode = http.StatusInternalServerError
weatherAPIResponse.status = "Internal server error"
ch <- weatherAPIResponse
return
}
var weatherData struct {
Daily struct {
Time []string `json:"time"`
Temperature2mMax []float64 `json:"temperature_2m_max"`
Temperature2mMin []float64 `json:"temperature_2m_min"`
} `json:"daily"`
}
err = json.Unmarshal(body, &weatherData)
if err != nil {
weatherAPIResponse.statusCode = http.StatusInternalServerError
weatherAPIResponse.status = "Internal server error"
ch <- weatherAPIResponse
return
}
weatherAPIResponse.tempMax = append(weatherAPIResponse.tempMax, weatherData.Daily.Temperature2mMax...)
weatherAPIResponse.tempMin = append(weatherAPIResponse.tempMin, weatherData.Daily.Temperature2mMin...)
ch <- weatherAPIResponse
}
func calculateResults(res1, res2 WeatherAPIResponse) CalculationsResult {
var calcResult CalculationsResult
// min temp based on first, second, average from both APIs
calcResult.minTemp1 = min(res1.tempMin)
calcResult.minTemp2 = min(res2.tempMin)
calcResult.avgMinTemp = (calcResult.minTemp1 + calcResult.minTemp2) / float64(2)
// max temp based on first, second, average from both APIs
calcResult.maxTemp1 = max(res1.tempMax)
calcResult.maxTemp2 = max(res2.tempMax)
calcResult.avgMaxTemp = (calcResult.maxTemp1 + calcResult.maxTemp2) / float64(2)
// Calculate average temperatures
calcResult.avgTemp1 = avg(avgSlice(res1.tempMin, res1.tempMax))
calcResult.avgTemp2 = avg(avgSlice(res2.tempMin, res2.tempMax))
calcResult.avgTemp = (calcResult.avgTemp1 + calcResult.avgTemp2) / float64(2)
return calcResult
}
func avgSlice(s1, s2 []float64) []float64 {
var s []float64
for i := 0; i < len(s1); i++ {
s = append(s, (s1[i]+s2[i])/float64(2))
}
return s
}
func avg(s []float64) float64 {
var sum float64 = 0
for _, number := range s {
sum += number
}
return sum / float64(len(s))
}
func max(s []float64) float64 {
var max float64 = s[0]
for _, number := range s {
if number > max {
max = number
}
}
return max
}
func min(s []float64) float64 {
var min float64 = s[0]
for _, number := range s {
if number < min {
min = number
}
}
return min
}
func parseBody(r *http.Request) map[string]string {
if err := r.ParseForm(); err != nil {
return nil
}
formValues := make(map[string]string)
for key, value := range r.Form {
formValues[key] = value[0]
}
return formValues
}
func isCodeSuccessful(code int) bool {
return code >= 200 && code <= 299
}