Golang天气API开发与展示教程
时间:2026-02-04 08:27:39 384浏览 收藏
在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《Golang实现天气API与信息展示》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!
答案:使用Golang开发天气服务需调用OpenWeatherMap API获取数据,定义WeatherResponse等结构体解析JSON响应,通过net/http实现HTTP客户端请求与API路由处理,支持查询城市实时天气并返回温度、湿度等信息,结合json.Unmarshal和json.NewEncoder完成数据编解码,最后可选添加前端页面通过AJAX请求后端接口展示结果,整体结构清晰且易于扩展。

用Golang开发一个天气信息展示与API服务,核心在于获取天气数据、设计简洁的API接口,并提供可扩展的结构。以下是实现思路和关键代码示例。
1. 明确功能需求
一个基础的天气服务通常包括以下功能:
- 根据城市名称查询实时天气
- 返回温度、湿度、风速、天气状况等基本信息
- 支持JSON格式API输出
- 可选:前端页面展示天气信息
我们可以通过调用第三方天气API(如OpenWeatherMap)来获取数据。
2. 获取天气数据(调用外部API)
使用net/http发送请求,encoding/json解析响应。
// weather.go
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
)
type Weather struct {
Main string `json:"main"`
Icon string `json:"icon"`
Description string `json:"description"`
}
type Main struct {
Temp float64 `json:"temp"`
Humidity int `json:"humidity"`
}
type Wind struct {
Speed float64 `json:"speed"`
}
type WeatherResponse struct {
Name string `json:"name"`
Weather []Weather `json:"weather"`
Main Main `json:"main"`
Wind Wind `json:"wind"`
}
定义HTTP客户端请求OpenWeatherMap:
func getWeather(city string) (*WeatherResponse, error) {
apiKey := "your_openweather_api_key"
url := fmt.Sprintf("http://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=metric", city, apiKey)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("城市未找到或API错误: %s", resp.Status)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var data WeatherResponse
err = json.Unmarshal(body, &data)
if err != nil {
return nil, err
}
return &data, nil
}
3. 构建RESTful API服务
使用net/http创建简单路由处理请求。
func weatherHandler(w http.ResponseWriter, r *http.Request) {
city := r.URL.Query().Get("city")
if city == "" {
http.Error(w, "缺少参数: city", http.StatusBadRequest)
return
}
weatherData, err := getWeather(city)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(weatherData)
}
启动服务器:
func main() {
http.HandleFunc("/weather", weatherHandler)
fmt.Println("服务启动在 :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
4. 可选:添加简单前端页面
创建静态HTML文件,通过AJAX调用后端API。
// 在main函数中注册静态资源
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
在static/index.html中添加表单和JS请求:
<input type="text" id="city" placeholder="输入城市">
<button onclick="fetchWeather()">查询</button>
<div id="result"></div>
<script>
function fetchWeather() {
const city = document.getElementById("city").value;
fetch(`/weather?city=${city}`)
.then(res => res.json())
.then(data => {
document.getElementById("result").innerHTML = `
<h3>${data.name}</h3>
<p>温度: ${data.main.temp}°C</p>
<p>天气: ${data.weather[0].description}</p>
<p>湿度: ${data.main.humidity}%</p>
`;
})
.catch(err => alert("查询失败:" + err.message));
}
</script>
确保目录结构:
├── main.go ├── static/ │ └── index.html
基本上就这些。你可以用Golang快速搭建一个轻量级天气服务,结构清晰,便于后续扩展缓存、数据库记录或支持更多城市。关键是理解HTTP请求处理、JSON编解码和第三方API集成方式。不复杂但容易忽略错误处理和用户输入验证,建议加上日志和参数校验提升健壮性。
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《Golang天气API开发与展示教程》文章吧,也可关注golang学习网公众号了解相关技术文章。
-
505 收藏
-
503 收藏
-
502 收藏
-
502 收藏
-
502 收藏
-
112 收藏
-
353 收藏
-
435 收藏
-
270 收藏
-
182 收藏
-
179 收藏
-
452 收藏
-
435 收藏
-
120 收藏
-
498 收藏
-
391 收藏
-
281 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习