2017-10-26 07:21:35 +00:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
|
2017-11-08 06:35:27 +00:00
|
|
|
"git.loafle.net/commons_go/rpc/server"
|
2017-10-26 07:21:35 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type HTTPAdapter struct {
|
2017-11-08 06:35:27 +00:00
|
|
|
http.Handler
|
|
|
|
RPCServerHandler server.ServerHandler
|
2017-10-26 07:21:35 +00:00
|
|
|
}
|
|
|
|
|
2017-11-08 06:35:27 +00:00
|
|
|
func New(rpcServerHandler server.ServerHandler) *HTTPAdapter {
|
2017-10-26 07:21:35 +00:00
|
|
|
return &HTTPAdapter{
|
2017-11-08 06:35:27 +00:00
|
|
|
RPCServerHandler: rpcServerHandler,
|
2017-10-26 07:21:35 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// ServeHTTP
|
|
|
|
func (a *HTTPAdapter) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if r.Method != "POST" {
|
|
|
|
writeError(w, 405, "rpc: POST method required, received "+r.Method)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
contentType := r.Header.Get("Content-Type")
|
|
|
|
idx := strings.Index(contentType, ";")
|
|
|
|
if idx != -1 {
|
|
|
|
contentType = contentType[:idx]
|
|
|
|
}
|
|
|
|
|
2017-11-08 06:35:27 +00:00
|
|
|
codec, err := a.RPCServerHandler.GetCodec(contentType)
|
2017-10-26 07:21:35 +00:00
|
|
|
if nil != err {
|
2017-11-08 06:35:27 +00:00
|
|
|
writeError(w, 415, "rpc: Unsupported Media Type "+contentType)
|
|
|
|
return
|
2017-10-26 07:21:35 +00:00
|
|
|
}
|
|
|
|
|
2017-11-08 06:35:27 +00:00
|
|
|
if err := server.Handle(a.RPCServerHandler, codec, r.Body, w); nil != err {
|
|
|
|
writeError(w, 500, err.Error())
|
|
|
|
return
|
|
|
|
}
|
2017-10-26 07:21:35 +00:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func writeError(w http.ResponseWriter, status int, msg string) {
|
|
|
|
w.WriteHeader(status)
|
|
|
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
|
|
|
fmt.Fprint(w, msg)
|
|
|
|
}
|