-
Notifications
You must be signed in to change notification settings - Fork 5
/
client.go
76 lines (66 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
package jrpc
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"sync/atomic"
)
// Client implements remote engine and delegates all calls to remote http server
// if AuthUser and AuthPasswd defined will be used for basic auth in each call to server
type Client struct {
API string // URL to jrpc server with entrypoint, i.e. http://127.0.0.1:8080/command
Client http.Client // http client injected by user
AuthUser string // basic auth user name, should match Server.AuthUser, optional
AuthPasswd string // basic auth password, should match Server.AuthPasswd, optional
id uint64 // used with atomic to populate unique id to Request.ID
}
// Call remote server with given method and arguments.
// Empty args will be ignored, single arg will be marshaled as-us and multiple args marshaled as []interface{}.
// Returns Response and error. Note: Response has it's own Error field, but that onw controlled by server.
// Returned error represent client-level errors, like failed http call, failed marshaling and so on.
func (r *Client) Call(method string, args ...interface{}) (*Response, error) {
var b []byte
var err error
switch {
case len(args) == 0:
b, err = json.Marshal(Request{Method: method, ID: atomic.AddUint64(&r.id, 1)})
if err != nil {
return nil, fmt.Errorf("marshaling failed for %s: %w", method, err)
}
case len(args) == 1:
b, err = json.Marshal(Request{Method: method, Params: args[0], ID: atomic.AddUint64(&r.id, 1)})
if err != nil {
return nil, fmt.Errorf("marshaling failed for %s: %w", method, err)
}
default:
b, err = json.Marshal(Request{Method: method, Params: args, ID: atomic.AddUint64(&r.id, 1)})
if err != nil {
return nil, fmt.Errorf("marshaling failed for %s: %w", method, err)
}
}
req, err := http.NewRequest("POST", r.API, bytes.NewBuffer(b))
if err != nil {
return nil, fmt.Errorf("failed to make request for %s: %w", method, err)
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
if r.AuthUser != "" && r.AuthPasswd != "" {
req.SetBasicAuth(r.AuthUser, r.AuthPasswd)
}
resp, err := r.Client.Do(req)
if err != nil {
return nil, fmt.Errorf("remote call failed for %s: %w", method, err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("bad status %s for %s", resp.Status, method)
}
cr := Response{}
if err = json.NewDecoder(resp.Body).Decode(&cr); err != nil {
return nil, fmt.Errorf("failed to decode response for %s: %w", method, err)
}
if cr.Error != "" {
return nil, fmt.Errorf("%s", cr.Error)
}
return &cr, nil
}