From 777ff5a09bc49ea59c77f86aa3d606794da89637 Mon Sep 17 00:00:00 2001 From: Gregory Eremin Date: Sat, 17 Oct 2015 01:08:14 +0300 Subject: [PATCH] Caller now accepts any unmarshal functions; JSON is used by default --- caller/caller.go | 15 +++++++++------ caller/caller_test.go | 6 +++++- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/caller/caller.go b/caller/caller.go index 70a787c..76584bd 100644 --- a/caller/caller.go +++ b/caller/caller.go @@ -12,8 +12,10 @@ import ( // Caller wraps a function and makes it ready to be dynamically called. type Caller struct { - fun reflect.Value - argtyp reflect.Type + // Unmarshaller is a BYOB unmarshaller function. By default it uses JSON. + Unmarshaller func(data []byte, v interface{}) error + fun reflect.Value + argtyp reflect.Type } var ( @@ -46,15 +48,16 @@ func New(fun interface{}) (c *Caller, err error) { } c = &Caller{ - fun: fval, - argtyp: ftyp.In(0), + Unmarshaller: json.Unmarshal, + fun: fval, + argtyp: ftyp.In(0), } return c, nil } // Call creates an instance of the Caller function's argument type, unmarshalls -// the JSON payload into it and dynamically calls the Caller function with this +// the payload into it and dynamically calls the Caller function with this // instance. func (c *Caller) Call(data []byte) error { val, err := c.unmarshal(data) @@ -68,7 +71,7 @@ func (c *Caller) Call(data []byte) error { func (c *Caller) unmarshal(data []byte) (val reflect.Value, err error) { val = c.newValue() - err = json.Unmarshal(data, val.Interface()) + err = c.Unmarshaller(data, val.Interface()) return } diff --git a/caller/caller_test.go b/caller/caller_test.go index 65a8a8b..bf74670 100644 --- a/caller/caller_test.go +++ b/caller/caller_test.go @@ -122,7 +122,11 @@ func captureStdoutAround(f func()) []byte { f() w.Close() - out, _ := ioutil.ReadAll(r) + out, err := ioutil.ReadAll(r) + if err != nil { + os.Stdout = origStdout + panic(err) + } r.Close() os.Stdout = origStdout