rpc/server/server.go
crusader e35dbc4cce ing
2017-11-01 15:21:49 +09:00

68 lines
1.2 KiB
Go

package server
import (
"log"
"net"
"git.loafle.net/commons_go/server"
)
func New(sh ServerHandler) server.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
}
for {
sh.lsh.OnPreRead(conn)
// Create a new codec request.
codecReq, errNew := codec.NewRequest(conn)
if nil != errNew {
if sh.IsClientDisconnect(errNew) {
doneChan <- struct{}{}
return
}
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:
}
}
}