fix empty (no args) remote calls

This commit is contained in:
Umputun
2019-06-25 20:06:30 -05:00
parent b30492556f
commit f30937c55e
3 changed files with 28 additions and 3 deletions
+9 -2
View File
@@ -25,12 +25,19 @@ func (r *Client) Call(method string, args ...interface{}) (*Response, error) {
var b []byte
var err error
if len(args) == 1 && reflect.TypeOf(args[0]).Kind() == reflect.Struct {
switch {
case args == nil || len(args) == 0:
b, err = json.Marshal(Request{Method: method, ID: atomic.AddUint64(&r.id, 1)})
if err != nil {
return nil, errors.Wrapf(err, "marshaling failed for %s", method)
}
case len(args) == 1 && reflect.TypeOf(args[0]).Kind() == reflect.Struct:
b, err = json.Marshal(Request{Method: method, Params: args[0], ID: atomic.AddUint64(&r.id, 1)})
if err != nil {
return nil, errors.Wrapf(err, "marshaling failed for %s", method)
}
} else {
default:
b, err = json.Marshal(Request{Method: method, Params: args, ID: atomic.AddUint64(&r.id, 1)})
if err != nil {
return nil, errors.Wrapf(err, "marshaling failed for %s", method)
+12
View File
@@ -47,6 +47,18 @@ func TestClient_CallWithObject(t *testing.T) {
t.Logf("%v %T", res, res)
}
func TestClient_CallWithNoParams(t *testing.T) {
ts := testServer(t, `{"method":"test","id":1}`, `{"result":"12345"}`)
defer ts.Close()
c := Client{API: ts.URL, Client: http.Client{}}
resp, err := c.Call("test")
assert.NoError(t, err)
res := ""
err = json.Unmarshal(*resp.Result, &res)
assert.Equal(t, "12345", res)
t.Logf("%v %T", res, res)
}
func TestClient_CallError(t *testing.T) {
ts := testServer(t, `{"method":"test","params":[123,"abc"],"id":1}`, `{"error":"some error"}`)
defer ts.Close()
+7 -1
View File
@@ -129,7 +129,13 @@ func (s *Server) handler(w http.ResponseWriter, r *http.Request) {
rest.SendErrorJSON(w, r, http.StatusNotImplemented, errors.New("unsupported method"), req.Method, 0)
return
}
render.JSON(w, r, fn(req.ID, *req.Params))
params := json.RawMessage{}
if req.Params != nil {
params = *req.Params
}
render.JSON(w, r, fn(req.ID, params))
}
func (s *Server) basicAuth(h http.Handler) http.Handler {