You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
1.5 KiB
75 lines
1.5 KiB
package tianqiapi
|
|
|
|
import (
|
|
"io/ioutil"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
)
|
|
|
|
const hostUrl = "https://tianqiapi.com/api?"
|
|
const appid = "81622428"
|
|
const appsecret = "AxKzYWq3"
|
|
|
|
var TianqiApi = &tianqiapi{}
|
|
|
|
type tianqiapi struct {
|
|
}
|
|
|
|
// @Style 根据城市id获取天气
|
|
func (t *tianqiapi) CityId(cityId string) (string, error) {
|
|
return t.Exec(url.Values{
|
|
"cityid": []string{cityId},
|
|
})
|
|
}
|
|
|
|
// @Style 根据城市获取天气
|
|
func (t *tianqiapi) City(city string) (string, error) {
|
|
return t.Exec(url.Values{
|
|
"city": []string{city},
|
|
})
|
|
}
|
|
|
|
// @Style 调用接口
|
|
func (t *tianqiapi) Exec(values url.Values) (string, error) {
|
|
t.pargams(&values)
|
|
request, err := t.request("get", hostUrl+values.Encode(), "")
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return request, nil
|
|
}
|
|
|
|
func (t *tianqiapi) pargams(values *url.Values) {
|
|
values.Add("version", "v61")
|
|
values.Add("appid", appid)
|
|
values.Add("appsecret", appsecret)
|
|
return
|
|
}
|
|
|
|
// @Style 网络请求
|
|
func (t *tianqiapi) request(method string, host string, data string, headers ...*map[string]string) (string, error) {
|
|
client := &http.Client{}
|
|
method = strings.ToUpper(method)
|
|
|
|
req, err := http.NewRequest(method, host, strings.NewReader(data))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if len(headers) > 0 {
|
|
for key, value := range *headers[0] {
|
|
req.Header.Add(key, value)
|
|
}
|
|
}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer resp.Body.Close()
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return string(body), nil
|
|
}
|