diff options
author | siddharth <s@ricketyspace.net> | 2022-05-15 23:39:38 -0400 |
---|---|---|
committer | siddharth <s@ricketyspace.net> | 2022-05-15 23:39:38 -0400 |
commit | cbc777005e2d344151ea5c1984a33ff7b262b79a (patch) | |
tree | e188052a255aeffeb915b1f066211662794a0df6 /nws/nws.go | |
parent | ceb8a50a802f3499a9e4a38940d7c001ce7d0004 (diff) |
nws: add Forecast
Diffstat (limited to 'nws/nws.go')
-rw-r--r-- | nws/nws.go | 65 |
1 files changed, 65 insertions, 0 deletions
@@ -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 +} |