Golang实战天气查询程序开发
时间:2025-11-19
浏览:320
作者:佚名
**用 Golang 编写天气查询程序实战:快速入门指南** 想用 Golang 实现一个简单的天气查询程序吗?本文将手把手教你如何使用 Golang 调用 OpenWeatherMap API 获取天气信息。首先,你需要注册 OpenWeatherMap 账号并获取 API 密钥。然后,通过定义合适的结构体来映射 API 返回的 JSON 数据,例如城市名称、温度、湿度和国家等信息。接下来,利用 `net/http` 包发起 GET 请求,并使用 `encoding/json` 包解析 JSON 响应。最后,在 `main` 函数中传入城市名称和 API 密钥,即可输出实时的天气信息。本文将详细讲解每一步骤,让你轻松掌握 Golang API 调用和 JSON 解析技巧,快速构建自己的天气查询应用。
答案是使用Golang调用OpenWeatherMap API实现天气查询。首先注册获取API密钥,通过https://api.openweathermap.org/data/2.5/weather接口发送GET请求,定义包含Name、Main、Sys等字段的结构体映射JSON响应,利用net/http发起请求,encoding/json解析结果,在main函数中传入城市和密钥,输出温度、湿度和国家信息,最终实现基础天气查询功能。

想用 Golang 写一个天气查询程序?其实不难。核心是调用公开的天气 API,获取 JSON 数据,然后解析并展示结果。下面一步步带你实现,从 API 调用到结构体定义,再到 JSON 解析,实战走起。
选择天气 API 并获取密钥
我们以 OpenWeatherMap 为例,它提供免费的天气数据接口。你需要先注册账号,获取一个 API Key。
关键接口地址:
https://api.openweathermap.org/data/2.5/weather?q=城市名&appid=你的密钥&units=metric
其中 units=metric 表示温度单位为摄氏度。
定义结构体来映射 JSON 响应
Golang 解析 JSON 的关键是定义与返回数据结构匹配的 struct。API 返回的数据较复杂,我们只提取关心的部分:
type Weather struct {
Main struct {
Temp float64 `json:"temp"`
Humidity int `json:"humidity"`
} `json:"main"`
Name string `json:"name"`
Sys struct {
Country string `json:"country"`
} `json:"sys"`
}
字段标签 json:"xxx" 告诉解析器 JSON 中的键名。比如 Temp 对应的是 main.temp。
发送 HTTP 请求并解析响应
使用标准库 net/http 发起 GET 请求,再用 encoding/json 解码:
func getWeather(city, apiKey string) (*Weather, error) {
url := fmt.Sprintf("https://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=metric", city, apiKey)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("天气服务错误: %s", resp.Status)
}
var weather Weather
err = json.NewDecoder(resp.Body).Decode(&weather)
if err != nil {
return nil, err
}
return &weather, nil
}
注意检查 HTTP 状态码,避免服务端出错时继续解析。
主函数调用并输出结果
在 main 中调用函数,打印天气信息:
func main() {
apiKey := "your_api_key_here"
city := "Beijing"
weather, err := getWeather(city, apiKey)
if err != nil {
log.Fatal(err)
}
fmt.Printf("城市: %s, 国家: %s\n", weather.Name, weather.Sys.Country)
fmt.Printf("温度: %.1f°C\n", weather.Main.Temp)
fmt.Printf("湿度: %d%%\n", weather.Main.Humidity)
}
运行后你会看到类似:
城市: Beijing, 国家: CN温度: 22.3°C
湿度: 65%
基本上就这些。Golang 处理 API 和 JSON 非常直接,只要结构体对得上,解析几乎零负担。你可以扩展支持多个城市、命令行输入,或者加上缓存机制。实战中多看 API 文档,结构体就能写准。
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
