weather-cli/cmd/weather.go

61 lines
1.2 KiB
Go
Raw Permalink Normal View History

2022-07-07 23:43:16 -04:00
package main
2022-07-08 22:12:21 -04:00
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
)
2022-07-07 23:43:16 -04:00
2022-07-26 22:22:05 -04:00
// Get and store the current forecast
2022-08-02 23:26:28 -04:00
func getCurrent(app *Application) {
2022-07-07 23:43:16 -04:00
2022-07-08 22:12:21 -04:00
lat := "lat=" + app.Config.Latitude
lon := "&lon=" + app.Config.Longitude
units := "&units=" + app.Config.Units
key := "&appid=" + app.Config.ApiKey
2022-08-09 01:13:22 -04:00
url := "https://api.openweathermap.org/data/2.5/weather?" + lat + lon + units + key
2022-07-07 23:43:16 -04:00
res, err := http.Get(url)
if err != nil {
2022-08-09 01:13:22 -04:00
log.Printf("Error getting current forecast: %v", err)
}
defer res.Body.Close()
2022-09-03 00:43:43 -04:00
body, err := ioutil.ReadAll(res.Body)
if err != nil {
2022-08-09 01:13:22 -04:00
log.Printf("Error reading response from server: %v\n", err)
}
err = json.Unmarshal(body, &app.Forecast)
if err != nil {
2022-08-09 01:13:22 -04:00
log.Printf("Error reading JSON from server: %v\n", err)
}
}
// Query forecast by zip code
func getCurrentByLoc(app *Application) {
zip := app.Config.Location
units := "&units=" + app.Config.Units
key := "&appid=" + app.Config.ApiKey
2022-08-09 01:13:22 -04:00
url := "https://api.openweathermap.org/data/2.5/weather?q=" + zip + units + key
2022-07-08 22:12:21 -04:00
res, err := http.Get(url)
if err != nil {
log.Println(err)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Println(err)
}
err = json.Unmarshal(body, &app.Forecast)
if err != nil {
log.Println(err)
}
2022-07-07 23:43:16 -04:00
}