-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweather.go
61 lines (51 loc) · 1.41 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
package main
import (
"encoding/json"
"fmt"
)
type WeatherClient struct {
apiKey string
httpClient HttpClientInterface
cache map[string]*WeatherMeta
}
const (
baseUrl string = "https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/"
)
func (weather *WeatherClient) GetWeatherCondition(latitude, longitude, datetime string, c chan *WeatherMeta) {
cacheKey := latitude + longitude + datetime
res, ok := weather.cache[cacheKey]
if ok {
c <- res
} else {
var weatherMeta *WeatherMeta
url := baseUrl + latitude + "," + longitude + "/" + datetime + "?key=" + weather.apiKey + "&include=current&unitGroup=uk"
body, err := weather.httpClient.Get(url)
if err == nil {
var weatherData WeatherData
err = json.Unmarshal(body, &weatherData)
if err == nil {
weatherMeta = &WeatherMeta{
WeatherData: &weatherData,
Error: nil,
}
}
}
if err != nil {
fmt.Println("Error while calling the weather api")
weatherMeta = &WeatherMeta{
WeatherData: nil,
Error: err,
}
}
// update the cache
weather.cache[cacheKey] = weatherMeta
c <- weatherMeta
}
}
func NewWeatherClient(httpClient HttpClientInterface, apiKey string) WeatherClientInterface {
weatherClient := WeatherClient{}
weatherClient.apiKey = apiKey
weatherClient.httpClient = httpClient
weatherClient.cache = make(map[string]*WeatherMeta)
return &weatherClient
}