![]() 2.7℃ 晴 |
|
风向风速:东北风2级 |
|
相对湿度:43% |
|
空气质量:66良 |
Go语言调用天气查询接口示例:
package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
)
const (
URL = "https://api.ip138.com/weather/"
TOKEN = "bd4c2bf9a38ab06f7cae88c9759ee172"
)
//----------------------------------
// 调用示例代码
//----------------------------------
//json struct
type weatherInfoJson struct {
Ret string `json:"ret"`
Code int `json:"code"`
Province string `json:"province"`
City string `json:"city"`
Area string `json:"area"`
Data todayData `json:"data"`
}
type todayData struct {
Time string `json:"time"`
DayWeather string `json:"dayWeather"`
DayTemp string `json:"dayTemp"`
DayWind string `json:"dayWind"`
NightWeather string `json:"nightWeather"`
NightTemp string `json:"nightTemp"`
NightWind string `json:"nightWind"`
Temp string `json:"temp"`
Weather string `json:"weather"`
Wind string `json:"wind"`
Humidity string `json:"humidity"`
Pm25 string `json:"pm25"`
}
func getWeather(code int) {
queryUrl := fmt.Sprintf("%s?code=%d&type=%d",URL,code,1)
client := &http.Client{}
reqest, err := http.NewRequest("GET",queryUrl,nil)
if err != nil {
fmt.Println("Fatal error ",err.Error())
}
reqest.Header.Add("token",TOKEN)
response, err := client.Do(reqest)
defer response.Body.Close()
if err != nil {
fmt.Println("Fatal error ",err.Error())
}
if response.StatusCode == 200 {
bodyByte, _ := ioutil.ReadAll(response.Body)
var info weatherInfoJson
json.Unmarshal(bodyByte,&info)
fmt.Println(info.Ip)
}
return
}