在Go语言中获取当地天气情况通常需要调用第三方天气API服务(如和风天气、心知天气、OpenWeatherMap等)。以下是一个基于OpenWeatherMap API的示例代码:
1. 注册API密钥
前往 OpenWeatherMap 注册账号,获取免费的API Key(免费版有调用限制)。
2. Go代码示例
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
// 定义天气数据结构(根据API返回的JSON格式调整)
type WeatherData struct {
Name string `json:"name"` // 城市名
Main struct {
Temp float64 `json:"temp"` // 温度(开尔文)
Humidity int `json:"humidity"` // 湿度
} `json:"main"`
Weather []struct {
Description string `json:"description"` // 天气描述(如 "多云")
} `json:"weather"`
}
func main() {
apiKey := "你的API_KEY" // 替换为你的OpenWeatherMap API Key
city := "Beijing" // 目标城市
units := "metric" // 单位制(metric:摄氏,imperial:华氏)
// 构造API请求URL
url := fmt.Sprintf("http://api.openweathermap.org/data/2.5/weather?q=%s&units=%s&appid=%s", city, units, apiKey)
// 发送HTTP GET请求
resp, err := http.Get(url)
if err != nil {
fmt.Printf("请求失败: %v\n", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("API返回错误: %s\n", body)
return
}
var data WeatherData
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil {
fmt.Printf("解析JSON失败: %v\n", err)
return
}
// 输出结果
fmt.Printf("城市: %s\n", data.Name)
fmt.Printf("温度: %.1f°C\n", data.Main.Temp)
fmt.Printf("湿度: %d%%\n", data.Main.Humidity)
if len(data.Weather) > 0 {
fmt.Printf("天气状况: %s\n", data.Weather[0].Description)
}
}
关键说明
API选择:
- OpenWeatherMap:免费但有速率限制。
- 和风天气:国内服务,稳定性更好。
- AccuWeather:商业级精度。
参数调整:
units=metric
:温度单位为摄氏度。q=城市名
:支持城市名或经纬度(如lat=39.9&lon=116.4
)。
错误处理:
- 检查HTTP状态码(如404表示城市不存在)。
- API可能返回错误JSON,需解析错误字段。
扩展功能:
- 缓存结果以减少API调用。
- 使用协程并发请求多个城市。
如果需要国内高稳定性的服务,可以替换为和风天气的API(需注册开发者账号)。
内容由零声教学AI助手提供,问题来源于学员提问