-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeteo.go
398 lines (358 loc) · 10.3 KB
/
meteo.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
package meteo
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/http/httputil"
"os"
"strings"
"time"
"github.com/qba73/geonames"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
const (
libVersion = "0.0.1"
userAgent = "Meteo/" + libVersion + "https://github.com/qba73/meteo"
)
type forecastResponseCompact struct {
Type string `json:"type"`
Geometry struct {
Type string `json:"type"`
Coordinates []float64 `json:"coordinates"`
} `json:"geometry"`
Properties struct {
Meta struct {
UpdatedAt time.Time `json:"updated_at"`
Units struct {
AirPressureAtSeaLevel string `json:"air_pressure_at_sea_level"`
AirTemperature string `json:"air_temperature"`
CloudAreaFraction string `json:"cloud_area_fraction"`
PrecipitationAmount string `json:"precipitation_amount"`
RelativeHumidity string `json:"relative_humidity"`
WindFromDirection string `json:"wind_from_direction"`
WindSpeed string `json:"wind_speed"`
} `json:"units"`
} `json:"meta"`
Timeseries []struct {
Time time.Time `json:"time"`
Data struct {
Instant struct {
Details struct {
AirPressureAtSeaLevel float64 `json:"air_pressure_at_sea_level"`
AirTemperature float64 `json:"air_temperature"`
CloudAreaFraction float64 `json:"cloud_area_fraction"`
RelativeHumidity float64 `json:"relative_humidity"`
WindFromDirection float64 `json:"wind_from_direction"`
WindSpeed float64 `json:"wind_speed"`
} `json:"details"`
} `json:"instant"`
Next12Hours struct {
Summary struct {
SymbolCode string `json:"symbol_code"`
} `json:"summary"`
} `json:"next_12_hours"`
Next1Hours struct {
Summary struct {
SymbolCode string `json:"symbol_code"`
} `json:"summary"`
Details struct {
PrecipitationAmount float64 `json:"precipitation_amount"`
} `json:"details"`
} `json:"next_1_hours"`
Next6Hours struct {
Summary struct {
SymbolCode string `json:"symbol_code"`
} `json:"summary"`
Details struct {
PrecipitationAmount float64 `json:"precipitation_amount"`
} `json:"details"`
} `json:"next_6_hours"`
} `json:"data"`
} `json:"timeseries"`
} `json:"properties"`
}
type CurrentWeather struct {
UpdatedAt time.Time
Time time.Time
PressureAtSeaLevel float64
Temperature float64
Precipitation float64
}
type Forecast struct {
UpdatedAt time.Time
Hourly []HourlyForecast
}
type HourlyForecast struct {
Time time.Time
AirPressure float64 // in hPa
AirTemperature float64 // in Celsius
CloudAreaFraction float64 // in "%""
RelativeHumidity float64 // in "%"
WindFromDirection float64 // in "degrees"
WindSpeed float64 // in "m/s"
PrecipitationAmount float64 // in "mm"
Summary string
}
// Location represents geo coordinates.
type Location struct {
Lat float64
Long float64
}
func resolve(ctx context.Context, location string) (Location, error) {
geonamesUser := os.Getenv("GEONAMES_USER")
if geonamesUser == "" {
log.Fatal("Please set environmental variable GEONAMES_USER.")
}
resolver, err := geonames.NewClient(geonamesUser)
if err != nil {
return Location{}, err
}
place, country, err := toPlaceAndCountry(location)
if err != nil {
return Location{}, err
}
names, err := resolver.GetPlace(place, country, 1)
if err != nil {
return Location{}, err
}
if len(names) < 1 {
return Location{}, fmt.Errorf("unable to resolve location: place %s, country %s", place, country)
}
return Location{
Lat: names[0].Position.Lat,
Long: names[0].Position.Long,
}, nil
}
func toPlaceAndCountry(location string) (string, string, error) {
bits := strings.Split(location, ",")
if len(bits) < 2 {
return "", "", fmt.Errorf("parsing place and country from location %s", location)
}
return bits[0], bits[1], nil
}
func getSymbolDescription(symbol string) string {
symbols := map[string]string{
"rain": "rain",
"heavyrain": "heavy rain",
"lightrain": "light rain",
"cloudy": "cloudy",
"heavyrainshowers_night": "heavy rain showers",
"heavyrainshowers_day": "heavy rain showers",
"rainshowers_day": "rain showers",
"rainshowers_night": "rain showers",
"lightrainshowers_day": "light showers",
"lightrainshowers_night": "light showers",
"partlycloudy_day": "partly cloudy",
"partlycloudy_night": "partly cloudy",
"fair_day": "fair",
"fair_night": "fair",
"fog": "fog",
"clearsky_night": "clear sky",
"clearsky_day": "clear sky",
}
desc, ok := symbols[symbol]
if !ok {
return ""
}
return desc
}
func getEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
type option func(*Client) error
func WithUserAgent(ua string) option {
return func(c *Client) error {
if ua == "" {
return errors.New("nil user agent")
}
c.userAgent = ua
return nil
}
}
func WithBaseURL(u string) option {
return func(c *Client) error {
if u == "" {
return errors.New("nil base URL")
}
c.BaseURL = u
return nil
}
}
func WithHTTPClient(hc *http.Client) option {
return func(c *Client) error {
if hc == nil {
return errors.New("nil http client")
}
c.HTTPClient = hc
return nil
}
}
func WithResolver(rs func(context.Context, string) (Location, error)) option {
return func(c *Client) error {
c.Resolve = rs
return nil
}
}
// Client represents a weather client
// for the Norwegian Meteorological Institute.
type Client struct {
userAgent string
BaseURL string
HTTPClient *http.Client
Resolve func(context.Context, string) (Location, error)
Debug io.Writer
}
// NewClient knows how to construct a new default client.
func NewClient(opts ...option) (*Client, error) {
c := Client{
userAgent: userAgent,
BaseURL: getEnv("API_MET_URL", "https://api.met.no"),
HTTPClient: http.DefaultClient,
Resolve: resolve,
}
for _, opt := range opts {
if err := opt(&c); err != nil {
return nil, err
}
}
return &c, nil
}
// GetWeather returns current weather for given place.
//
// Place string should have format: "<place-name>,<country-code>",
// for example: "London,UK", "Dublin,IE", "Paris,FR", "Warsaw,PL".
func (c *Client) GetWeather(ctx context.Context, place string) (Weather, error) {
location, err := c.Resolve(ctx, place)
if err != nil {
return Weather{}, err
}
return c.weather(ctx, location)
}
// GetWeatherForCoordinates returns current weather for a place
// with given coordinates (lat, long)
func (c *Client) GetWeatherForCoordinates(ctx context.Context, lat, long float64) (Weather, error) {
l := Location{
Lat: lat,
Long: long,
}
return c.weather(ctx, l)
}
func (c *Client) weather(ctx context.Context, location Location) (Weather, error) {
u := fmt.Sprintf("%s/weatherapi/locationforecast/2.0/compact?lat=%.2f&lon=%.2f", c.BaseURL, location.Lat, location.Long)
var nf forecastResponseCompact
if err := c.get(ctx, u, &nf); err != nil {
return Weather{}, err
}
if len(nf.Properties.Timeseries) < 1 {
return Weather{}, fmt.Errorf("invalid response %+v", nf)
}
w := Weather{
Summary: getSymbolDescription(nf.Properties.Timeseries[0].Data.Next1Hours.Summary.SymbolCode),
Temp: nf.Properties.Timeseries[0].Data.Instant.Details.AirTemperature,
}
return w, nil
}
func (c *Client) forecast(ctx context.Context, location Location) (Forecast, error) {
u := fmt.Sprintf("%s/weatherapi/locationforecast/2.0/compact?lat=%.2f&lon=%.2f", c.BaseURL, location.Lat, location.Long)
var nf forecastResponseCompact
if err := c.get(ctx, u, &nf); err != nil {
return Forecast{}, err
}
if len(nf.Properties.Timeseries) < 1 {
return Forecast{}, fmt.Errorf("invalid response %+v", nf)
}
w := Forecast{
UpdatedAt: nf.Properties.Meta.UpdatedAt,
}
return w, nil
}
func (c *Client) get(ctx context.Context, url string, data any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("creating HTTP request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", c.userAgent)
if c.Debug != nil {
reqDump, err := httputil.DumpRequestOut(req, true)
if err != nil {
return fmt.Errorf("dumping HTTP request: %w", err)
}
fmt.Fprintln(c.Debug, string(reqDump))
fmt.Fprintln(c.Debug)
}
res, err := c.HTTPClient.Do(req)
if err != nil {
return fmt.Errorf("sending request: %w", err)
}
defer res.Body.Close()
if c.Debug != nil {
c.dumpResponse(res)
}
if res.StatusCode != http.StatusOK {
return fmt.Errorf("got response code: %v", res.StatusCode)
}
body, err := io.ReadAll(res.Body)
if err != nil {
return fmt.Errorf("reading response body: %w", err)
}
if err := json.Unmarshal(body, data); err != nil {
return fmt.Errorf("unmarshaling response body: %w", err)
}
return nil
}
// dumpResponse writes a raw response data to the debug
// output if set, or std error otherwise.
func (c *Client) dumpResponse(res *http.Response) {
resDump, _ := httputil.DumpResponse(res, true)
fmt.Fprintln(c.Debug, string(resDump))
fmt.Fprintln(c.Debug)
}
// Weather represents weather conditions
// in a geographical region.
type Weather struct {
Summary string
Temp float64
}
// String implements stringer interface.
func (w Weather) String() string {
return fmt.Sprintf("%s %.1f°C", cases.Title(language.English).String(w.Summary), w.Temp)
}
// GetWeather returns current weather for given
// place and country using default client.
func GetWeather(location string) (Weather, error) {
ctx := context.Background()
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
c, err := NewClient()
if err != nil {
return Weather{}, err
}
return c.GetWeather(ctx, location)
}
// RunCLI is a main function that runs the cli machinery.
func RunWeatherCLI() int {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "Usage: %s LOCATION\n\nExmple: %[1]s London,UK\n", os.Args[0])
return 1
}
location := strings.Join(os.Args[1:], " ")
w, err := GetWeather(location)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
fmt.Fprintln(os.Stdout, w)
return 0
}
func RunForecastCLI() int {
return 0
}