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

用Golang开发一个天气信息展示与API服务,核心在于获取天气数据、设计简洁的API接口,并提供可扩展的结构。以下是实现思路和关键代码示例。
一个基础的天气服务通常包括以下功能:
我们可以通过调用第三方天气API(如OpenWeatherMap)来获取数据。
使用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
}
使用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))
}
创建静态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中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号