答案:使用Golang和OpenWeatherMap API可快速构建天气查询服务。1. 注册获取API密钥;2. 定义WeatherResponse结构体解析JSON响应;3. 实现getWeather处理函数,接收city参数并调用第三方API;4. 主函数注册/weather路由并启动HTTP服务;5. 返回JSON格式天气数据,支持中文与摄氏度单位;6. 可通过环境变量、缓存、超时控制等进行优化。

用Golang构建一个简单的天气信息查询API并不复杂,结合标准库和第三方天气服务(如OpenWeatherMap),可以快速实现。下面是一个完整的示例,展示如何创建一个HTTP服务,接收城市名称,调用天气API并返回JSON格式的天气数据。
访问 OpenWeatherMap官网 注册账号并获取免费的API密钥(App ID)。免费版支持每分钟60次请求,足够学习和小项目使用。
创建项目目录,无需外部依赖(仅使用标准库):
weather-api/我们只使用 net/http、encoding/json 和 io/ioutil 等标准库。
立即学习“go语言免费学习笔记(深入)”;
根据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"`
}
编写一个处理函数,从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)
}
在 main 函数中注册路由并启动服务:
func main() {
http.HandleFunc("/weather", getWeather)
fmt.Println("服务器启动在 :8080")
http.ListenAndServe(":8080", nil)
}
运行程序后,访问:
http://localhost:8080/weather?city=Beijing
返回示例:
{"main":{"temp":25,"humidity":60},"name":"Beijing","sys":{"country":"CN"}}基本上就这些。这个示例展示了如何用Golang快速构建一个实用的天气查询API,不复杂但涵盖了HTTP客户端、JSON解析和服务端响应等核心知识点。
以上就是Golang构建天气信息查询API示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号