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

Golang开发天气信息展示与API服务

P粉602998670
发布: 2025-09-23 14:03:01
原创
187人浏览过
答案:使用Golang开发天气服务需调用OpenWeatherMap API获取数据,定义WeatherResponse等结构体解析JSON响应,通过net/http实现HTTP客户端请求与API路由处理,支持查询城市实时天气并返回温度、湿度等信息,结合json.Unmarshal和json.NewEncoder完成数据编解码,最后可选添加前端页面通过AJAX请求后端接口展示结果,整体结构清晰且易于扩展。

golang开发天气信息展示与api服务

用Golang开发一个天气信息展示与API服务,核心在于获取天气数据、设计简洁的API接口,并提供可扩展的结构。以下是实现思路和关键代码示例。

1. 明确功能需求

一个基础的天气服务通常包括以下功能:

  • 根据城市名称查询实时天气
  • 返回温度、湿度、风速、天气状况等基本信息
  • 支持JSON格式API输出
  • 可选:前端页面展示天气信息

我们可以通过调用第三方天气API(如OpenWeatherMap)来获取数据。

2. 获取天气数据(调用外部API)

使用net/http发送请求,encoding/json解析响应。

立即学习go语言免费学习笔记(深入)”;

// 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创建简单路由处理请求。

微信 WeLM
微信 WeLM

WeLM不是一个直接的对话机器人,而是一个补全用户输入信息的生成模型。

微信 WeLM33
查看详情 微信 WeLM
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服务的详细内容,更多请关注php中文网其它相关文章!

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

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

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

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