rpc/gateway/server_handlers.go

68 lines
1.4 KiB
Go
Raw Normal View History

2017-11-02 06:39:30 +00:00
package gateway
import (
"log"
"net"
"git.loafle.net/commons_go/server"
)
type ServerHandlers struct {
server.ServerHandlers
RPCGetewayHandler RPCGetewayHandler
}
func (sh *ServerHandlers) Handle(conn net.Conn, stopChan <-chan struct{}, doneChan chan<- struct{}) {
contentType := sh.RPCGetewayHandler.GetContentType(conn)
codec, err := sh.RPCGetewayHandler.GetCodec(contentType)
if nil != err {
log.Printf("RPC Handle: %v", err)
doneChan <- struct{}{}
return
}
for {
sh.RPCGetewayHandler.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.RPCGetewayHandler.OnPostRead(conn)
result, err := sh.RPCGetewayHandler.Handle(codecReq)
if nil != err {
sh.RPCGetewayHandler.OnPreWriteError(conn, err)
codecReq.WriteError(conn, 400, err)
sh.RPCGetewayHandler.OnPostWriteError(conn, err)
} else {
sh.RPCGetewayHandler.OnPreWriteResult(conn, result)
codecReq.WriteResponse(conn, result)
sh.RPCGetewayHandler.OnPostWriteResult(conn, result)
}
select {
case <-stopChan:
return
default:
}
}
}
func (sh *ServerHandlers) Validate() {
sh.ServerHandlers.Validate()
if nil == sh.RPCGetewayHandler {
panic("RPCGetewayHandler must be specified.")
}
}