一个基于命令行的天气应用程序,使用 WeatherAPI.com 服务提供实时天气状况和天气预报。
## 主要功能
- 获取当前天气状况,包括:
- 温度
- 天气状况
- 湿度
- 风速和风向
- 查看3天天气预报,包括:
- 最高温和最低温
- 天气状况
- 最大风速
- 降水量
- 平均湿度
- 交互式菜单系统
- 支持随时切换城市
- 对无效城市名进行错误处理
### v1.0.0
- 首次发布
- 支持实时天气查询
- 支持三天天气预报
- 支持城市切换功能
结构

💻 主函数示例
func main() {
const apiKey = "89f887f2bc8241918bd114435250904"
var city string
fmt.Print("Enter city name: ")
city = readInput()
var weather *Weather
var err error
for {
weather, err = GetForecast(city, apiKey, 3) // 获取3天预报
if err != nil {
log.Printf("Error getting forecast: %v", err)
fmt.Print("Please enter a valid city name: ")
city = readInput()
continue
}
break
}
for {
showMenu()
choice := readInput()
switch choice {
case "1":
weather.ShowCurrentWeather()
case "2":
weather.ShowForecast()
case "3":
fmt.Print("Enter new city name: ")
city = readInput()
weather, err = GetForecast(city, apiKey, 3)
if err != nil {
log.Printf("Error getting forecast: %v\n", err)
continue
}
fmt.Printf("Changed to %s successfully!\n", city)
case "4":
fmt.Println("Thank you for using Weather Information System. Goodbye!")
return
default:
fmt.Println("Invalid choice. Please try again.")
}
}
}
GetForecast函数示例
func GetForecast(city string, apiKey string, days uint) (*Weather, error) {
url := fmt.Sprintf("http://api.weatherapi.com/v1/forecast.json?key=%s&q=%s&days=%d", apiKey, city, days)
res, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("HTTP request error: %v", err)
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API returned non-200 status code: %d", res.StatusCode)
}
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, fmt.Errorf("read response body error: %v", err)
}
var weather Weather
if err := json.Unmarshal(body, &weather); err != nil {
return nil, fmt.Errorf("JSON parsing error: %v", err)
}
return &weather, nil
}
使用示例

