rpc/server/server.go
crusader fda60823d6 ing
2017-11-01 15:17:32 +09:00

68 lines
1.2 KiB
Go

package server
import (
"log"
"net"
"git.loafle.net/commons_go/rpc/protocol"
"git.loafle.net/commons_go/server"
)
func New(sh ServerHandler) Server {
lsh := &serverHandlers{}
lsh.ServerHandler = sh
lsh.lsh = sh
s := server.NewServer(lsh)
return s
}
type serverHandlers struct {
server.ServerHandler
lsh ServerHandler
}
func (sh *serverHandlers) Handle(conn net.Conn, stopChan <-chan struct{}, doneChan chan<- struct{}) {
contentType := sh.lsh.GetContentType(conn)
codec, err := sh.lsh.getCodec(contentType)
if nil != err {
log.Printf("RPC Handle: %v", err)
doneChan <- struct{}{}
return
}
var codecReq protocol.ServerCodecRequest
Loop:
for {
sh.lsh.OnPreRead(conn)
// Create a new codec request.
codecReq, errNew := codec.NewRequest(conn)
if nil != errNew {
log.Printf("RPC Handle: %v", errNew)
doneChan <- struct{}{}
return
}
sh.lsh.OnPostRead(conn)
result, err := sh.lsh.invoke(codecReq)
if nil != err {
sh.lsh.OnPreWriteError(conn, err)
codecReq.WriteError(conn, 400, err)
sh.lsh.OnPostWriteError(conn, err)
} else {
sh.lsh.OnPreWriteResult(conn, result)
codecReq.WriteResponse(conn, result)
sh.lsh.OnPostWriteResult(conn, result)
}
select {
case <-stopChan:
return
default:
}
}
}