Last active
January 15, 2024 18:46
-
-
Save kkroesch/75041db6eb3ddc3970c061a332291a17 to your computer and use it in GitHub Desktop.
Get Weather Data from Open Weather Map.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"net/http" | |
"os" | |
"time" | |
) | |
type WeatherData struct { | |
Weather []struct { | |
Description string `json: "description"` | |
} `json: "weather"` | |
Main struct { | |
Temp float64 `json: "temp"` | |
Pressure uint16 `json: "pressure"` | |
} `json: "main` | |
} | |
func fetchWeather(lat float64, lon float64) WeatherData { | |
var data WeatherData | |
api_key, hasApiKey := os.LookupEnv("WEATHERMAP_API_KEY") | |
if !hasApiKey { | |
panic("No API key.") | |
} | |
url := "https://api.openweathermap.org/data/2.5/weather?lat=%2.1f&lon=%3.1f&appid=%s" | |
url = fmt.Sprintf(url, lat, lon, api_key) | |
resp, err := http.Get(url) | |
if err != nil { | |
fmt.Println("Cannot get weather: ", err) | |
return data | |
} | |
defer resp.Body.Close() | |
if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { | |
fmt.Println("Cannot get weather: ", err) | |
return data | |
} | |
return data | |
} | |
func main() { | |
startNow := time.Now() | |
lat, lon := 47.4, 7.9 | |
data := fetchWeather(lat, lon) | |
fmt.Printf("%s, %2.1f°C\n", data.Weather[0].Description, data.Main.Temp-273) | |
fmt.Println("Took: ", time.Since(startNow)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment