-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
76 lines (61 loc) · 1.8 KB
/
Copy pathclient.go
File metadata and controls
76 lines (61 loc) · 1.8 KB
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
package visualcrossing
import (
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
type Client struct {
client *http.Client
BaseURL string
APIKey string
}
const BASEURL = "https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline"
func NewClient(apiKey string) *Client {
return &Client{
client: http.DefaultClient,
APIKey: apiKey,
BaseURL: BASEURL,
}
}
func (c *Client) SetTimeout(to time.Duration) {
c.client.Timeout = to
}
func (c *Client) GetTimelineForecast(lat, lng string, t *time.Time, args Arguments) (forecast *Forecast, err error) {
return c.GetTimelineForecastCtx(context.Background(), lat, lng, t, args)
}
func (c *Client) GetTimelineForecastCtx(ctx context.Context, lat, lng string, t *time.Time, args Arguments) (forecast *Forecast, err error) {
path := fmt.Sprintf("%s,%s", lat, lng)
if t != nil {
path += fmt.Sprintf("/%d", t.Unix())
}
return c.GetCtx(ctx, path, args)
}
func (c *Client) GetCtx(ctx context.Context, path string, args Arguments) (*Forecast, error) {
var forecast Forecast
url := fmt.Sprintf("%s/%s", c.BaseURL, path)
args["key"] = c.APIKey
params := args.ToURLValues()
if len(params) > 0 {
url = fmt.Sprintf("%s?%s", url, params.Encode())
}
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
resp, err := c.client.Do(req.WithContext(ctx))
if err != nil {
return nil, fmt.Errorf("error requesting for /%s: %w", path, err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("api responded with %v", resp.StatusCode)
}
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&forecast)
if err != nil {
return nil, fmt.Errorf("error decoding response for /%s: %w", path, err)
}
return &forecast, nil
}