rpc/adapter/fasthttp/adapter.go

52 lines
1.0 KiB
Go
Raw Normal View History

2017-10-26 07:21:35 +00:00
package fasthttp
import (
"fmt"
"io"
"strings"
"git.loafle.net/commons_go/rpc"
"github.com/valyala/fasthttp"
)
type FastHTTPAdapter struct {
registry rpc.Registry
}
// FastHTTPHandler
func (a *FastHTTPAdapter) FastHTTPHandler(ctx *fasthttp.RequestCtx) {
if !ctx.IsPost() {
WriteError(ctx, 405, "rpc: POST method required, received "+r.Method)
return
}
contentType := string(ctx.Request.Header.ContentType())
idx := strings.Index(contentType, ";")
if idx != -1 {
contentType = contentType[:idx]
}
err := a.registry.Invoke(contentType, ctx.PostBody(), ctx, beforeWrite, afterWrite)
if nil != err {
WriteError(w, 400, err.Error())
}
}
func beforeWrite(w io.Writer) {
ctx := w.(*fasthttp.RequestCtx)
ctx.Response.Header.Set("x-content-type-options", "nosniff")
ctx.SetContentType("application/json; charset=utf-8")
}
func afterWrite(w io.Writer) {
}
func writeError(ctx *fasthttp.RequestCtx, status int, msg string) {
ctx.SetStatusCode(status)
ctx.SetContentType("text/plain; charset=utf-8")
fmt.Fprint(ctx, msg)
}