rpc/adapter/http/adapter.go
crusader 0c7808f8e3 ing
2017-10-26 16:21:35 +09:00

59 lines
1.1 KiB
Go

package http
import (
"fmt"
"io"
"net/http"
"strings"
"git.loafle.net/commons_go/rpc"
)
type HTTPAdapter struct {
registry rpc.Registry
}
func NewAdapter(registry rpc.Registry) *HTTPAdapter {
return &HTTPAdapter{
registry: registry,
}
}
// 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]
}
err := a.registry.Invoke(contentType, r.Body, w, beforeWrite, afterWrite)
r.Body.Close()
if nil != err {
writeError(w, 400, err.Error())
}
}
func beforeWrite(w io.Writer) {
writer := w.(http.ResponseWriter)
writer.Header().Set("x-content-type-options", "nosniff")
writer.Header().Set("Content-Type", "application/json; charset=utf-8")
}
func afterWrite(w io.Writer) {
}
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)
}