ZBLOG

GOLANG获取全世界的天气

在 Golang 中获取全世界的天气数据,通常需要调用支持全球覆盖的天气 API(如 OpenWeatherMap、AccuWeather、WeatherAPI 等)。以下是完整的实现方案:


1. 选择全球覆盖的天气API

API名称 免费额度 文档地址 特点
OpenWeatherMap 1,000次/天 https://openweathermap.org/api 全球覆盖,多语言支持
WeatherAPI 100万次/月 https://www.weatherapi.com/docs/ 天气预报+历史数据
AccuWeather 50次/天 https://developer.accuweather.com 商业级精度,需企业申请

2. 完整代码示例(以OpenWeatherMap为例)

(1) 安装依赖

go get github.com/imroc/req/v3  # 推荐的高性能HTTP客户端

(2) 实现代码

package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/imroc/req/v3"
)

// OpenWeatherMap返回的数据结构 (根据实际API调整)
type WeatherData struct {
	Coord struct {
		Lon float64 `json:"lon"`
		Lat float64 `json:"lat"`
	} `json:"coord"`
	Main struct {
		Temp      float64 `json:"temp"`
		FeelsLike float64 `json:"feels_like"`
	} `json:"main"`
	Name string `json:"name"` // 城市名
}

const (
	apiKey = "YOUR_API_KEY" // 替换为你的OpenWeatherMap Key
)

func GetGlobalWeather(city string) (*WeatherData, error) {
	client := req.C().
		SetTimeout(5 * time.Second).
        EnableDumpEachRequest() // Debug时可开启

    url := fmt.Sprintf("https://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=metric", city, apiKey)
    
	var weather WeatherData
	resp, err := client.R().
        SetHeader("Accept", "application/json").
        SetSuccessResult(&weather).
        Get(url)

	if err != nil {
	    return nil, fmt.Errorf("请求失败: %v", err)
    }
	if !resp.IsSuccessState() {
	    return nil, fmt.Errorf("API错误: %s", resp.String())
    }

	return &weather, nil
}

func main() {
	cities := []string{"London", "Tokyo", "New York", "Paris"}
	for _, city := range cities {
	    weather, err := GetGlobalWeather(city)
	    if err != nil {
	        log.Printf("[%s]获取失败: %v\n", city, err)
	        continue
	    }
	    fmt.Printf(
            "[%s] %.1f°C (体感%.1f°C) [坐标: %.2f,%.2f]\n",
            weather.Name,
            weather.Main.Temp,
            weather.Main.FeelsLike,
            weather.Coord.Lon,
            weather.Coord.Lat,
        )
    }
}

3. 关键功能扩展

(1) 按地理坐标查询

// 根据经纬度查询
url := fmt.Sprintf(
    "https://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&appid=%s",
    35.68, // Latitude 
    139.76, // Longitude 
    apiKey,
)

(2) JSON字段映射建议

使用在线工具快速生成结构体:
https://transform.tools/json-to-go

(3) HTTPS证书问题处理

如果遇到证书错误:

client := req.C().EnableInsecureSkipVerify()

4. API管理最佳实践

(1) API Key安全存储

避免硬编码在代码中:

// 从环境变量读取
apiKey := os.Getenv("OPENWEATHER_API_KEY")

启动时设置环境变量:

export OPENWEATHER_API_KEY=your_key && go run main.go

(2) Mock测试数据

本地开发时可模拟API响应:

func MockWeatherAPI() *req.MockTransport { 
	return req.NewMockTransport().
        Get("https://api.openweathermap.org*").
        RespondWith().
        BodyString(`{"coord":{"lon":139,"lat":35},"main":{"temp":25}}`)
}

5. FAQ解决方案

  • Q: API返回401 Unauthorized
    检查:

    1. API Key是否有效
    2. Key是否包含在URL参数中
  • Q:如何获取城市ID列表?
    下载OpenWeatherMap的城市列表JSON:
    http://bulk.openweathermap.org/sample/

如果需要对接其他特定API或优化性能(如并发请求),可以进一步讨论具体需求!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=24008

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?