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. // Caller wraps a function and makes it ready to be dynamically called.
type Caller struct { type Caller struct {
fun reflect.Value // Unmarshaller is a BYOB unmarshaller function. By default it uses JSON.
argtyp reflect.Type Unmarshaller func(data []byte, v interface{}) error
fun reflect.Value
argtyp reflect.Type
} }
var ( var (
@ -46,15 +48,16 @@ func New(fun interface{}) (c *Caller, err error) {
} }
c = &Caller{ c = &Caller{
fun: fval, Unmarshaller: json.Unmarshal,
argtyp: ftyp.In(0), fun: fval,
argtyp: ftyp.In(0),
} }
return c, nil return c, nil
} }
// Call creates an instance of the Caller function's argument type, unmarshalls // 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. // instance.
func (c *Caller) Call(data []byte) error { func (c *Caller) Call(data []byte) error {
val, err := c.unmarshal(data) 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) { func (c *Caller) unmarshal(data []byte) (val reflect.Value, err error) {
val = c.newValue() val = c.newValue()
err = json.Unmarshal(data, val.Interface()) err = c.Unmarshaller(data, val.Interface())
return return
} }

View File

@ -122,7 +122,11 @@ func captureStdoutAround(f func()) []byte {
f() f()
w.Close() w.Close()
out, _ := ioutil.ReadAll(r) out, err := ioutil.ReadAll(r)
if err != nil {
os.Stdout = origStdout
panic(err)
}
r.Close() r.Close()
os.Stdout = origStdout os.Stdout = origStdout