2017-10-26 07:21:35 +00:00
|
|
|
package fasthttp
|
|
|
|
|
|
|
|
import (
|
2017-11-08 06:35:27 +00:00
|
|
|
"bytes"
|
2017-10-26 07:21:35 +00:00
|
|
|
"fmt"
|
|
|
|
"strings"
|
|
|
|
|
2017-11-08 06:35:27 +00:00
|
|
|
"git.loafle.net/commons_go/rpc/server"
|
2017-10-26 07:21:35 +00:00
|
|
|
"github.com/valyala/fasthttp"
|
|
|
|
)
|
|
|
|
|
|
|
|
type FastHTTPAdapter struct {
|
2017-11-08 06:35:27 +00:00
|
|
|
RPCServerHandler server.ServerHandler
|
|
|
|
}
|
|
|
|
|
|
|
|
func New(rpcServerHandler server.ServerHandler) *FastHTTPAdapter {
|
|
|
|
return &FastHTTPAdapter{
|
|
|
|
RPCServerHandler: rpcServerHandler,
|
|
|
|
}
|
2017-10-26 07:21:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (a *FastHTTPAdapter) FastHTTPHandler(ctx *fasthttp.RequestCtx) {
|
|
|
|
if !ctx.IsPost() {
|
2017-10-26 12:37:28 +00:00
|
|
|
writeError(ctx, 405, "rpc: POST method required, received "+string(ctx.Method()))
|
2017-10-26 07:21:35 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
contentType := string(ctx.Request.Header.ContentType())
|
|
|
|
idx := strings.Index(contentType, ";")
|
|
|
|
if idx != -1 {
|
|
|
|
contentType = contentType[:idx]
|
|
|
|
}
|
|
|
|
|
2017-11-08 06:35:27 +00:00
|
|
|
codec, err := a.RPCServerHandler.GetCodec(contentType)
|
|
|
|
if nil != err {
|
|
|
|
writeError(ctx, 415, "rpc: Unsupported Media Type "+contentType)
|
|
|
|
return
|
|
|
|
}
|
2017-10-26 07:21:35 +00:00
|
|
|
|
2017-11-08 06:35:27 +00:00
|
|
|
r := bytes.NewReader(ctx.PostBody())
|
2017-10-26 07:21:35 +00:00
|
|
|
|
2017-11-08 06:35:27 +00:00
|
|
|
if err := server.Handle(a.RPCServerHandler, codec, r, ctx); nil != err {
|
|
|
|
writeError(ctx, 500, err.Error())
|
|
|
|
return
|
|
|
|
}
|
2017-10-26 07:21:35 +00:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func writeError(ctx *fasthttp.RequestCtx, status int, msg string) {
|
|
|
|
ctx.SetStatusCode(status)
|
|
|
|
ctx.SetContentType("text/plain; charset=utf-8")
|
|
|
|
fmt.Fprint(ctx, msg)
|
|
|
|
}
|