-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathclient.go
More file actions
150 lines (131 loc) · 3.5 KB
/
client.go
File metadata and controls
150 lines (131 loc) · 3.5 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
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
// Package goplaces provides a Go client for the Google Places API (New).
package goplaces
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// DefaultBaseURL is the default endpoint for the Places API (New).
const DefaultBaseURL = "https://places.googleapis.com/v1"
// Client wraps access to the Google Places API.
type Client struct {
apiKey string
baseURL string
routesBaseURL string
directionsBaseURL string
httpClient *http.Client
}
// Options configures the Places client.
type Options struct {
APIKey string
BaseURL string
RoutesBaseURL string
DirectionsBaseURL string
HTTPClient *http.Client
Timeout time.Duration
}
// NewClient builds a client with sane defaults.
func NewClient(opts Options) *Client {
baseURL := strings.TrimRight(opts.BaseURL, "/")
if baseURL == "" {
baseURL = DefaultBaseURL
}
routesBaseURL := strings.TrimRight(opts.RoutesBaseURL, "/")
if routesBaseURL == "" {
routesBaseURL = defaultRoutesBaseURL
}
directionsBaseURL := strings.TrimRight(opts.DirectionsBaseURL, "/")
if directionsBaseURL == "" {
directionsBaseURL = defaultDirectionsBaseURL
}
client := opts.HTTPClient
if client == nil {
timeout := opts.Timeout
if timeout == 0 {
timeout = 10 * time.Second
}
client = &http.Client{Timeout: timeout}
}
return &Client{
apiKey: opts.APIKey,
baseURL: baseURL,
routesBaseURL: routesBaseURL,
directionsBaseURL: directionsBaseURL,
httpClient: client,
}
}
func (c *Client) doRequest(
ctx context.Context,
method string,
endpoint string,
body any,
fieldMask string,
) ([]byte, error) {
if strings.TrimSpace(c.apiKey) == "" {
return nil, ErrMissingAPIKey
}
var reader io.Reader
if body != nil {
payload, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("goplaces: encode request: %w", err)
}
reader = bytes.NewReader(payload)
}
request, err := http.NewRequestWithContext(ctx, method, endpoint, reader)
if err != nil {
return nil, fmt.Errorf("goplaces: build request: %w", err)
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("X-Goog-Api-Key", c.apiKey)
// Field masks trim API payloads and keep responses fast/cheap.
if strings.TrimSpace(fieldMask) != "" {
request.Header.Set("X-Goog-FieldMask", fieldMask)
}
response, err := c.httpClient.Do(request)
if err != nil {
return nil, fmt.Errorf("goplaces: request failed: %w", err)
}
defer func() {
_ = response.Body.Close()
}()
// Hard-cap payload size to avoid runaway error bodies.
payload, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
if err != nil {
return nil, fmt.Errorf("goplaces: read response: %w", err)
}
if response.StatusCode >= http.StatusBadRequest {
apiErr := &APIError{StatusCode: response.StatusCode, Body: strings.TrimSpace(string(payload))}
return nil, apiErr
}
if len(payload) == 0 {
return nil, errors.New("goplaces: empty response")
}
return payload, nil
}
func (c *Client) buildURL(path string, query map[string]string) (string, error) {
endpoint := c.baseURL + path
if len(query) == 0 {
return endpoint, nil
}
parsed, err := url.Parse(endpoint)
if err != nil {
return "", fmt.Errorf("goplaces: invalid url: %w", err)
}
values := parsed.Query()
for key, value := range query {
if strings.TrimSpace(value) == "" {
continue
}
values.Set(key, value)
}
parsed.RawQuery = values.Encode()
return parsed.String(), nil
}