-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
146 lines (127 loc) · 2.54 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
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
package govespa
import (
"context"
"io"
"net/http"
"net/url"
"strconv"
"time"
)
type VespaClient struct {
httpClient *http.Client
headers http.Header
baseUrl string
}
type NewClientParams struct {
HttpClient *http.Client
Headers http.Header
BaseUrl string
}
func NewClient(params NewClientParams) *VespaClient {
return &VespaClient{
httpClient: params.HttpClient,
headers: params.Headers,
baseUrl: params.BaseUrl,
}
}
func (v *VespaClient) Put(docId DocumentId) *Put {
p := &Put{
client: v,
id: docId,
fields: make(map[string]any),
}
return p
}
func (v *VespaClient) Update(docId DocumentId) *Update {
u := &Update{
client: v,
id: docId,
fields: make(map[string]map[string]any),
}
return u
}
func (v *VespaClient) Query() *Query {
s := &Query{
client: v,
variables: make(url.Values),
}
return s
}
func (v *VespaClient) Remove(docId DocumentId) *Remove {
r := &Remove{
client: v,
id: docId,
}
return r
}
func (v *VespaClient) Get(docId DocumentId) *Get {
g := &Get{
client: v,
id: docId,
}
return g
}
type executeRequestParams struct {
ctx context.Context
path string
query url.Values
headers http.Header
method string
body io.Reader
}
func (v *VespaClient) executeRequest(params executeRequestParams) (*http.Response, error) {
if params.ctx == nil {
params.ctx = context.Background()
}
reqUrl, err := url.JoinPath(v.baseUrl, params.path)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(params.ctx, params.method, reqUrl, params.body)
if err != nil {
return nil, err
}
if params.query != nil {
req.URL.RawQuery = params.query.Encode()
}
if params.headers != nil {
req.Header = params.headers
}
resp, err := v.httpClient.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
func (v *VespaClient) getBaseUrl() (*url.URL, error) {
u, err := url.Parse(v.baseUrl)
if err != nil {
return nil, err
}
return u, nil
}
type OperationalParams struct {
create bool
condition string
timeout time.Duration
route string
tracelevel uint8
}
func (params OperationalParams) getQuery() (q url.Values) {
if params.create {
q.Add("create", "true")
}
if params.condition != "" {
q.Add("condition", params.condition)
}
if params.timeout != 0 {
q.Add("timeout", strconv.FormatInt(params.timeout.Milliseconds(), 10))
}
if params.route != "" {
q.Add("route", params.route)
}
if params.tracelevel != 0 {
q.Add("tracelevel", strconv.FormatUint(uint64(params.tracelevel), 10))
}
return
}