-
Notifications
You must be signed in to change notification settings - Fork 0
/
locations.go
90 lines (69 loc) · 2.12 KB
/
locations.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
package turso
import (
"context"
"fmt"
"net/http"
)
type LocationsClient client
type LocationsResponse struct {
Locations map[string]string
}
type Location struct {
Code string `json:"code"`
Description string `json:"description"`
}
type LocationResponse struct {
Code string `json:"code"`
Description string `json:"description"`
Closest []Location
}
func (c *LocationsClient) List(ctx context.Context) (map[string]string, error) {
r, err := c.client.Get(ctx, "/v1/locations", nil)
if err != nil {
return nil, fmt.Errorf("failed to request locations: %s", err)
}
defer r.Body.Close()
if r.StatusCode != http.StatusOK {
return nil, fmt.Errorf("failed to get locations: %w", parseResponseError(r))
}
data, err := unmarshal[LocationsResponse](r)
if err != nil {
return nil, fmt.Errorf("failed to deserialize locations response: %w", err)
}
return data.Locations, nil
}
func (c *LocationsClient) Get(ctx context.Context, location string) (LocationResponse, error) {
r, err := c.client.Get(ctx, "/v1/locations/"+location, nil)
if err != nil {
return LocationResponse{}, fmt.Errorf("failed to request location %s: %w", location, err)
}
defer r.Body.Close()
if r.StatusCode != http.StatusOK {
return LocationResponse{}, fmt.Errorf("failed to get location %s: %s", location, r.Status)
}
data, err := unmarshal[struct {
Location LocationResponse `json:"location"`
}](r)
if err != nil {
return LocationResponse{}, fmt.Errorf("failed to deserialize location response: %w", err)
}
return data.Location, nil
}
type ClosestLocationResponse struct {
Server string
}
func (c *LocationsClient) Closest(ctx context.Context) (string, error) {
r, err := c.client.Get(ctx, "https://region.turso.io", nil)
if err != nil {
return "", fmt.Errorf("failed to request closest: %s", err)
}
defer r.Body.Close()
if r.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to get closest location: %w", parseResponseError(r))
}
data, err := unmarshal[ClosestLocationResponse](r)
if err != nil {
return "", fmt.Errorf("failed to deserialize locations response: %w", err)
}
return data.Server, nil
}