城市天气数据获取接口

本贴最后更新于 1815 天前,其中的信息可能已经物是人非

一 定义城市天气数据结构,用于存储解析获取的天气数据

type Weather struct { Status int `json:"status"` Date string `json:"date"` Time string `json:"time"` CityInfo CityInfo `json:"cityInfo"` WeatherData WeatherData `json:"data"` } type WeatherData struct { Shidu string `json:"shidu"` Pm25 float64 `json:"pm25"` Pm10 float64 `json:"pm10"` Quality string `json:"quality"` Wendu string `json:"wendu"` Ganmao string `json:"ganmao"` Forecasts []Forecast `json:"forecast"` Yesterday Forecast `json:"yesterday"` } type CityInfo struct { City string `json:"city"` CityKey string `json:"citykey"` Parent string `json:"parent"` UpdateTime string `json:"updateTime"` } type Forecast struct { Date string `json:"date"` High string `json:"high"` Low string `json:"low"` Ymd string `json:"ymd"` Week string `json:"week"` Sunrise string `json:"sunrise"` Sunset string `json:"sunset"` Api int `json:"api"` Fx string `json:"fx"` Fl string `json:"fl"` Type string `json:"type"` Notice string `json:"notice"` }

二 根据城市气象代码表获取 15 天城市天气

城市气象代码表

//GetWeather 获取城市15天天气 func GetWeather(cityCode string) (*Weather, error) { url := "http://t.weather.sojson.com/api/weather/city/" + cityCode weather := &Weather{} resp, err := http.Get(url) if err != nil { return nil, err } defer resp.Body.Close() out, err := ioutil.ReadAll(resp.Body) if err != nil { return nil, err } if err := json.Unmarshal(out, weather); err != nil { return nil, err } if weather.Status != 200 { return nil, errors.New("get weather error!") } return weather, nil }

三 显示效果,例图是 gowork 用的 v-charts 显示 7 天基本的天气图表

3.png

  • golang

    Go 语言是 Google 推出的一种全新的编程语言,可以在不损失应用程序性能的情况下降低代码的复杂性。谷歌首席软件工程师罗布派克(Rob Pike)说:我们之所以开发 Go,是因为过去 10 多年间软件开发的难度令人沮丧。Go 是谷歌 2009 发布的第二款编程语言。

    498 引用 • 1395 回帖 • 257 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...