From 2fd55f11836bc4b4490421e336c79f3ceeaeaede Mon Sep 17 00:00:00 2001 From: Matthias Fulz Date: Wed, 6 Nov 2019 01:16:23 +0100 Subject: [PATCH] Basic handling of input and output arguments for registered functions --- server.go | 60 +++++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 50 insertions(+), 10 deletions(-) diff --git a/server.go b/server.go index 98770ae..dc99fa5 100644 --- a/server.go +++ b/server.go @@ -2,6 +2,7 @@ package srpc import ( "bytes" + "errors" "fmt" "olznet.de/ssob" "reflect" @@ -31,10 +32,12 @@ type responseHeader struct { } type parseInputsFunc func(in []byte) (ret []reflect.Value) +type parseOutputsFunc func(in []reflect.Value) (ret []byte) type service struct { - f reflect.Value - fin parseInputsFunc + f reflect.Value + fin parseInputsFunc + fout parseOutputsFunc } type Server struct { @@ -48,6 +51,9 @@ func NewServer() *Server { var DefaultServer = NewServer() func (server *Server) RegisterName(name string, rcvr interface{}) (err error) { + if _, ok := server.serviceMap.Load(name); ok { + return errors.New("srpc: Function with name '" + name + "' already registerd") + } ft := reflect.TypeOf(rcvr) fv := reflect.ValueOf(rcvr) @@ -56,7 +62,7 @@ func (server *Server) RegisterName(name string, rcvr interface{}) (err error) { fs := service{} - f := func(in []byte) (ret []reflect.Value) { + fs.fin = func(in []byte) (ret []reflect.Value) { var b bytes.Buffer if _, err = b.Write(in); err != nil { return nil @@ -76,19 +82,53 @@ func (server *Server) RegisterName(name string, rcvr interface{}) (err error) { return ret } - fs.fin = f + fs.fout = func(in []reflect.Value) (ret []byte) { + var b bytes.Buffer + encoder := ssob.NewEncoder(&b) + + for _, v := range in { + if v.Type() == reflect.TypeOf((*error)(nil)).Elem() { + if v.IsNil() { + if err := encoder.Encode(string("")); err != nil { + fmt.Println(err) + return nil + } + } else { + if err := encoder.Encode(v.Interface().(error).Error()); err != nil { + fmt.Println(err) + return nil + } + } + } else { + if err := encoder.Encode(v.Interface()); err != nil { + fmt.Println(err) + return nil + } + } + } + + return b.Bytes() + } + fs.f = fv server.serviceMap.Store(name, fs) return nil } -func (server *Server) CallName(name string, in []byte) { +func (server *Server) CallName(name string, args ...interface{}) (ret []byte) { + var b bytes.Buffer + encoder := ssob.NewEncoder(&b) + fs, _ := server.serviceMap.Load(name) - fmt.Printf("3. ") - fmt.Println(in) - inputs := fs.(service).fin(in) - fmt.Println(inputs) - fs.(service).f.Call(inputs) + for _, a := range args { + if err := encoder.Encode(a); err != nil { + fmt.Println(err) + return nil + } + } + inputs := fs.(service).fin(b.Bytes()) + outputs := fs.(service).f.Call(inputs) + return fs.(service).fout(outputs) }