-
Notifications
You must be signed in to change notification settings - Fork 0
/
get.go
101 lines (88 loc) · 1.76 KB
/
get.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
package govespa
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"strconv"
"time"
)
var ErrNoDoc = errors.New("no document found")
type Get struct {
client *VespaClient
iter scanner
ctx context.Context
params GetParameter
id DocumentId
}
type GetParameter struct {
cluster string
fieldSet string
timeout time.Duration
tracelevel uint8
}
type GetResponse struct {
PathId string `json:"pathId"`
Id string `json:"id"`
Fields map[string]any `json:"fields"`
}
func (g *Get) WithContext(c context.Context) *Get {
g.ctx = c
return g
}
func (r *Get) AddParameter(p GetParameter) *Get {
r.params = p
return r
}
func (g *Get) Exec(dest any) (GetResponse, error) {
res, err := g.fetch()
if err != nil {
return GetResponse{}, err
}
if len(res.Fields) == 0 {
return GetResponse{}, ErrNoDoc
}
i := scanner{
res: []map[string]any{res.Fields},
}
err = i.Get(dest)
if err != nil {
return GetResponse{}, fromError(err)
}
return res, nil
}
func (g *Get) fetch() (GetResponse, error) {
resp, err := g.client.executeRequest(executeRequestParams{
ctx: g.ctx,
path: g.id.toPath(),
query: g.params.getQuery(),
method: "GET",
body: nil,
})
if err != nil {
return GetResponse{}, err
}
defer resp.Body.Close()
res := new(GetResponse)
err = json.NewDecoder(resp.Body).Decode(res)
if err != nil {
return GetResponse{}, err
}
return *res, nil
}
func (p GetParameter) getQuery() (q url.Values) {
if p.cluster != "" {
q.Add("cluster", p.cluster)
}
if p.fieldSet != "" {
q.Add("fieldSet", p.fieldSet)
}
if p.timeout != 0 {
q.Add("timeout", fmt.Sprintf("%vs", p.timeout.Seconds()))
}
if p.tracelevel != 0 {
q.Add("tracelevel", strconv.FormatUint(uint64(p.tracelevel), 10))
}
return
}