本例请求了天气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)")
}
标签:wea,http,string,示例,fmt,json,Println,Tem
From: https://www.cnblogs.com/ccwangjin/p/18079275