• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang metadata.FromContext函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中google/golang.org/grpc/metadata.FromContext函数的典型用法代码示例。如果您正苦于以下问题:Golang FromContext函数的具体用法?Golang FromContext怎么用?Golang FromContext使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了FromContext函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Status

func (s *testMetaServer) Status(ctx context.Context, _ *pbtypes.Void) (*ServerStatus, error) {
	md, _ := metadata.FromContext(ctx)
	if want, got := md["want-access-token"], md["authorization"]; got != want {
		return nil, grpc.Errorf(codes.Unknown, "got access-token %q, want %q", got, want)
	}
	return &ServerStatus{}, nil
}
开发者ID:alexsaveliev,项目名称:go-sourcegraph,代码行数:7,代码来源:context_test.go


示例2: ListSubscriptions

// ListSubscriptions lists matching subscriptions.
func (c *SubscriberClient) ListSubscriptions(ctx context.Context, req *pubsubpb.ListSubscriptionsRequest) *SubscriptionIterator {
	md, _ := metadata.FromContext(ctx)
	ctx = metadata.NewContext(ctx, metadata.Join(md, c.metadata))
	it := &SubscriptionIterator{}
	it.InternalFetch = func(pageSize int, pageToken string) ([]*pubsubpb.Subscription, string, error) {
		var resp *pubsubpb.ListSubscriptionsResponse
		req.PageToken = pageToken
		if pageSize > math.MaxInt32 {
			req.PageSize = math.MaxInt32
		} else {
			req.PageSize = int32(pageSize)
		}
		err := gax.Invoke(ctx, func(ctx context.Context) error {
			var err error
			resp, err = c.subscriberClient.ListSubscriptions(ctx, req)
			return err
		}, c.CallOptions.ListSubscriptions...)
		if err != nil {
			return nil, "", err
		}
		return resp.Subscriptions, resp.NextPageToken, nil
	}
	fetch := func(pageSize int, pageToken string) (string, error) {
		items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
		if err != nil {
			return "", err
		}
		it.items = append(it.items, items...)
		return nextPageToken, nil
	}
	it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
	return it
}
开发者ID:GoogleCloudPlatform,项目名称:gcloud-golang,代码行数:34,代码来源:subscriber_client.go


示例3: NewRaftProxyHealthServer

func NewRaftProxyHealthServer(local HealthServer, connSelector raftpicker.Interface, cluster raftpicker.RaftCluster, ctxMod func(context.Context) (context.Context, error)) HealthServer {
	redirectChecker := func(ctx context.Context) (context.Context, error) {
		s, ok := transport.StreamFromContext(ctx)
		if !ok {
			return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context")
		}
		addr := s.ServerTransport().RemoteAddr().String()
		md, ok := metadata.FromContext(ctx)
		if ok && len(md["redirect"]) != 0 {
			return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"])
		}
		if !ok {
			md = metadata.New(map[string]string{})
		}
		md["redirect"] = append(md["redirect"], addr)
		return metadata.NewContext(ctx, md), nil
	}
	mods := []func(context.Context) (context.Context, error){redirectChecker}
	mods = append(mods, ctxMod)

	return &raftProxyHealthServer{
		local:        local,
		cluster:      cluster,
		connSelector: connSelector,
		ctxMods:      mods,
	}
}
开发者ID:HuKeping,项目名称:docker,代码行数:27,代码来源:health.pb.go


示例4: newStreamInterceptor

func newStreamInterceptor(s *etcdserver.EtcdServer) grpc.StreamServerInterceptor {
	smap := monitorLeader(s)

	return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
		if !api.IsCapabilityEnabled(api.V3rpcCapability) {
			return rpctypes.ErrGRPCNotCapable
		}

		md, ok := metadata.FromContext(ss.Context())
		if ok {
			if ks := md[rpctypes.MetadataRequireLeaderKey]; len(ks) > 0 && ks[0] == rpctypes.MetadataHasLeader {
				if s.Leader() == types.ID(raft.None) {
					return rpctypes.ErrGRPCNoLeader
				}

				cctx, cancel := context.WithCancel(ss.Context())
				ss = serverStreamWithCtx{ctx: cctx, cancel: &cancel, ServerStream: ss}

				smap.mu.Lock()
				smap.streams[ss] = struct{}{}
				smap.mu.Unlock()

				defer func() {
					smap.mu.Lock()
					delete(smap.streams, ss)
					smap.mu.Unlock()
					cancel()
				}()

			}
		}
		return metricsStreamInterceptor(srv, ss, info, handler)
	}
}
开发者ID:mqliang,项目名称:etcd,代码行数:34,代码来源:interceptor.go


示例5: getGRPCTraceID

func getGRPCTraceID(ctx context.Context) (string, error) {

	md, ok := metadata.FromContext(ctx)
	if !ok {
		id, err := uuid.NewV4()
		if err != nil {
			return "", err
		}
		return id.String(), nil
	}

	tokens := md["trace"]
	if len(tokens) == 0 {
		id, err := uuid.NewV4()
		if err != nil {
			return "", err
		}
		return id.String(), nil
	}

	if tokens[0] != "" {
		return tokens[0], nil
	}

	id, err := uuid.NewV4()
	if err != nil {
		return "", err
	}
	return id.String(), nil
}
开发者ID:clawio,项目名称:service-localfs-prop,代码行数:30,代码来源:utils.go


示例6: MetadataFromContext

func MetadataFromContext(ctx context.Context) (metadata.MD, error) {
	md, ok := metadata.FromContext(ctx)
	if !ok {
		return md, ErrContext
	}
	return md, nil
}
开发者ID:TheThingsNetwork,项目名称:ttn,代码行数:7,代码来源:metadata.go


示例7: TestAnnotateContext_ForwardsGrpcMetadata

func TestAnnotateContext_ForwardsGrpcMetadata(t *testing.T) {
	ctx := context.Background()
	request, err := http.NewRequest("GET", "http://www.example.com", nil)
	if err != nil {
		t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://www.example.com", err)
	}
	request.Header.Add("Some-Irrelevant-Header", "some value")
	request.Header.Add("Grpc-Metadata-FooBar", "Value1")
	request.Header.Add("Grpc-Metadata-Foo-BAZ", "Value2")
	request.Header.Add("Grpc-Metadata-foo-bAz", "Value3")
	request.Header.Add("Authorization", "Token 1234567890")
	annotated, err := runtime.AnnotateContext(ctx, request)
	if err != nil {
		t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err)
		return
	}
	md, ok := metadata.FromContext(annotated)
	if got, want := len(md), emptyForwardMetaCount+3; !ok || got != want {
		t.Errorf("Expected %d metadata items in context; got %d", got, want)
	}
	if got, want := md["foobar"], []string{"Value1"}; !reflect.DeepEqual(got, want) {
		t.Errorf(`md["foobar"] = %q; want %q`, got, want)
	}
	if got, want := md["foo-baz"], []string{"Value2", "Value3"}; !reflect.DeepEqual(got, want) {
		t.Errorf(`md["foo-baz"] = %q want %q`, got, want)
	}
	if got, want := md["authorization"], []string{"Token 1234567890"}; !reflect.DeepEqual(got, want) {
		t.Errorf(`md["authorization"] = %q want %q`, got, want)
	}
}
开发者ID:kubernetes,项目名称:dashboard,代码行数:30,代码来源:context_test.go


示例8: LogRPCWithFields

// LogRPCWithFields will feed any request context into a logrus Entry.
func LogRPCWithFields(log *logrus.Logger, ctx context.Context) *logrus.Entry {
	md, ok := metadata.FromContext(ctx)
	if !ok {
		return logrus.NewEntry(log)
	}
	return log.WithFields(MetadataToFields(md))
}
开发者ID:pugong,项目名称:gizmo,代码行数:8,代码来源:rpc_server.go


示例9: NewRaftProxyResourceAllocatorServer

func NewRaftProxyResourceAllocatorServer(local ResourceAllocatorServer, connSelector raftselector.ConnProvider, localCtxMod, remoteCtxMod func(context.Context) (context.Context, error)) ResourceAllocatorServer {
	redirectChecker := func(ctx context.Context) (context.Context, error) {
		s, ok := transport.StreamFromContext(ctx)
		if !ok {
			return ctx, grpc.Errorf(codes.InvalidArgument, "remote addr is not found in context")
		}
		addr := s.ServerTransport().RemoteAddr().String()
		md, ok := metadata.FromContext(ctx)
		if ok && len(md["redirect"]) != 0 {
			return ctx, grpc.Errorf(codes.ResourceExhausted, "more than one redirect to leader from: %s", md["redirect"])
		}
		if !ok {
			md = metadata.New(map[string]string{})
		}
		md["redirect"] = append(md["redirect"], addr)
		return metadata.NewContext(ctx, md), nil
	}
	remoteMods := []func(context.Context) (context.Context, error){redirectChecker}
	remoteMods = append(remoteMods, remoteCtxMod)

	var localMods []func(context.Context) (context.Context, error)
	if localCtxMod != nil {
		localMods = []func(context.Context) (context.Context, error){localCtxMod}
	}

	return &raftProxyResourceAllocatorServer{
		local:         local,
		connSelector:  connSelector,
		localCtxMods:  localMods,
		remoteCtxMods: remoteMods,
	}
}
开发者ID:docker,项目名称:docker,代码行数:32,代码来源:resource.pb.go


示例10: UnaryCall

func (s *testServer) UnaryCall(ctx context.Context, in *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
	md, ok := metadata.FromContext(ctx)
	if ok {
		if err := grpc.SendHeader(ctx, md); err != nil {
			grpclog.Fatalf("grpc.SendHeader(%v, %v) = %v, want %v", ctx, md, err, nil)
		}
		grpc.SetTrailer(ctx, md)
	}
	if s.security != "" {
		// Check Auth info
		authInfo, ok := credentials.FromContext(ctx)
		if !ok {
			grpclog.Fatalf("Failed to get AuthInfo from ctx.")
		}
		var authType string
		switch info := authInfo.(type) {
		case credentials.TLSInfo:
			authType = info.AuthType()
		default:
			grpclog.Fatalf("Unknown AuthInfo type")
		}
		if authType != s.security {
			grpclog.Fatalf("Wrong auth type: got %q, want %q", authType, s.security)
		}
	}

	// Simulate some service delay.
	time.Sleep(time.Second)
	return &testpb.SimpleResponse{
		Payload: newPayload(in.GetResponseType(), in.GetResponseSize()),
	}, nil
}
开发者ID:johnmccawley,项目名称:origin,代码行数:32,代码来源:end2end_test.go


示例11: GetRatePlans

func (c Client) GetRatePlans(ctx context.Context, hotelIDs []int32, inDate string, outDate string) RatePlanReply {
	md, _ := metadata.FromContext(ctx)

	trace.Req(md["traceID"], md["from"], "service.rate", "GetRatePlans")
	defer trace.Rep(md["traceID"], "service.rate", md["from"], time.Now())

	args := &pb.Args{
		HotelIds: hotelIDs,
		InDate:   inDate,
		OutDate:  outDate,
	}

	reply, err := c.client.GetRates(ctx, args)

	if err != nil {
		return RatePlanReply{
			RatePlans: []*pb.RatePlan{},
			Err:       err,
		}
	}

	return RatePlanReply{
		RatePlans: reply.RatePlans,
		Err:       nil,
	}
}
开发者ID:beauhoyt,项目名称:go-micro-services,代码行数:26,代码来源:client.go


示例12: ValidateContext

func (s *networkServerRPC) ValidateContext(ctx context.Context) error {
	md, ok := metadata.FromContext(ctx)
	if !ok {
		return errors.NewErrInternal("Could not get metadata from context")
	}
	var id, token string
	if ids, ok := md["id"]; ok && len(ids) == 1 {
		id = ids[0]
	}
	if id == "" {
		return errors.NewErrInvalidArgument("Metadata", "id missing")
	}
	if tokens, ok := md["token"]; ok && len(tokens) == 1 {
		token = tokens[0]
	}
	if token == "" {
		return errors.NewErrInvalidArgument("Metadata", "token missing")
	}
	var claims *jwt.StandardClaims
	claims, err := security.ValidateJWT(token, []byte(s.networkServer.(*networkServer).Identity.PublicKey))
	if err != nil {
		return err
	}
	if claims.Subject != id {
		return errors.NewErrInvalidArgument("Metadata", "token was issued for a different component id")
	}
	return nil
}
开发者ID:TheThingsNetwork,项目名称:ttn,代码行数:28,代码来源:server.go


示例13: List

func (s *_ABitOfEverythingServer) List(_ *empty.Empty, stream examples.StreamService_ListServer) error {
	s.m.Lock()
	defer s.m.Unlock()

	err := stream.SendHeader(metadata.New(map[string]string{
		"count": fmt.Sprintf("%d", len(s.v)),
	}))
	if err != nil {
		return nil
	}

	for _, msg := range s.v {
		if err := stream.Send(msg); err != nil {
			return err
		}
	}

	// return error when metadata includes error header
	if header, ok := metadata.FromContext(stream.Context()); ok {
		if v, ok := header["error"]; ok {
			stream.SetTrailer(metadata.New(map[string]string{
				"foo": "foo2",
				"bar": "bar2",
			}))
			return grpc.Errorf(codes.InvalidArgument, "error metadata: %v", v)
		}
	}
	return nil
}
开发者ID:tmc,项目名称:grpc-gateway,代码行数:29,代码来源:a_bit_of_everything.go


示例14: isForwardedRequest

func isForwardedRequest(ctx context.Context) bool {
	md, _ := metadata.FromContext(ctx)
	if len(md[certForwardedKey]) != 1 {
		return false
	}
	return md[certForwardedKey][0] == "true"
}
开发者ID:Chandra-TechPassionate,项目名称:docker,代码行数:7,代码来源:forward.go


示例15: VerifiedIdentityFromContext

// Reads the OIDC JWT passed in the context and verifies it using the given OIDC client.
// Returns the verified identity on success, error otherwise.
func VerifiedIdentityFromContext(client *gooidc.Client, ctx context.Context) (*gooidc.Identity, error) {
	md, ok := metadata.FromContext(ctx)
	if !ok {
		return nil, errors.New("missing RPC credentials")
	}
	rawJWT, ok := md["jwt"]
	if !ok {
		return nil, errors.New("missing OIDC credentials")
	}
	if len(rawJWT) != 1 {
		return nil, errors.New("incorrect JWT data sent")
	}
	jwt, err := jose.ParseJWT(rawJWT[0])
	if err != nil {
		return nil, err
	}
	if err := client.VerifyJWT(jwt); err != nil {
		return nil, err
	}
	claims, err := jwt.Claims()
	if err != nil {
		return nil, err
	}
	return gooidc.IdentityFromClaims(claims)
}
开发者ID:polvi,项目名称:grpc-credentials,代码行数:27,代码来源:oidc.go


示例16: WithMetadataForwardTLSInfo

// WithMetadataForwardTLSInfo reads certificate from context and returns context where
// ForwardCert is set based on original certificate.
func WithMetadataForwardTLSInfo(ctx context.Context) (context.Context, error) {
	md, ok := metadata.FromContext(ctx)
	if !ok {
		md = metadata.MD{}
	}

	ous := []string{}
	org := ""
	cn := ""

	certSubj, err := certSubjectFromContext(ctx)
	if err == nil {
		cn = certSubj.CommonName
		ous = certSubj.OrganizationalUnit
		if len(certSubj.Organization) > 0 {
			org = certSubj.Organization[0]
		}
	}

	// If there's no TLS cert, forward with blank TLS metadata.
	// Note that the presence of this blank metadata is extremely
	// important. Without it, it would look like manager is making
	// the request directly.
	md[certForwardedKey] = []string{"true"}
	md[certCNKey] = []string{cn}
	md[certOrgKey] = []string{org}
	md[certOUKey] = ous
	peer, ok := peer.FromContext(ctx)
	if ok {
		md[remoteAddrKey] = []string{peer.Addr.String()}
	}

	return metadata.NewContext(ctx, md), nil
}
开发者ID:Chandra-TechPassionate,项目名称:docker,代码行数:36,代码来源:forward.go


示例17: TraceClient

func TraceClient(ctx context.Context) {
	if md, ok := metadata.FromContext(ctx); ok {
		if s, ok := md["client"]; ok {
			Tracef(ctx, "client %+v", s)
		}
	}
}
开发者ID:dpetersen,项目名称:grpc,代码行数:7,代码来源:main.go


示例18: EmptyCall

func (s *testServer) EmptyCall(ctx context.Context, in *testpb.Empty) (*testpb.Empty, error) {
	if _, ok := metadata.FromContext(ctx); ok {
		// For testing purpose, returns an error if there is attached metadata.
		return nil, grpc.Errorf(codes.DataLoss, "got extra metadata")
	}
	return new(testpb.Empty), nil
}
开发者ID:awpr-google,项目名称:grpc-go,代码行数:7,代码来源:end2end_test.go


示例19: Say

func (hs *helloServer) Say(ctx context.Context, request *pb.Request) (*pb.Response, error) {
	var (
		token *jwt.Token
		err   error
	)

	md, ok := metadata.FromContext(ctx)
	if !ok {
		return nil, grpc.Errorf(codes.Unauthenticated, "valid token required.")
	}

	jwtToken, ok := md["authorization"]
	if !ok {
		return nil, grpc.Errorf(codes.Unauthenticated, "valid token required.")
	}

	token, err = validateToken(jwtToken[0], hs.jwtPublicKey)
	if err != nil {
		return nil, grpc.Errorf(codes.Unauthenticated, "valid token required.")
	}

	response := &pb.Response{
		Message: fmt.Sprintf("Hello %s (%s)", request.Name, token.Claims["email"]),
	}

	return response, nil
}
开发者ID:kelseyhightower,项目名称:grpc-hello-service,代码行数:27,代码来源:helloserver.go


示例20: TestAnnotateContext_XForwardedFor

func TestAnnotateContext_XForwardedFor(t *testing.T) {
	ctx := context.Background()
	request, err := http.NewRequest("GET", "http://bar.foo.example.com", nil)
	if err != nil {
		t.Fatalf("http.NewRequest(%q, %q, nil) failed with %v; want success", "GET", "http://bar.foo.example.com", err)
	}
	request.Header.Add("X-Forwarded-For", "192.0.2.100") // client
	request.RemoteAddr = "192.0.2.200:12345"             // proxy

	annotated, err := runtime.AnnotateContext(ctx, request)
	if err != nil {
		t.Errorf("runtime.AnnotateContext(ctx, %#v) failed with %v; want success", request, err)
		return
	}
	md, ok := metadata.FromContext(annotated)
	if !ok || len(md) != emptyForwardMetaCount+1 {
		t.Errorf("Expected %d metadata items in context; got %v", emptyForwardMetaCount+1, md)
	}
	if got, want := md["x-forwarded-host"], []string{"bar.foo.example.com"}; !reflect.DeepEqual(got, want) {
		t.Errorf(`md["host"] = %v; want %v`, got, want)
	}
	// Note: it must be in order client, proxy1, proxy2
	if got, want := md["x-forwarded-for"], []string{"192.0.2.100, 192.0.2.200"}; !reflect.DeepEqual(got, want) {
		t.Errorf(`md["x-forwarded-for"] = %v want %v`, got, want)
	}
}
开发者ID:kubernetes,项目名称:dashboard,代码行数:26,代码来源:context_test.go



注:本文中的google/golang.org/grpc/metadata.FromContext函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang metadata.Join函数代码示例发布时间:2022-05-28
下一篇:
Golang grpc_testing.TestService_FullDuplexCallServer类代码示例发布时间:2022-05-28
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap