Golang实现天气查询API教程
时间:2025-09-26
浏览:401
作者:佚名
想用Go语言快速搭建一个天气查询API吗?本文将提供一份详细的Golang天气查询API实例教程,教你如何利用Golang和OpenWeatherMap API,轻松构建一个支持中文显示和摄氏度单位的天气查询服务。教程涵盖从OpenWeatherMap API密钥申请、`WeatherResponse`结构体定义,到`getWeather`处理函数实现,以及HTTP服务启动的全过程。你将学会如何接收城市参数,调用第三方API,并返回JSON格式的天气数据。此外,文章还提供优化建议,如环境变量配置、缓存机制和超时控制等,助你打造更稳定高效的天气API。无论你是Golang新手还是有一定经验的开发者,都能通过本教程快速掌握天气API的开发技巧。
答案:使用Golang和OpenWeatherMap API可快速构建天气查询服务。1. 注册获取API密钥;2. 定义WeatherResponse结构体解析JSON响应;3. 实现getWeather处理函数,接收city参数并调用第三方API;4. 主函数注册/weather路由并启动HTTP服务;5. 返回JSON格式天气数据,支持中文与摄氏度单位;6. 可通过环境变量、缓存、超时控制等进行优化。

用Golang构建一个简单的天气信息查询API并不复杂,结合标准库和第三方天气服务(如OpenWeatherMap),可以快速实现。下面是一个完整的示例,展示如何创建一个HTTP服务,接收城市名称,调用天气API并返回JSON格式的天气数据。
1. 准备工作:获取OpenWeatherMap API密钥
访问 OpenWeatherMap官网 注册账号并获取免费的API密钥(App ID)。免费版支持每分钟60次请求,足够学习和小项目使用。
2. 项目结构与依赖
创建项目目录,无需外部依赖(仅使用标准库):
weather-api/├── main.go
我们只使用 net/http、encoding/json 和 io/ioutil 等标准库。
3. 定义数据结构
根据OpenWeatherMap的响应,定义对应的Go结构体:
type WeatherResponse 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"`
}
4. 实现天气查询处理函数
编写一个处理函数,从URL参数中读取城市名,调用OpenWeatherMap API:
func getWeather(w http.ResponseWriter, r *http.Request) {
city := r.URL.Query().Get("city")
if city == "" {
http.Error(w, "缺少城市参数", http.StatusBadRequest)
return
}
apiKey := "你的API密钥" // 替换为你的实际密钥
url := fmt.Sprintf("http://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=metric&lang=zh_cn", city, apiKey)
resp, err := http.Get(url)
if err != nil {
http.Error(w, "请求天气数据失败", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
http.Error(w, "城市未找到或API错误", http.StatusNotFound)
return
}
var weather WeatherResponse
body, _ := ioutil.ReadAll(resp.Body)
json.Unmarshal(body, &weather)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(weather)
}
5. 启动HTTP服务器
在 main 函数中注册路由并启动服务:
func main() {
http.HandleFunc("/weather", getWeather)
fmt.Println("服务器启动在 :8080")
http.ListenAndServe(":8080", nil)
}
6. 测试API
运行程序后,访问:
http://localhost:8080/weather?city=Beijing
返回示例:
{"main":{"temp":25,"humidity":60},"name":"Beijing","sys":{"country":"CN"}}7. 可选优化
- 使用环境变量存储API密钥,避免硬编码
- 添加缓存机制(如内存缓存)减少重复请求
- 使用 context 控制HTTP请求超时
- 增加日志输出便于调试
- 使用结构化配置管理
基本上就这些。这个示例展示了如何用Golang快速构建一个实用的天气查询API,不复杂但涵盖了HTTP客户端、JSON解析和服务端响应等核心知识点。
理论要掌握,实操不能落!以上关于《Golang实现天气查询API教程》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
