package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
)
const apikey = "GETYOUROWNAPIKEY"
func main() {
weather := Weather{}
weather.callWeatherAPI()
weather.renderWeather()
}
func (w *Weather) renderWeather() {
var description string
for _, v := range w.Weather {
description = v.Description
}
fmt.Printf("Currently in %v it is %v degrees with %v and %v percent humidity.\n",
w.Name, kelvinToFarenheit(w.Main.Temp), description, w.Main.Humidity)
}
func (w *Weather) callWeatherAPI() {
url := "http://api.openweathermap.org/data/2.5/weather?zip=78660,us&appid=" + apikey
req, _ := http.NewRequest("GET", url, nil)
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Println(err)
}
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
w.Body = body
json.Unmarshal(body, w)
}
func kelvinToFarenheit(k float64) string {
f := k - 273.15
f = f * 9 / 5
f = f + 32
return fmt.Sprintf("%.2f", f)
}
func utot(t int64) string {
tm := time.Unix(t, 0)
return tm.Format("Mon Jan 2 2006 15:04:05")
}
// Generated by https://quicktype.io
type Weather struct {
Coord Coord `json:"coord"`
Weather []WeatherElement `json:"weather"`
Base string `json:"base"`
Main Main `json:"main"`
Visibility int64 `json:"visibility"`
Wind Wind `json:"wind"`
Clouds Clouds `json:"clouds"`
Dt int64 `json:"dt"`
Sys Sys `json:"sys"`
Timezone int64 `json:"timezone"`
ID int64 `json:"id"`
Name string `json:"name"`
Cod int64 `json:"cod"`
Body []byte
}
type Clouds struct {
All int64 `json:"all"`
}
type Coord struct {
Lon float64 `json:"lon"`
Lat float64 `json:"lat"`
}
type Main struct {
Temp float64 `json:"temp"`
Pressure int64 `json:"pressure"`
Humidity int64 `json:"humidity"`
TempMin float64 `json:"temp_min"`
TempMax float64 `json:"temp_max"`
}
type Sys struct {
Type int64 `json:"type"`
ID int64 `json:"id"`
Country string `json:"country"`
Sunrise int64 `json:"sunrise"`
Sunset int64 `json:"sunset"`
}
type WeatherElement struct {
ID int64 `json:"id"`
Main string `json:"main"`
Description string `json:"description"`
Icon string `json:"icon"`
}
type Wind struct {
Speed float64 `json:"speed"`
Deg int64 `json:"deg"`
}
/*
{"coord":{"lon":-97.63,"lat":30.44},
"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],
"base":"stations","main":{"temp":283.59,"pressure":1020,"humidity":58,"temp_min":280.37,
"temp_max":285.93},"visibility":16093,"wind":{"speed":2.62,"deg":166},
"clouds":{"all":1},"dt":1573955856,"sys":{"type":1,"id":3344,"country":"US",
"sunrise":1573909033,"sunset":1573947214},"timezone":-21600,"id":0,
"name":"Pflugerville","cod":200}
*/