rpc/handle.go

40 lines
769 B
Go
Raw Normal View History

2017-11-08 06:35:27 +00:00
package rpc
import (
"io"
"git.loafle.net/commons_go/rpc/protocol"
)
type Invoker func(codecReq protocol.ServerCodecRequest) (result interface{}, err error)
func Handle(sh ServerHandler, codec protocol.ServerCodec, r io.Reader, w io.Writer, invoker Invoker) error {
sh.OnPreRead(r)
// Create a new codec request.
codecReq, errNew := codec.NewRequest(r)
defer func() {
if nil != codecReq {
codecReq.Complete()
}
}()
if nil != errNew {
return errNew
}
sh.OnPostRead(r)
result, err := invoker(codecReq)
if nil != err {
sh.OnPreWriteError(w, err)
codecReq.WriteError(w, 400, err)
sh.OnPostWriteError(w, err)
} else {
sh.OnPreWriteResult(w, result)
codecReq.WriteResponse(w, result)
sh.OnPostWriteResult(w, result)
}
return nil
}