srpc/server.go

95 lines
1.5 KiB
Go

package srpc
import (
"bytes"
"fmt"
"olznet.de/ssob"
"reflect"
"sync"
)
type argumentType uint8
const (
AIN argumentType = 0
AOUT argumentType = 1
AINOUT argumentType = 2
)
type responseStatus uint8
const (
OK responseStatus = 0
ERR responseStatus = 1
)
var RESPONSE_HEADER_SIZE = int32(9)
type responseHeader struct {
size int64
status responseStatus
}
type parseInputsFunc func(in []byte) (ret []reflect.Value)
type service struct {
f reflect.Value
fin parseInputsFunc
}
type Server struct {
serviceMap sync.Map
}
func NewServer() *Server {
return &Server{}
}
var DefaultServer = NewServer()
func (server *Server) RegisterName(name string, rcvr interface{}) (err error) {
ft := reflect.TypeOf(rcvr)
fv := reflect.ValueOf(rcvr)
nIn := ft.NumIn()
//nOut := ft.NumOut()
fs := service{}
f := func(in []byte) (ret []reflect.Value) {
var b bytes.Buffer
if _, err = b.Write(in); err != nil {
return nil
}
decoder := ssob.NewDecoder(&b)
ret = make([]reflect.Value, nIn)
for i := 0; i < nIn; i++ {
in := reflect.New(ft.In(i))
if err = decoder.Decode(in.Interface()); err != nil {
fmt.Println(err)
return nil
}
ret[i] = reflect.Indirect(in)
}
return ret
}
fs.fin = f
fs.f = fv
server.serviceMap.Store(name, fs)
return nil
}
func (server *Server) CallName(name string, in []byte) {
fs, _ := server.serviceMap.Load(name)
fmt.Printf("3. ")
fmt.Println(in)
inputs := fs.(service).fin(in)
fmt.Println(inputs)
fs.(service).f.Call(inputs)
}