package server import ( "encoding/json" "fmt" "io/ioutil" "net/http" ) const apiKey = "abb35e21bdcbad6d1b00141a2b25cf5a" 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, } err := templates.ExecuteTemplate(w, "fullweatherHTML", data) if err != nil { fmt.Println("Error executing template:", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) } for _, info := range weatherInfo { widgetData := map[string]interface{}{ "Temperature": info.Main.Temp, "City": info.Name, } err := templates.ExecuteTemplate(w, "weatherwidgetHTML", widgetData) if err != nil { fmt.Println("Error executing template:", err) http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } } }