55 lines
1.1 KiB
Go
55 lines
1.1 KiB
Go
package openWeatherMap
|
|
|
|
import (
|
|
"ArinDash/config"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
)
|
|
|
|
const apiBaseURL = "https://api.openweathermap.org/data/2.5/weather"
|
|
|
|
type configFile struct {
|
|
OpenWeatherMap openWeatherMapConfig
|
|
}
|
|
|
|
type openWeatherMapConfig struct {
|
|
LocationId string
|
|
ApiKey string
|
|
}
|
|
|
|
func FetchCurrentWeather() CurrentWeather {
|
|
cfg := &configFile{}
|
|
config.LoadConfig(cfg)
|
|
client := &http.Client{}
|
|
currentWeather := &CurrentWeather{}
|
|
if cfg.OpenWeatherMap.ApiKey == "" {
|
|
return CurrentWeather{
|
|
ErrorMessage: "No API key provided",
|
|
}
|
|
}
|
|
|
|
req, err := http.NewRequest("GET", apiBaseURL+"?id="+cfg.OpenWeatherMap.LocationId+"&units=metric&lang=en&APPID="+cfg.OpenWeatherMap.ApiKey, nil)
|
|
if err != nil {
|
|
return CurrentWeather{
|
|
ErrorMessage: err.Error(),
|
|
}
|
|
}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return CurrentWeather{
|
|
ErrorMessage: err.Error(),
|
|
}
|
|
}
|
|
defer resp.Body.Close()
|
|
respBody, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return CurrentWeather{
|
|
ErrorMessage: err.Error(),
|
|
}
|
|
}
|
|
|
|
err = json.Unmarshal(respBody, currentWeather)
|
|
return *currentWeather
|
|
}
|