-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
110 lines (89 loc) · 2.25 KB
/
api.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
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
package accuweather
import (
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"github.com/PlatformOfTrust/connector-accuweather/models"
jsoniter "github.com/json-iterator/go"
)
var json = jsoniter.ConfigCompatibleWithStandardLibrary
type GeoPositionService struct {
Token string
}
func (s *GeoPositionService) Get(l *models.Location) (string, error) {
url, _ := url.Parse("https://dataservice.accuweather.com/locations/v1/cities/geoposition/search")
q := url.Query()
q.Set("apikey", s.Token)
q.Set("q", fmt.Sprintf("%f,%f", l.Lat, l.Lng))
url.RawQuery = q.Encode()
resp, err := http.Get(url.String())
if err != nil {
return "", err
}
body, _ := ioutil.ReadAll(resp.Body)
var response GeoPositionResponse
err = json.Unmarshal(body, &response)
if err != nil {
return "", err
}
if response.Key == "" {
return "", errors.New("No key found")
}
return response.Key, err
}
type ForecastService struct {
Token string
GeoPosition models.GeoPositionService
}
func (s *ForecastService) Get(p *models.Params) ([]models.Forecast, error) {
locationKey, err := s.GeoPosition.Get(&p.TargetObject)
if err != nil {
return []models.Forecast{}, err
}
baseUrl := "https://dataservice.accuweather.com/forecasts/v1/daily"
var uri string
switch p.Period {
case 1:
uri = fmt.Sprintf("%s/%s/%s", baseUrl, "1day", locationKey)
break
case 5:
uri = fmt.Sprintf("%s/%s/%s", baseUrl, "5day", locationKey)
break
case 10:
uri = fmt.Sprintf("%s/%s/%s", baseUrl, "10day", locationKey)
break
case 15:
uri = fmt.Sprintf("%s/%s/%s", baseUrl, "15day", locationKey)
break
default:
uri = fmt.Sprintf("http://dataservice.accuweather.com/currentconditions/v1/%s", locationKey)
break
}
url, _ := url.Parse(uri)
q := url.Query()
q.Set("apikey", s.Token)
q.Set("details", "true")
q.Set("metric", "true")
url.RawQuery = q.Encode()
resp, err := http.Get(url.String())
if err != nil {
return []models.Forecast{}, err
}
decoder := json.NewDecoder(resp.Body)
if p.Period == 0 {
var fc []CurrentCondition
err = decoder.Decode(&fc)
if err != nil {
return []models.Forecast{}, err
}
return fc[0].MapToPot(), nil
}
var fc Forecast
err = decoder.Decode(&fc)
if err != nil {
return []models.Forecast{}, err
}
return fc.MapToPot(), nil
}