答案:使用Golang通过OpenWeatherMap API获取天气数据,结合html/template渲染页面,实现动态展示。1. 调用API获取JSON格式天气信息;2. 定义Weather结构体解析数据;3. 创建HTML模板绑定数据字段;4. 编写HTTP处理器加载模板并返回响应;5. 启动服务器监听请求,支持城市参数;6. 可选添加meta或JS实现定时刷新。完整流程涵盖环境变量管理、错误处理与安全渲染,适合轻量级Web服务开发。

用 Golang 制作一个实时天气展示网页,核心在于后端获取天气数据、模板渲染和动态数据绑定。虽然 Golang 本身是后端语言,不能像前端框架那样“实时”更新页面,但结合模板引擎和 HTTP 服务,可以实现数据驱动的页面展示。下面通过实战步骤带你一步步完成。
要展示天气,先得有数据。你可以使用公开的天气 API,比如 OpenWeatherMap 或 心知天气 等。
以 OpenWeatherMap 为例:
https://api.openweathermap.org/data/2.5/weather?q=Beijing&appid=YOUR_API_KEY&units=metric
示例代码获取天气数据:
立即学习“go语言免费学习笔记(深入)”;
package main
<p>import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"text/template"
)</p><p>type Weather struct {
Name string <code>json:"name"</code>
Main struct {
Temp float64 <code>json:"temp"</code>
Humidity int <code>json:"humidity"</code>
} <code>json:"main"</code>
Weather []struct {
Description string <code>json:"description"</code>
} <code>json:"weather"</code>
}</p><p>func getWeather(city string) (*Weather, error) {
apiKey := os.Getenv("WEATHER_API_KEY") // 推荐用环境变量保存密钥
url := fmt.Sprintf("<a href="https://www.php.cn/link/34571ad4ab328f2e87f24657505a6a3e">https://www.php.cn/link/34571ad4ab328f2e87f24657505a6a3e</a>", city, apiKey)</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var weather Weather
err = json.Unmarshal(body, &weather)
if err != nil {
return nil, err
}
return &weather, nil}
Go 内置 html/template 包,支持安全地将数据注入 HTML。
创建一个简单的 HTML 模板文件 index.html:
<!DOCTYPE html>
<html>
<head>
<title>实时天气</title>
<meta charset="utf-8">
<style>
body { font-family: Arial, sans-serif; text-align: center; margin-top: 50px; }
.weather { background: #f0f8ff; padding: 30px; border-radius: 10px; display: inline-block; }
h1 { color: #333; }
p { font-size: 1.2em; color: #555; }
</style>
</head>
<body>
<div class="weather">
<h1>天气信息</h1>
<p>城市: <strong>{{.Name}}</strong></p>
<p>温度: <strong>{{.Main.Temp}}°C</strong></p>
<p>天气: {{.Weather.0.Description}}</p>
<p>湿度: {{.Main.Humidity}}%</p>
</div>
</body>
</html>
在 Go 中加载并渲染这个模板:
var tmpl = template.Must(template.ParseFiles("index.html"))
<p>func weatherHandler(w http.ResponseWriter, r *http.Request) {
city := r.URL.Query().Get("city")
if city == "" {
city = "Beijing" // 默认城市
}</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">weather, err := getWeather(city)
if err != nil {
http.Error(w, "无法获取天气数据", http.StatusInternalServerError)
return
}
tmpl.Execute(w, weather)}
在 main 函数中启动 HTTP 服务器:
func main() {
http.HandleFunc("/", weatherHandler)
fmt.Println("服务启动在 :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
运行前设置 API 密钥:
export WEATHER_API_KEY=your_actual_api_key go run main.go
浏览器访问:https://www.php.cn/link/0ca28c19a7db0b4d5e3f17829bbe29b8,即可看到对应城市的天气信息。
如果希望页面自动更新,可以在 HTML 中加入 JavaScript 定时刷新或使用 <meta http-equiv="refresh">。
例如在 <head> 中添加:
<meta http-equiv="refresh" content="30"> <!-- 每30秒刷新一次 -->
或者用 JS 更灵活控制:
<script>
setInterval(() => {
location.reload();
}, 30000);
</script>
这样就实现了“准实时”天气展示。
基本上就这些。Golang 负责获取数据和渲染模板,HTML 展示内容,简单高效。适合做轻量级天气服务或学习 Web 开发基础。不复杂但容易忽略细节,比如错误处理、API 限流、模板安全等,实际项目中要注意补全。
以上就是Golang 如何做一个实时天气展示网页_Golang 模板渲染与数据绑定实战的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号