@@ -1,26 +0,0 @@
|
||||
package ctx // import "go.unistack.org/micro/v3/util/ctx"
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
// FromRequest creates context with metadata from http.Request
|
||||
func FromRequest(r *http.Request) context.Context {
|
||||
ctx := r.Context()
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
md = metadata.New(len(r.Header) + 2)
|
||||
}
|
||||
for key, val := range r.Header {
|
||||
md.Set(key, strings.Join(val, ","))
|
||||
}
|
||||
// pass http host
|
||||
md["Host"] = r.Host
|
||||
// pass http method
|
||||
md["Method"] = r.Method
|
||||
return metadata.NewIncomingContext(ctx, md)
|
||||
}
|
@@ -1,41 +0,0 @@
|
||||
package ctx
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"go.unistack.org/micro/v3/metadata"
|
||||
)
|
||||
|
||||
func TestRequestToContext(t *testing.T) {
|
||||
testData := []struct {
|
||||
request *http.Request
|
||||
expect metadata.Metadata
|
||||
}{
|
||||
{
|
||||
&http.Request{
|
||||
Header: http.Header{
|
||||
"Foo1": []string{"bar"},
|
||||
"Foo2": []string{"bar", "baz"},
|
||||
},
|
||||
},
|
||||
metadata.Metadata{
|
||||
"Foo1": "bar",
|
||||
"Foo2": "bar,baz",
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, d := range testData {
|
||||
ctx := FromRequest(d.request)
|
||||
md, ok := metadata.FromIncomingContext(ctx)
|
||||
if !ok {
|
||||
t.Fatalf("Expected metadata for request %+v", d.request)
|
||||
}
|
||||
for k, v := range d.expect {
|
||||
if val := md[k]; val != v {
|
||||
t.Fatalf("Expected %s for key %s for expected md %+v, got md %+v", v, k, d.expect, md)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user