From cbc777005e2d344151ea5c1984a33ff7b262b79a Mon Sep 17 00:00:00 2001 From: siddharth Date: Sun, 15 May 2022 23:39:38 -0400 Subject: nws: add Forecast --- nws/nws.go | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) (limited to 'nws/nws.go') diff --git a/nws/nws.go b/nws/nws.go index a3155ab..b939d2a 100644 --- a/nws/nws.go +++ b/nws/nws.go @@ -24,6 +24,29 @@ type NWSPoint struct { Properties NWSPointProperties } +type NWSForecastPeriod struct { + Number int + Name string + StartTime string + EndTime string + IsDayTime bool + Temperature int + TemperatureUnit string + TemperatureTrend string + WindSpeed string + WindDirection string + ShortForecast string + DetailedForecast string +} + +type NWSForecastProperties struct { + Periods []NWSForecastPeriod +} + +type NWSForecast struct { + Properties NWSForecastProperties +} + type NWSError struct { Title string Type string @@ -74,3 +97,45 @@ func Points(lat, lng float32) (*NWSPoint, error) { return point, nil } +// NWS forecast endpoint. +func Forecast(point *NWSPoint) (*NWSForecast, error) { + if point == nil { + return nil, fmt.Errorf("forecast: point nil") + } + if len(point.Properties.Forecast) == 0 { + return nil, fmt.Errorf("forecast: link empty") + } + + // Get the forecast + resp, err := client.Get(point.Properties.Forecast) + if err != nil { + return nil, fmt.Errorf("forecast: get: %v", err) + } + + // Parse response body. + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, fmt.Errorf("forecast: body: %v", err) + } + + // Check if the request failed. + if resp.StatusCode != 200 { + perr := new(NWSError) + err := json.Unmarshal(body, perr) + if err != nil { + return nil, fmt.Errorf("forecast: json: %v", err) + } + return nil, fmt.Errorf("forecast: %v", perr) + } + + // Unmarshal. + forecast := new(NWSForecast) + err = json.Unmarshal(body, forecast) + if err != nil { + return nil, fmt.Errorf("forecast: decode: %v", err) + } + if len(forecast.Properties.Periods) == 0 { + return nil, fmt.Errorf("forecast: periods empty") + } + return forecast, nil +} -- cgit v1.2.3