github.com/polarismesh/polaris@v1.17.8/test/integrate/grpc/discover.go (about) 1 /** 2 * Tencent is pleased to support the open source community by making Polaris available. 3 * 4 * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. 5 * 6 * Licensed under the BSD 3-Clause License (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * https://opensource.org/licenses/BSD-3-Clause 11 * 12 * Unless required by applicable law or agreed to in writing, software distributed 13 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 14 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 15 * specific language governing permissions and limitations under the License. 16 */ 17 18 package grpc 19 20 import ( 21 "context" 22 "fmt" 23 "io" 24 "time" 25 26 apiservice "github.com/polarismesh/specification/source/go/api/v1/service_manage" 27 "google.golang.org/grpc/metadata" 28 29 "github.com/polarismesh/polaris/common/utils" 30 ) 31 32 // Discover 统一发现函数 33 func (c *Client) Discover(drt apiservice.DiscoverRequest_DiscoverRequestType, service *apiservice.Service, hook func(resp *apiservice.DiscoverResponse)) error { 34 fmt.Printf("\ndiscover\n") 35 36 md := metadata.Pairs("request-id", utils.NewUUID()) 37 ctx := metadata.NewOutgoingContext(context.Background(), md) 38 39 ctx, cancel := context.WithTimeout(ctx, time.Second) 40 defer cancel() 41 42 worker, err := c.Worker.Discover(ctx) 43 if err != nil { 44 fmt.Printf("%v\n", err) 45 return err 46 } 47 48 request := &apiservice.DiscoverRequest{ 49 Type: drt, 50 Service: service, 51 } 52 if err := worker.Send(request); err != nil { 53 fmt.Printf("%v\n", err) 54 return err 55 } 56 57 worker.CloseSend() 58 59 for { 60 rsp, err := worker.Recv() 61 if err != nil { 62 if err == io.EOF { 63 return nil 64 } 65 66 fmt.Printf("%v\n", err) 67 return err 68 } 69 70 hook(rsp) 71 } 72 } 73 74 // DiscoverRequest 统一发现函数 75 func (c *Client) DiscoverRequest(request *apiservice.DiscoverRequest) (*apiservice.DiscoverResponse, error) { 76 fmt.Printf("\ndiscover\n") 77 78 md := metadata.Pairs("request-id", utils.NewUUID()) 79 ctx := metadata.NewOutgoingContext(context.Background(), md) 80 81 ctx, cancel := context.WithTimeout(ctx, time.Second) 82 defer cancel() 83 84 worker, err := c.Worker.Discover(ctx) 85 if err != nil { 86 fmt.Printf("%v\n", err) 87 return nil, err 88 } 89 90 if err := worker.Send(request); err != nil { 91 fmt.Printf("%v\n", err) 92 return nil, err 93 } 94 worker.CloseSend() 95 96 var latestResp *apiservice.DiscoverResponse 97 98 for { 99 rsp, err := worker.Recv() 100 if err != nil { 101 if err == io.EOF { 102 return latestResp, nil 103 } 104 105 fmt.Printf("%v\n", err) 106 } 107 108 fmt.Printf("%v\n", rsp) 109 latestResp = rsp 110 } 111 112 }