答案:使用Golang开发天气服务需调用OpenWeatherMap API获取数据,定义WeatherResponse等结构体解析JSON响应,通过net/http实现HTTP客户端请求与API路由处理,支持查询城市实时天气并返回温度、湿度等信息,结合json.Unmarshal和json.NewEncoder完成数据编解码,最后可选添加前端页面通过AJAX请求后端接口展示结果,整体结构清晰且易于扩展。
用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创建简单路由处理请求。
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集成方式。不复杂但容易忽略错误处理和用户输入验证,建议加上日志和参数校验提升健壮性。
html js 前端 json ajax go golang app usb 后端 ai 路由 win golang restful json ajax html Static 结构体 接口 JS 数据库 http