要开发golang天气查询应用,核心在于处理http请求与解析api响应。1.选择openweathermap等api时,关注数据覆盖、免费额度和文档质量,并通过注册获取api密钥,避免硬编码敏感信息;2.使用net/http库发送get请求,配合http.client设置超时机制,检查状态码并用defer关闭响应体,确保资源不泄露;3.解析json需定义匹配结构体字段,利用json.unmarshal映射数据,注意大小写、可选字段及类型一致性问题,必要时手动处理复杂类型。
用Golang开发一个天气查询应用,核心就是搞定两件事:一是怎么跟外部的天气API说话(HTTP请求),二是怎么听懂它说的话(数据解析)。说白了,就是把远程服务的数据抓过来,然后按我们想要的方式展示出来。
构建一个Golang天气查询应用,我们得从获取第三方API数据和解析它们入手。这可不是什么高深莫测的事,但要做好,里头有些门道值得琢磨。
package main import ( "encoding/json" "fmt" "io" "net/http" "os" "time" ) // WeatherResponse 结构体定义,用于匹配OpenWeatherMap API的JSON响应 // 这里只取了部分关键字段,实际应用可能需要更多 type WeatherResponse struct { Weather []struct { Description string `json:"description"` Icon string `json:"icon"` } `json:"weather"` Main struct { Temp float64 `json:"temp"` FeelsLike float64 `json:"feels_like"` TempMin float64 `json:"temp_min"` TempMax float64 `json:"temp_max"` Humidity int `json:"humidity"` } `json:"main"` Name string `json:"name"` // 城市名称 Cod int `json:"cod"` // 状态码 } // getWeatherData 从OpenWeatherMap API获取天气数据 func getWeatherData(city string, apiKey string) (*WeatherResponse, error) { // 构建API请求URL // 确保API Key和城市名正确编码,这里简单处理 apiURL := fmt.Sprintf("http://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=metric&lang=zh_cn", city, apiKey) // 创建一个HTTP客户端,设置超时 client := &http.Client{Timeout: 10 * time.Second} // 发送GET请求 resp, err := client.Get(apiURL) if err != nil { return nil, fmt.Errorf("请求天气API失败: %w", err) } // 确保响应体被关闭,避免资源泄露 defer resp.Body.Close() // 检查HTTP状态码 if resp.StatusCode != http.StatusOK { // 尝试读取错误信息,如果API有返回的话 bodyBytes, _ := io.ReadAll(resp.Body) return nil, fmt.Errorf("API请求返回非成功状态码: %d, 响应: %s", resp.StatusCode, string(bodyBytes)) } // 读取响应体 bodyBytes, err := io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("读取API响应失败: %w", err) } // 解析JSON数据到WeatherResponse结构体 var weatherData WeatherResponse err = json.Unmarshal(bodyBytes, &weatherData) if err != nil { return nil, fmt.Errorf("解析JSON数据失败: %w", err) } // 检查API返回的内部状态码,有些API会在JSON中提供业务错误码 if weatherData.Cod != http.StatusOK { // OpenWeatherMap在城市未找到时Cod会是404 return nil, fmt.Errorf("API返回业务错误码: %d, 城市可能不存在", weatherData.Cod) } return &weatherData, nil } func main() { // 从环境变量获取API Key,这是更安全的做法 apiKey := os.Getenv("OPENWEATHER_API_KEY") if apiKey == "" { fmt.Println("错误:请设置环境变量 OPENWEATHER_API_KEY") fmt.Println("示例:export OPENWEATHER_API_KEY=你的API密钥") return } city := "Beijing" // 默认查询城市,也可以从命令行参数获取 // 尝试获取天气数据 weather, err := getWeatherData(city, apiKey) if err != nil { fmt.Printf("获取天气数据时发生错误: %v\n", err) return } // 打印天气信息 fmt.Printf("%s当前天气:\n", weather.Name) if len(weather.Weather) > 0 { fmt.Printf(" 描述: %s\n", weather.Weather[0].Description) } fmt.Printf(" 温度: %.1f°C (体感: %.1f°C)\n", weather.Main.Temp, weather.Main.FeelsLike) fmt.Printf(" 湿度: %d%%\n", weather.Main.Humidity) fmt.Printf(" 最高温: %.1f°C, 最低温: %.1f°C\n", weather.Main.TempMax, weather.Main.TempMin) }
选择一个合适的天气API,对我来说,首先看的是它的数据覆盖面和准确性,其次是免费额度是否够用,以及文档是否清晰。市面上可选的不少,比如OpenWeatherMap、AccuWeather、Weatherbit.io等等。我个人比较常用OpenWeatherMap,因为它有比较慷慨的免费层级,而且API接口相对直观。
立即学习“go语言免费学习笔记(深入)”;
获取API密钥的流程大同小异。以OpenWeatherMap为例,你得先去它官网注册一个账号。注册成功后,通常在你的用户Dashboard或者API Keys的页面就能找到你的专属密钥。这个密钥就是你访问他们数据服务的“通行证”。拿到密钥后,切记不要直接硬编码在代码里,那可是安全大忌。更好的做法是把它存在环境变量里,或者通过配置文件加载,这样代码和敏感信息就分开了。
在Golang里发送HTTP请求,
net/http
http.Get()
http.Client
http.Client
Timeout
处理API响应,我觉得最关键的是错误处理。网络请求本身就充满了不确定性。首先,要检查请求本身有没有出错,比如网络不通、域名解析失败之类的。接着,要看HTTP状态码,不是所有的200 OK都代表成功,有时候404、500这些错误码会告诉你服务器出了问题,或者请求的资源不存在。然后才是读取响应体,
io.ReadAll
defer resp.Body.Close()
JSON解析在Golang里,
encoding/json
json.Unmarshal
json:"json_key_name"
tag
处理复杂JSON时,嵌套结构体是家常便饭。比如天气API里,
main
main
WeatherResponse
weather
[]struct{}
我遇到过一些坑:
tag
omitempty
json.Unmarshal
json.Unmarshal
json.Unmarshaler
map[string]interface{}
以上就是怎样用Golang开发天气查询应用 调用第三方API获取数据解析的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号