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 ( import (
"bytes" "bytes"
"errors"
"fmt" "fmt"
"olznet.de/ssob" "olznet.de/ssob"
"reflect" "reflect"
@ -31,10 +32,12 @@ type responseHeader struct {
} }
type parseInputsFunc func(in []byte) (ret []reflect.Value) type parseInputsFunc func(in []byte) (ret []reflect.Value)
type parseOutputsFunc func(in []reflect.Value) (ret []byte)
type service struct { type service struct {
f reflect.Value f reflect.Value
fin parseInputsFunc fin parseInputsFunc
fout parseOutputsFunc
} }
type Server struct { type Server struct {
@ -48,6 +51,9 @@ func NewServer() *Server {
var DefaultServer = NewServer() var DefaultServer = NewServer()
func (server *Server) RegisterName(name string, rcvr interface{}) (err error) { 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) ft := reflect.TypeOf(rcvr)
fv := reflect.ValueOf(rcvr) fv := reflect.ValueOf(rcvr)
@ -56,7 +62,7 @@ func (server *Server) RegisterName(name string, rcvr interface{}) (err error) {
fs := service{} fs := service{}
f := func(in []byte) (ret []reflect.Value) { fs.fin = func(in []byte) (ret []reflect.Value) {
var b bytes.Buffer var b bytes.Buffer
if _, err = b.Write(in); err != nil { if _, err = b.Write(in); err != nil {
return nil return nil
@ -76,19 +82,53 @@ func (server *Server) RegisterName(name string, rcvr interface{}) (err error) {
return ret 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 fs.f = fv
server.serviceMap.Store(name, fs) server.serviceMap.Store(name, fs)
return nil 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) fs, _ := server.serviceMap.Load(name)
fmt.Printf("3. ") for _, a := range args {
fmt.Println(in) if err := encoder.Encode(a); err != nil {
inputs := fs.(service).fin(in) fmt.Println(err)
fmt.Println(inputs) return nil
fs.(service).f.Call(inputs) }
}
inputs := fs.(service).fin(b.Bytes())
outputs := fs.(service).f.Call(inputs)
return fs.(service).fout(outputs)
} }