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 <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2020-07-06 15:55:17 +03:00 committed by GitHub
parent 6f309dada3
commit 97ae2979ad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 24 deletions

View File

@ -5,7 +5,6 @@ import (
"encoding/json" "encoding/json"
"io" "io"
"net/http" "net/http"
"net/textproto"
"strconv" "strconv"
"strings" "strings"
@ -104,30 +103,11 @@ func (h *rpcHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// create context // create context
cx := ctx.FromRequest(r) 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 // set merged context to request
*r = *r.Clone(cx) *r = *r.Clone(cx)
// if stream we currently only support json // if stream we currently only support json
if isStream(r, service) { 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) serveWebsocket(cx, w, r, service, c)
return return
} }

View File

@ -3,16 +3,24 @@ package ctx
import ( import (
"context" "context"
"net/http" "net/http"
"net/textproto"
"strings" "strings"
"github.com/micro/go-micro/v2/metadata" "github.com/micro/go-micro/v2/metadata"
) )
func FromRequest(r *http.Request) context.Context { func FromRequest(r *http.Request) context.Context {
ctx := context.Background() ctx := r.Context()
md := make(metadata.Metadata) md, ok := metadata.FromContext(ctx)
for k, v := range r.Header { if !ok {
md[k] = strings.Join(v, ",") 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) return metadata.NewContext(ctx, md)
} }