rpc/server/server.go

68 lines
1.2 KiB
Go
Raw Normal View History

2017-10-31 09:25:44 +00:00
package server
import (
2017-11-01 06:17:32 +00:00
"log"
"net"
2017-10-31 09:25:44 +00:00
"git.loafle.net/commons_go/rpc/protocol"
2017-11-01 06:17:32 +00:00
"git.loafle.net/commons_go/server"
2017-10-31 09:25:44 +00:00
)
func New(sh ServerHandler) Server {
2017-11-01 06:17:32 +00:00
lsh := &serverHandlers{}
lsh.ServerHandler = sh
lsh.lsh = sh
s := server.NewServer(lsh)
2017-10-31 09:25:44 +00:00
2017-11-01 06:17:32 +00:00
return s
2017-10-31 09:25:44 +00:00
}
2017-11-01 06:17:32 +00:00
type serverHandlers struct {
server.ServerHandler
lsh ServerHandler
2017-10-31 09:25:44 +00:00
}
2017-11-01 06:17:32 +00:00
func (sh *serverHandlers) Handle(conn net.Conn, stopChan <-chan struct{}, doneChan chan<- struct{}) {
contentType := sh.lsh.GetContentType(conn)
codec, err := sh.lsh.getCodec(contentType)
2017-10-31 09:25:44 +00:00
if nil != err {
2017-11-01 06:17:32 +00:00
log.Printf("RPC Handle: %v", err)
doneChan <- struct{}{}
return
2017-10-31 09:25:44 +00:00
}
var codecReq protocol.ServerCodecRequest
2017-11-01 06:17:32 +00:00
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)
2017-10-31 09:25:44 +00:00
}
2017-11-01 06:17:32 +00:00
select {
case <-stopChan:
return
default:
}
2017-10-31 09:25:44 +00:00
}
}