答案是使用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 解析,实战走起。
我们以 OpenWeatherMap 为例,它提供免费的天气数据接口。你需要先注册账号,获取一个 API Key。
关键接口地址:
https://api.openweathermap.org/data/2.5/weather?q=城市名&appid=你的密钥&units=metric
其中 units=metric 表示温度单位为摄氏度。
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。
立即学习“go语言免费学习笔记(深入)”;
使用标准库 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基本上就这些。Golang 处理 API 和 JSON 非常直接,只要结构体对得上,解析几乎零负担。你可以扩展支持多个城市、命令行输入,或者加上缓存机制。实战中多看 API 文档,结构体就能写准。
以上就是如何用 Golang 编写一个天气查询程序_Golang API 调用与 JSON 解析实战的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号