首页 > 后端开发 > Golang > 正文

Golang 如何做一个实时天气展示网页_Golang 模板渲染与数据绑定实战

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

golang 如何做一个实时天气展示网页_golang 模板渲染与数据绑定实战

用 Golang 制作一个实时天气展示网页,核心在于后端获取天气数据、模板渲染和动态数据绑定。虽然 Golang 本身是后端语言,不能像前端框架那样“实时”更新页面,但结合模板引擎和 HTTP 服务,可以实现数据驱动的页面展示。下面通过实战步骤带你一步步完成。

1. 获取实时天气数据

要展示天气,先得有数据。你可以使用公开的天气 API,比如 OpenWeatherMap心知天气 等。

以 OpenWeatherMap 为例:

  • 注册账号并获取 API Key
  • 调用接口:https://api.openweathermap.org/data/2.5/weather?q=Beijing&appid=YOUR_API_KEY&units=metric
  • 返回 JSON 格式的数据,包含温度、天气描述、湿度等

示例代码获取天气数据:

立即学习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
登录后复制

}

2. 使用 Go 模板渲染 HTML 页面

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)
登录后复制

}

3. 启动 Web 服务并访问页面

main 函数中启动 HTTP 服务器:

Supercreator
Supercreator

AI视频创作编辑器,几分钟内从构思到创作。

Supercreator 80
查看详情 Supercreator
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,即可看到对应城市的天气信息。

4. 实现“准实时”刷新(可选)

如果希望页面自动更新,可以在 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中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号