From 97ae2979ad621fc291f10e8e2ad630daf963abab Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Mon, 6 Jul 2020 15:55:17 +0300 Subject: [PATCH] pass request context from request rpc endpoints (#1799) http middleware can add additional metadata to context, for example tracing wrappers, pass down it to underlining services Signed-off-by: Vasiliy Tolstov --- api/handler/rpc/rpc.go | 20 -------------------- util/ctx/ctx.go | 16 ++++++++++++---- 2 files changed, 12 insertions(+), 24 deletions(-) diff --git a/api/handler/rpc/rpc.go b/api/handler/rpc/rpc.go index 7e8790c2..fb326375 100644 --- a/api/handler/rpc/rpc.go +++ b/api/handler/rpc/rpc.go @@ -5,7 +5,6 @@ import ( "encoding/json" "io" "net/http" - "net/textproto" "strconv" "strings" @@ -104,30 +103,11 @@ func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { // create context cx := ctx.FromRequest(r) - // get context from http handler wrappers - md, ok := metadata.FromContext(r.Context()) - if !ok { - md = make(metadata.Metadata) - } - // fill contex with http headers - md["Host"] = r.Host - md["Method"] = r.Method - // get canonical headers - for k, _ := range r.Header { - // may be need to get all values for key like r.Header.Values() provide in go 1.14 - md[textproto.CanonicalMIMEHeaderKey(k)] = r.Header.Get(k) - } - - // merge context with overwrite - cx = metadata.MergeContext(cx, md, true) // set merged context to request *r = *r.Clone(cx) // if stream we currently only support json if isStream(r, service) { - // drop older context as it can have timeouts and create new - // md, _ := metadata.FromContext(cx) - //serveWebsocket(context.TODO(), w, r, service, c) serveWebsocket(cx, w, r, service, c) return } diff --git a/util/ctx/ctx.go b/util/ctx/ctx.go index 939a6587..019c6a2f 100644 --- a/util/ctx/ctx.go +++ b/util/ctx/ctx.go @@ -3,16 +3,24 @@ package ctx import ( "context" "net/http" + "net/textproto" "strings" "github.com/micro/go-micro/v2/metadata" ) func FromRequest(r *http.Request) context.Context { - ctx := context.Background() - md := make(metadata.Metadata) - for k, v := range r.Header { - md[k] = strings.Join(v, ",") + ctx := r.Context() + md, ok := metadata.FromContext(ctx) + if !ok { + md = make(metadata.Metadata) } + for k, v := range r.Header { + md[textproto.CanonicalMIMEHeaderKey(k)] = strings.Join(v, ",") + } + // pass http host + md["Host"] = r.Host + // pass http method + md["Method"] = r.Method return metadata.NewContext(ctx, md) }