package http import ( "fmt" "net/http" "strings" "git.loafle.net/commons_go/rpc/server" ) type HTTPAdapter struct { http.Handler RPCServerHandler server.ServerHandler } func New(rpcServerHandler server.ServerHandler) *HTTPAdapter { return &HTTPAdapter{ RPCServerHandler: rpcServerHandler, } } // 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] } codec, err := a.RPCServerHandler.GetCodec(contentType) if nil != err { writeError(w, 415, "rpc: Unsupported Media Type "+contentType) return } if err := server.Handle(a.RPCServerHandler, codec, r.Body, w); nil != err { writeError(w, 500, err.Error()) return } } 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) }