Basic handling of input and output arguments for registered functions

This commit is contained in:
Matthias Fulz 2019-11-06 01:16:23 +01:00
parent 992cfd4220
commit 2fd55f1183
1 changed files with 50 additions and 10 deletions

View File

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