/
weather.go
79 lines (70 loc) · 1.9 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
package gaodeKit
import (
"github.com/richelieu-yang/chimera/v2/src/component/web/request/reqKit"
"github.com/richelieu-yang/chimera/v2/src/core/errorKit"
"github.com/richelieu-yang/chimera/v2/src/serialize/json/jsonKit"
)
const (
weatherUrl = "https://restapi.amap.com/v3/weather/weatherInfo"
)
// GetLive 获取"实况"天气.
/*
@param city 城市编码
*/
func (client *Client) GetLive(city string) (*Live, error) {
_, data, err := reqKit.Get(weatherUrl, map[string][]string{
"key": {client.key},
"city": {city},
"extensions": {"base"},
})
if err != nil {
return nil, err
}
resp := &WeatherResponse{}
if err := jsonKit.Unmarshal(data, resp); err != nil {
return nil, errorKit.Wrap(err, "Fail to unmarshal with json: %s", string(data))
}
if err := resp.IsSuccess(); err != nil {
return nil, err
}
if len(resp.Lives) == 0 {
return nil, errorKit.New("len(resp.Lives) == 0")
}
return resp.Lives[0], nil
}
// GetTodayCast 获取今天的"预报"天气.
func (client *Client) GetTodayCast(city string) (*Cast, error) {
forecast, err := client.GetForecast(city)
if err != nil {
return nil, err
}
if len(forecast.Casts) == 0 {
return nil, errorKit.New("len(forecast.Casts) == 0")
}
return forecast.Casts[0], nil
}
// GetForecast 获取"预报"天气.
/*
@param city 城市编码
*/
func (client *Client) GetForecast(city string) (*Forecast, error) {
_, data, err := reqKit.Get(weatherUrl, map[string][]string{
"key": {client.key},
"city": {city},
"extensions": {"all"},
})
if err != nil {
return nil, err
}
resp := &WeatherResponse{}
if err := jsonKit.Unmarshal(data, resp); err != nil {
return nil, errorKit.Wrap(err, "Fail to unmarshal with json: %s", string(data))
}
if err := resp.IsSuccess(); err != nil {
return nil, err
}
if len(resp.Forecasts) == 0 {
return nil, errorKit.New("len(resp.Forecasts) == 0")
}
return resp.Forecasts[0], nil
}