Go语言中通过get请求获取api.open-meteo.com网站的天气数据

Go语言中通过get请求获取api.open-meteo.com网站的天气数据

C++中使用cpp-httplib和nlohmann_json库实现http请求获取天气数据Nodejs通过get请求获取api.open-meteo.com网站的天气数据使用Java通过get请求获取api.open-meteo.com网站的天气数据Python中通过get请求获取api.open-meteo.com网站的天气数据C#中通过get请求获取api.open-meteo.com网站的天气数据,我们再使用Go语言实现对应功能。

以下是使用 Go 语言发送 HTTP GET 请求以获取 api.open-meteo.com 网站天气数据的示例代码:


示例代码

go 复制代码
package main

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

func getWeather() {
	// API URL 和查询参数
	baseURL := "http://api.open-meteo.com/v1/forecast"
	latitude := "37.8136"
	longitude := "144.9631"
	query := fmt.Sprintf("%s?latitude=%s&longitude=%s&current_weather=true", baseURL, latitude, longitude)

	// 发送 GET 请求
	resp, err := http.Get(query)
	if err != nil {
		fmt.Println("Error occurred while making the request:", err)
		return
	}
	defer resp.Body.Close()

	// 检查响应状态码
	if resp.StatusCode != http.StatusOK {
		fmt.Printf("Failed to retrieve data. Status code: %d\n", resp.StatusCode)
		return
	}

	// 读取响应数据
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}

	// 解析 JSON 数据
	var weatherData map[string]interface{}
	if err := json.Unmarshal(body, &weatherData); err != nil {
		fmt.Println("Error parsing JSON:", err)
		return
	}

	// 打印天气数据
	fmt.Println("Weather Data:")
	fmt.Println(weatherData)
}

func main() {
	getWeather()
}

说明

  1. HTTP GET 请求:

    • 使用 http.Get 发送 GET 请求。
    • 查询参数(纬度、经度等)通过 fmt.Sprintf 拼接到 URL 中。
  2. 响应处理:

    • 检查响应状态码是否为 200 OK
    • 使用 ioutil.ReadAll 读取响应体。
  3. JSON 解析:

    • 使用 encoding/json 包解析 JSON 数据。
    • 将 JSON 数据解析为 map[string]interface{},便于动态访问字段。
  4. 错误处理:

    • 捕获网络请求错误、响应读取错误和 JSON 解析错误。

运行代码

  1. 保存文件

    将代码保存为 get_weather_data.go

  2. 运行程序

    在终端中运行以下命令:

    bash 复制代码
    go run get_weather_data.go

示例输出

plaintext 复制代码
Weather Data:
map[latitude:37.8136 longitude:144.9631 generationtime_ms:0.123 utc_offset_seconds:0 timezone:GMT current_weather:map[temperature:20.5 windspeed:5.2 winddirection:180]]

注意事项

  1. JSON 数据访问:

    • 如果需要访问具体字段,可以使用类型断言。例如:

      go 复制代码
      currentWeather := weatherData["current_weather"].(map[string]interface{})
      temperature := currentWeather["temperature"].(float64)
      fmt.Printf("Current temperature: %.2f°C\n", temperature)
  2. 依赖管理:

    • Go 自带的 net/httpencoding/json 包已经足够处理 HTTP 请求和 JSON 数据解析,无需额外依赖。
  3. 网络连接:

    • 确保你的网络可以访问 http://api.open-meteo.com
  4. 扩展功能:

    • 如果需要发送 POST 请求或添加自定义头部,可以使用 http.NewRequesthttp.Client

示例扩展

如果需要打印当前温度,可以修改代码如下:

go 复制代码
currentWeather := weatherData["current_weather"].(map[string]interface{})
temperature := currentWeather["temperature"].(float64)
fmt.Printf("Current temperature: %.2f°C\n", temperature)
相关推荐
提笔忘字的帝国13 小时前
【教程】macOS 如何完全卸载 Java 开发环境
java·开发语言·macos
flysh0513 小时前
C# 架构设计:接口 vs 抽象类的深度选型指南
开发语言·c#
2501_9418824813 小时前
从灰度发布到流量切分的互联网工程语法控制与多语言实现实践思路随笔分享
java·开发语言
bkspiderx13 小时前
C++中的volatile:从原理到实践的全面解析
开发语言·c++·volatile
程序新视界14 小时前
为什么不建议基于Multi-Agent来构建Agent工程?
人工智能·后端·agent
沛沛老爹14 小时前
Java泛型擦除:原理、实践与应对策略
java·开发语言·人工智能·企业开发·发展趋势·技术原理
专注_每天进步一点点14 小时前
【java开发】写接口文档的札记
java·开发语言
代码方舟14 小时前
Java企业级实战:对接天远名下车辆数量查询API构建自动化风控中台
java·大数据·开发语言·自动化
flysh0514 小时前
C# 中类型转换与模式匹配核心概念
开发语言·c#
AC赳赳老秦14 小时前
Python 爬虫进阶:DeepSeek 优化反爬策略与动态数据解析逻辑
开发语言·hadoop·spring boot·爬虫·python·postgresql·deepseek