gitee.com/h79/goutils@v1.22.10/discovery/resolver/grpc/connector.go (about) 1 package grpc 2 3 import ( 4 "gitee.com/h79/goutils/common/attributes" 5 "gitee.com/h79/goutils/discovery/resolver/builder" 6 grpcAttributes "google.golang.org/grpc/attributes" 7 grpcResolver "google.golang.org/grpc/resolver" 8 "sort" 9 ) 10 11 // connector 12 // 一个与grpc桥接的实现 13 type connector struct { 14 cc grpcResolver.ClientConn 15 } 16 17 // UpdateState builder.Connector interface 18 func (cr *connector) UpdateState(state builder.State) { 19 if cr.cc == nil { 20 return 21 } 22 s := grpcResolver.State{ 23 ServiceConfig: nil, 24 Addresses: toGrpcAddress(state.Addresses), 25 Attributes: toGrpcAttribute(state.Attributes), 26 } 27 _ = cr.cc.UpdateState(s) 28 } 29 30 // ReportError resolver.Connector interface 31 func (cr *connector) ReportError(er error) { 32 if cr.cc == nil { 33 return 34 } 35 cr.cc.ReportError(er) 36 } 37 38 func toGrpcAttribute(attrs *attributes.Attributes) *grpcAttributes.Attributes { 39 if attrs == nil { 40 return nil 41 } 42 var attr *grpcAttributes.Attributes 43 attrs.For(func(key interface{}, val interface{}) { 44 attr = attr.WithValue(key, val) 45 }) 46 return attr 47 } 48 49 func toGrpcAddress(addr builder.Addresses) []grpcResolver.Address { 50 sort.Sort(addr) 51 grpcAddress := make([]grpcResolver.Address, 0) 52 for i := range addr { 53 aa := grpcResolver.Address{ 54 Addr: addr[i].Addr, 55 ServerName: addr[i].ServerName, 56 Attributes: toGrpcAttribute(addr[i].Attributes), 57 } 58 grpcAddress = append(grpcAddress, aa) 59 } 60 return grpcAddress 61 }