This repository has been archived by the owner on Jan 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aliyun.go
78 lines (72 loc) · 1.53 KB
/
aliyun.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
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
type AliRes struct {
Status string `json:"status"`
Msg string `json:"msg"`
Result struct {
City string `json:"city"`
Aqi struct {
Pm2_5 string `json:"pm2_5"`
Quality string `json:"quality"`
} `json:"aqi"`
} `json:"result"`
}
type Aliyun struct {
Req http.Client
Appcode string
}
func makeErrorAqi(err error) Aqi {
return Aqi{Error: err.Error()}
}
func parseBody(res *http.Response) ([]byte, error) {
var body []byte
if res.StatusCode != 200 {
return body, errors.New(res.Status)
}
// 读取Body
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return body, err
}
return body, nil
}
func (x Aliyun) Query(city string) Aqi {
// 创建请求
url := fmt.Sprintf("http://jisutqybmf.market.alicloudapi.com/weather/query?city=%s", city)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return makeErrorAqi(err)
}
req.Header.Add("Authorization", fmt.Sprintf("APPCODE %s", x.Appcode))
// 执行请求
res, err := x.Req.Do(req)
if err != nil {
return makeErrorAqi(err)
}
defer res.Body.Close()
body, err := parseBody(res)
if err != nil {
return makeErrorAqi(err)
}
var aqidata AliRes
err = json.Unmarshal(body, &aqidata)
if err != nil {
return makeErrorAqi(err)
}
// 检查返回值
if aqidata.Status != "0" {
return makeErrorAqi(errors.New(aqidata.Msg))
}
return Aqi{
Pm2_5: aqidata.Result.Aqi.Pm2_5,
Area: aqidata.Result.City,
Quality: aqidata.Result.Aqi.Quality,
Error: "",
}
}