-
Notifications
You must be signed in to change notification settings - Fork 2
/
client.go
74 lines (60 loc) · 1.63 KB
/
client.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
package functions
import (
"net/http"
"net/url"
)
type Client struct {
clientError error
session http.Client
clientTransport transport
}
type transport struct {
header http.Header
baseUrl url.URL
}
func (t transport) RoundTrip(request *http.Request) (*http.Response, error) {
for headerName, values := range t.header {
for _, val := range values {
request.Header.Add(headerName, val)
}
}
request.URL = t.baseUrl.ResolveReference(request.URL)
return http.DefaultTransport.RoundTrip(request)
}
// TokenAuth sets authorization headers for subsequent requests.
func (c *Client) TokenAuth(token string) *Client {
c.clientTransport.header.Set("Authorization", "Bearer "+token)
//c.clientTransport.header.Set("apikey", token)
return c
}
/*
NewClient constructs a new client given a URL to a functions-go instance
Usage:
client := functions.NewClient("https://abc.functions.supabase.co", "<service-token>", nil)
Inspired By Postgrest and storage-go.
*/
func NewClient(rawUrl string, token string, headers map[string]string) *Client {
baseURL, err := url.Parse(rawUrl)
if err != nil {
return &Client{
clientError: err,
}
}
t := transport{
header: http.Header{},
baseUrl: *baseURL,
}
c := Client{
session: http.Client{Transport: t},
clientTransport: t,
}
// Set required headers
c.clientTransport.header.Set("Accept", "application/json")
c.clientTransport.header.Set("Content-Type", "application/json")
c.clientTransport.header.Set("Authorization", "Bearer "+token)
// Optional headers [if exists]
for key, value := range headers {
c.clientTransport.header.Set(key, value)
}
return &c
}