登录
首页 >  Golang >  Go教程

Golang实现天气API与数据展示

时间:2026-04-10 18:50:24 120浏览 收藏

本文详细介绍了如何使用Golang快速构建一个轻量级、结构清晰且易于扩展的天气信息API服务:通过调用OpenWeatherMap第三方API获取实时天气数据,利用net/http发起HTTP请求并处理响应,借助encoding/json完成JSON数据的解析与序列化,定义精准的结构体(如WeatherResponse)映射API返回字段,并搭建RESTful路由接口支持按城市名查询温度、湿度、风速及天气状况等核心信息;同时可选集成简洁前端页面,通过AJAX调用后端接口实现动态展示,整个实现兼顾实用性与工程规范,是学习Go网络编程与API开发的理想实践范例。

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

用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学习网公众号!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>