本例請求了天氣api介面
對接流程
- 註冊一個賬號, 對接免費實況天氣介面
- 閱讀介面文件 http://tianqiapi.com/index/doc?version=day
- 請求介面
- 解析json
開發流程
- 建立一個 json.go 檔案
- 需要引入的包
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
-
定義 Weather Struct
go結構體內的變數首字母必須大寫
type Weather struct {
Nums int
Cityid string
City string
Date string
Week string
Update_time string
Wea string
Wea_img string
Tem string
Tem_day string
Tem_night string
Win string
Win_speed string
Win_meter string
Air string
Pressure string
Humidity string
}
- http.Get 請求介面
- json.Unmarshal 解析json
- gofmt -w json.go 格式化程式碼
完整程式碼
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Weather struct {
Nums int
Cityid string
City string
Date string
Week string
Update_time string
Wea string
Wea_img string
Tem string
Tem_day string
Tem_night string
Win string
Win_speed string
Win_meter string
Air string
Pressure string
Humidity string
}
func main() {
resp, err := http.Get("http://v1.yiketianqi.com/free/day?appid=85841439&appsecret=EKCDLT4I&unescape=1&city=")
if err != nil {
fmt.Println("請求失敗:", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("讀取響應失敗:", err)
}
fmt.Println(string(body))
jsonData := []byte(string(body))
var wea Weather
err2 := json.Unmarshal(jsonData, &wea)
if err2 != nil {
fmt.Println("error:", err2)
return
}
fmt.Println("城市名稱:", wea.City)
fmt.Println("城市編號:", wea.Cityid)
fmt.Println("當前日期:", wea.Date, wea.Week)
fmt.Println("更新時間:", wea.Update_time)
fmt.Println("今日天氣:", wea.Tem, "°", wea.Wea, wea.Tem_night, "°~", wea.Tem_day, "°")
fmt.Println("風向風力:", wea.Win, wea.Win_speed, wea.Win_meter)
fmt.Println("空氣質量:", wea.Air)
fmt.Println("當前氣壓:", wea.Pressure)
fmt.Println("當前溼度:", wea.Humidity)
fmt.Println("資料來源:", "天氣API(http://tianqiapi.com)")
}