1
0
Fork 0

Caller now accepts any unmarshal functions; JSON is used by default

This commit is contained in:
Gregory Eremin 2015-10-17 01:08:14 +03:00
parent d0ff12ce64
commit 777ff5a09b
2 changed files with 14 additions and 7 deletions

View File

@ -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
}

View File

@ -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