105 lines
2.2 KiB
Go
105 lines
2.2 KiB
Go
package server
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"os"
|
|
|
|
"github.com/joho/godotenv"
|
|
)
|
|
|
|
var apiKey string
|
|
|
|
func init() {
|
|
err := godotenv.Load()
|
|
if err != nil {
|
|
fmt.Println("Error loading .env file:", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
apiKey = os.Getenv("API_KEY")
|
|
|
|
if apiKey == "" {
|
|
fmt.Println("API_KEY environment variable not set.")
|
|
os.Exit(1)
|
|
}
|
|
}
|
|
|
|
type WeatherData struct {
|
|
Coord struct {
|
|
Lat float64 `json:"lat"`
|
|
Lon float64 `json:"lon"`
|
|
} `json:"coord"`
|
|
Weather []struct {
|
|
Description string `json:"description"`
|
|
Icon string `json:"icon"`
|
|
} `json:"weather"`
|
|
Main struct {
|
|
Temp float64 `json:"temp"`
|
|
FellsLike float64 `json:"fells_like"`
|
|
Preassure int `json:"preassure"`
|
|
Humidity int `json:"humidity"`
|
|
TempMin float64 `json:"temp_min"`
|
|
TempMax float64 `json:"temp_max"`
|
|
} `json:"main"`
|
|
Wind struct {
|
|
Speed float64 `json:"speed"`
|
|
Deg float64 `json:"deg"`
|
|
} `json:"wind"`
|
|
Clouds struct {
|
|
All int `json:"all"`
|
|
} `json:"clouds"`
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
func getWeather(city string) (WeatherData, error) {
|
|
url := fmt.Sprintf("http://api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=metric&lang=hr", city, apiKey)
|
|
|
|
resp, err := http.Get(url)
|
|
if err != nil {
|
|
return WeatherData{}, err
|
|
}
|
|
defer resp.Body.Close()
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return WeatherData{}, err
|
|
}
|
|
var weatherData WeatherData
|
|
err = json.Unmarshal(body, &weatherData)
|
|
if err != nil {
|
|
return WeatherData{}, err
|
|
}
|
|
return weatherData, nil
|
|
}
|
|
|
|
func WeatherHandler(w http.ResponseWriter, r *http.Request) {
|
|
cities := []string{"Sarajevo", "Banja Luka", "Zenica", "Tuzla", "Mostar"}
|
|
|
|
var weatherInfo []WeatherData
|
|
for _, city := range cities {
|
|
data, err := getWeather(city)
|
|
if err != nil {
|
|
fmt.Printf("Error fetching weather for %s: %v\n", city, err)
|
|
continue
|
|
}
|
|
weatherInfo = append(weatherInfo, data)
|
|
}
|
|
|
|
title := "Vremenska Prognoza"
|
|
data := map[string]interface{}{
|
|
"title": title,
|
|
"weatherInfo": weatherInfo,
|
|
"categories": CategoryMenu,
|
|
}
|
|
|
|
err := templates.ExecuteTemplate(w, "weatherHTML", data)
|
|
if err != nil {
|
|
fmt.Println("Error executing template:", err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
}
|
|
|
|
}
|