rpc/server_handlers.go

87 lines
1.8 KiB
Go
Raw Normal View History

2017-11-08 06:35:27 +00:00
package rpc
import (
"fmt"
"io"
"strings"
"git.loafle.net/commons_go/rpc/protocol"
)
2017-11-15 05:45:08 +00:00
func NewServerHandler() ServerHandler {
sh := &ServerHandlers{}
return sh
}
2017-11-08 06:35:27 +00:00
type ServerHandlers struct {
codecs map[string]protocol.ServerCodec
}
2017-11-15 05:45:08 +00:00
func (sh *ServerHandlers) Init() error {
return nil
}
func (sh *ServerHandlers) OnStart() {
// no op
2017-11-08 06:35:27 +00:00
}
func (sh *ServerHandlers) OnPreRead(r io.Reader) {
// no op
}
func (sh *ServerHandlers) OnPostRead(r io.Reader) {
// no op
}
func (sh *ServerHandlers) OnPreWriteResult(w io.Writer, result interface{}) {
// no op
}
func (sh *ServerHandlers) OnPostWriteResult(w io.Writer, result interface{}) {
// no op
}
func (sh *ServerHandlers) OnPreWriteError(w io.Writer, err error) {
// no op
}
func (sh *ServerHandlers) OnPostWriteError(w io.Writer, err error) {
// no op
}
2017-11-15 05:45:08 +00:00
func (sh *ServerHandlers) OnStop() {
// no op
}
2017-11-08 06:35:27 +00:00
func (sh *ServerHandlers) Validate() {
}
2017-11-15 05:45:08 +00:00
// RegisterCodec adds a new codec to the server.
//
// Codecs are defined to process a given serialization scheme, e.g., JSON or
// XML. A codec is chosen based on the "Content-Type" header from the request,
// excluding the charset definition.
func (sh *ServerHandlers) RegisterCodec(codec protocol.ServerCodec, contentType string) {
if nil == sh.codecs {
sh.codecs = make(map[string]protocol.ServerCodec)
}
sh.codecs[strings.ToLower(contentType)] = codec
}
2017-11-08 06:35:27 +00:00
func (sh *ServerHandlers) GetCodec(contentType string) (protocol.ServerCodec, error) {
var codec protocol.ServerCodec
if contentType == "" && len(sh.codecs) == 1 {
// If Content-Type is not set and only one codec has been registered,
// then default to that codec.
for _, c := range sh.codecs {
codec = c
}
} else if codec = sh.codecs[strings.ToLower(contentType)]; codec == nil {
return nil, fmt.Errorf("Unrecognized Content-Type: %s", contentType)
}
return codec, nil
}