ZBLOG

golang获取天气

在 Golang 中获取天气数据通常需要调用第三方天气 API(如和风天气、OpenWeatherMap、高德地图API等)。以下是几种常见的实现方式:


1. 使用 HTTP 请求调用天气 API

(1) 示例:通过和风天气API获取数据

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

// 定义天气数据结构(根据API返回的JSON格式调整)
type WeatherResponse struct {
	Now struct {
		Temp      string `json:"temp"`
		FeelsLike string `json:"feelsLike"`
	} `json:"now"`
}

func main() {
	apiKey := "YOUR_API_KEY"       // 替换为你的API Key
	location := "101010100"         // 城市ID(参考和风天气文档)
	
	url := fmt.Sprintf("https://devapi.qweather.com/v7/weather/now?location=%s&key=%s", location, apiKey)
	
	resp, err := http.Get(url)
	if err != nil {
		fmt.Println("请求失败:", err)
		return
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	var weather WeatherResponse
	err = json.Unmarshal(body, &weather)
	if err != nil {
		fmt.Println("解析JSON失败:", err)
		return
	}

	fmt.Printf("当前温度: %s°C\n体感温度: %s°C\n", 
        weather.Now.Temp, 
        weather.Now.FeelsLike,
    )
}

(2) 其他常用天气API

  • OpenWeatherMap:
    
    url := fmt.Sprintf("http://api.openweathermap.org/data/2.5/weather?q=Beijing&appid=%s&units=metric", apiKey)
    
  • 高德地图API:
    需签名验证,参考官方文档

2. 使用现成的Go SDK

部分天气服务提供官方或社区维护的SDK:

# 例如安装和风天气的非官方SDK:
go get github.com/qwd/go-heweather

使用示例:

import "github.com/qwd/go-heweather"

client := heweather.NewClient("YOUR_KEY")
data, err := client.GetWeather("北京")
if err != nil {
    panic(err)
}
fmt.Println(data.Now.Temp)

3. 处理HTTPS与超时设置

建议为HTTP客户端添加超时限制:

client := &http.Client{
    Timeout: time.Second * 10, // 10秒超时
}
resp, err := client.Get(url)

4. 缓存优化

频繁调用API可能触发限流,可加入本地缓存(如Redis):

import "github.com/go-redis/redis/v8"

// 伪代码示例:优先从Redis读取缓存
val, err := redisClient.Get(ctx, "weather:beijing").Result()
if err == nil {
    fmt.Println("缓存数据:", val)
} else {
    // 调用API并写入缓存...
}

5. FAQ

  • Q: API返回的数据是乱码?
    检查响应头的编码,可能需要手动解码:

    body, _ := io.ReadAll(resp.Body)
    utf8Body, _ := simplifiedchinese.GB18030.NewDecoder().Bytes(body) // GBK转UTF-8
    
  • Q:如何免费获取API Key?
    多数服务提供免费额度(如和风天气开发者认证后免费1000次/日)。

如果需要完整的可运行代码或对接特定平台,可以提供更具体的需求方向!


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

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?