-
Notifications
You must be signed in to change notification settings - Fork 0
/
weather.go
85 lines (67 loc) · 1.76 KB
/
weather.go
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
package main
import (
"encoding/json"
"log"
"net/http"
)
type weatherProvider interface {
temperature(country string, city string) (float64, error)
}
type openWeatherMap struct {
apiKey string
}
func (w openWeatherMap) temperature(country string, city string) (float64, error) {
resp, err := http.Get("http://api.openweathermap.org/data/2.5/weather?APPID=" + w.apiKey + "&q=" + city)
if err != nil {
log.Printf("Error %s", err)
return 0, err
}
defer resp.Body.Close()
var d struct {
Name string `json:"name"`
Main struct {
Kelvin float64 `json:"temp"`
} `json:"main"`
}
if err := json.NewDecoder(resp.Body).Decode(&d); err != nil {
log.Printf("Error %s", err)
return 0, err
}
log.Printf("openWeatherMap: %s: %.2f", city, d.Main.Kelvin)
return d.Main.Kelvin, nil
}
type weatherUnderground struct {
apiKey string
}
func (w weatherUnderground) temperature(country string, city string) (float64, error) {
resp, err := http.Get("http://api.wunderground.com/api/" + w.apiKey + "/conditions/q/" + country + "/" + city + ".json")
if err != nil {
log.Printf("Error %s", err)
return 0, err
}
defer resp.Body.Close()
var d struct {
Observation struct {
Celsius float64 `json:"temp_c"`
} `json:"current_observation"`
}
if err := json.NewDecoder(resp.Body).Decode(&d); err != nil {
log.Printf("Error %s", err)
return 0, err
}
kelvin := d.Observation.Celsius + 273.15
log.Printf("weatherUnderground:: %s: %.2f", city, kelvin)
return kelvin, nil
}
type multiWeatherProvider []weatherProvider
func (w multiWeatherProvider) temperature(city string) (float64, error) {
sum := 0.0
for _, provider := range w {
k, err := provider.temperature(city)
if err != nil {
return 0, err
}
sum += k
}
return sum / float64(len(w)), nil
}