Best K6 code snippet using client.New
client.go
Source:client.go
...36 closing bool // closing æ shutdown ä»»ä¸ç½®ä¸º true æ¶è¡¨ç¤º Client å¤äºä¸å¯ç¨ç¶æ37 shutdown bool // closing 表示ç¨æ·ä¸»å¨å
³éï¼shutdown ä¸è¬æ¯æé误åç38}39var _ io.Closer = (*Client)(nil)40var ErrShutdown = errors.New("connection is shut down")41func (client *Client) Close() error {42 client.mu.Lock()43 defer client.mu.Unlock()44 if client.closing {45 return ErrShutdown46 }47 client.closing = true48 return client.cc.Close()49}50func (client *Client) IsAvailable() bool {51 client.mu.Lock()52 defer client.mu.Unlock()53 return !client.shutdown && !client.closing54}55// å°åæ° call æ·»å å° client.pending ä¸ï¼å¹¶æ´æ° client.seq56func (client *Client) registerCall(call *Call) (uint64, error) {57 client.mu.Lock()58 defer client.mu.Unlock()59 if client.closing || client.shutdown {60 return 0, ErrShutdown61 }62 call.Seq = client.seq63 client.pending[call.Seq] = call64 client.seq++65 return call.Seq, nil66}67// æ ¹æ® seqï¼ä» client.pending ä¸ç§»é¤å¯¹åºç call68func (client *Client) removeCall(seq uint64) *Call {69 client.mu.Lock()70 defer client.mu.Unlock()71 call := client.pending[seq]72 delete(client.pending, seq)73 return call74}75// åçé误æ¶ï¼å° shutdown 置为 trueï¼ä¸å°é误信æ¯éç¥ç»ææ pending ç¶æç call76func (client *Client) terminateCalls(err error) {77 client.sending.Lock()78 defer client.sending.Unlock()79 client.mu.Lock()80 defer client.mu.Unlock()81 client.shutdown = true82 for _, call := range client.pending {83 call.Error = err84 call.done()85 }86}87func (client *Client) send(call *Call) {88 client.sending.Lock()89 defer client.sending.Unlock()90 seq, err := client.registerCall(call)91 if err != nil {92 call.Error = err93 call.done()94 return95 }96 client.header.ServiceMethod = call.ServiceMethod97 client.header.Seq = seq98 client.header.Error = ""99 if err := client.cc.Write(&client.header, call.Args); err != nil {100 call := client.removeCall(seq)101 if call != nil {102 call.Error = err103 call.done()104 }105 }106}107// æ¥æ¶ååº108func (client *Client) receive() {109 var err error110 for err == nil {111 var h codec.Header112 if err = client.cc.ReadHeader(&h); err != nil {113 break114 }115 call := client.removeCall(h.Seq)116 switch {117 case call == nil:118 // call ä¸åå¨ï¼å¯è½æ¯è¯·æ±æ²¡æåéå®æ´ï¼æè
å 为å
¶ä»åå 被åæ¶ï¼ä½æ¯æå¡ç«¯ä»æ§å¤çäº119 err = client.cc.ReadBody(nil)120 case h.Error != "":121 // call åå¨ï¼ä½æå¡ç«¯å¤çåºé122 call.Error = fmt.Errorf(h.Error)123 err = client.cc.ReadBody(nil)124 call.done()125 default:126 // call åå¨ï¼æå¡ç«¯å¤çæ£å¸¸ï¼ä» body ä¸è¯»å Reply çå¼127 err = client.cc.ReadBody(call.Reply)128 if err != nil {129 call.Error = errors.New("reading body " + err.Error())130 }131 call.done()132 }133 }134 client.terminateCalls(err)135}136func (client *Client) Go(serviceMethod string, args, reply interface{}, done chan *Call) *Call {137 if done == nil {138 done = make(chan *Call, 10)139 } else if cap(done) == 0 {140 log.Panic("rpc client: done channel is unbuffered")141 }142 call := &Call{143 ServiceMethod: serviceMethod,144 Args: args,145 Reply: reply,146 Done: done,147 }148 client.send(call)149 return call150}151func (client *Client) Call(ctx context.Context, serviceMethod string, args, reply interface{}) error {152 call := client.Go(serviceMethod, args, reply, make(chan *Call, 1))153 select {154 case <-ctx.Done():155 client.removeCall(call.Seq)156 return errors.New("rpc client: call failed: " + ctx.Err().Error())157 case call := <-call.Done:158 return call.Error159 }160}161func parseOptions(opts ...*Option) (*Option, error) {162 if len(opts) == 0 || opts[0] == nil {163 return DefaultOption, nil164 }165 if len(opts) != 1 {166 return nil, errors.New("number of options is more than 1")167 }168 opt := opts[0]169 opt.MagicNumber = DefaultOption.MagicNumber170 if opt.CodecType == "" {171 opt.CodecType = DefaultOption.CodecType172 }173 return opt, nil174}175func NewClient(conn net.Conn, opt *Option) (*Client, error) {176 f := codec.NewCodecFuncMap[opt.CodecType]177 if f == nil {178 err := fmt.Errorf("invalid codec type %s", opt.CodecType)179 log.Println("rpc client: codec error:", err)180 return nil, err181 }182 if err := json.NewEncoder(conn).Encode(opt); err != nil {183 log.Println("rpc client: options error: ", err)184 return nil, err185 }186 return newClientCodec(f(conn), opt), nil187}188func newClientCodec(cc codec.Codec, opt *Option) *Client {189 client := &Client{190 seq: 1, // ä»1å¼å§ï¼0å为æ æç Call191 cc: cc,192 opt: opt,193 pending: make(map[uint64]*Call),194 }195 go client.receive()196 return client197}198type clientResult struct {199 client *Client200 err error201}202type newClientFunc func(conn net.Conn, opt *Option) (client *Client, err error)203func dialTimeout(f newClientFunc, network, address string, opts ...*Option) (client *Client, err error) {204 opt, err := parseOptions(opts...)205 if err != nil {206 return nil, err207 }208 // å° net.Dial æ¿æ¢ä¸º net.DialTimeoutï¼å¦æè¿æ¥å建è¶
æ¶ï¼å°è¿åé误209 conn, err := net.DialTimeout(network, address, opt.ConnectTimeout)210 if err != nil {211 return nil, err212 }213 defer func() {214 if err != nil {215 _ = conn.Close()216 }217 }()218 ch := make(chan clientResult)219 // æ§è¡å®æåéè¿ä¿¡é ch åéç»æ220 //å¦æ time.After() ä¿¡éå
æ¥æ¶å°æ¶æ¯ï¼å说æ NewClient æ§è¡è¶
æ¶ï¼è¿åé误221 go func() {222 client, err := f(conn, opt)223 ch <- clientResult{client: client, err: err}224 }()225 if opt.ConnectTimeout == 0 {226 result := <-ch227 return result.client, result.err228 }229 select {230 case <-time.After(opt.ConnectTimeout):231 return nil, fmt.Errorf("rpc client: connect timeout: expect within %s", opt.ConnectTimeout)232 case result := <-ch:233 return result.client, result.err234 }235}236// Dial connects to an RPC server at the specified network address237func Dial(network, address string, opts ...*Option) (*Client, error) {238 return dialTimeout(NewClient, network, address, opts...)239}240func NewHTTPClient(conn net.Conn, opt *Option) (*Client, error) {241 _, _ = io.WriteString(conn, fmt.Sprintf("CONNECT %s HTTP/1.0\n\n", defaultRPCPath))242 // å¨è½¬æ¢å° RPC åè®®åï¼éè¦æåè·å HTTP response243 resp, err := http.ReadResponse(bufio.NewReader(conn), &http.Request{Method: "CONNECT"})244 if err == nil && resp.Status == connected {245 return NewClient(conn, opt)246 }247 if err == nil {248 err = errors.New("unexpected HTTP response: " + resp.Status)249 }250 return nil, err251}252func DialHTTP(network, address string, opts ...*Option) (*Client, error) {253 return dialTimeout(NewHTTPClient, network, address, opts...)254}255// XDial calls different functions to connect to a RPC server256// according the first parameter rpcAddr.257// rpcAddr is a general format (protocol@addr) to represent a rpc server258// eg, http@10.0.0.1:7001, tcp@10.0.0.1:9999, unix@/tmp/sgRPC.sock259func XDial(rpcAddr string, opts ...*Option) (*Client, error) {260 parts := strings.Split(rpcAddr, "@")261 if len(parts) != 2 {262 return nil, fmt.Errorf("rpc client err: wrong format '%s', expect protocol@addr", rpcAddr)263 }264 protocol, addr := parts[0], parts[1]265 switch protocol {266 case "http":267 return DialHTTP("tcp", addr, opts...)...
resource_test.go
Source:resource_test.go
...17func TestClient_CreateWithReference(t *testing.T) {18 ctx := context.TODO()19 t.Run("Success", func(t *testing.T) {20 // Given21 g := gomega.NewGomegaWithT(t)22 scheme := runtime.NewScheme()23 g.Expect(clientgoscheme.AddToScheme(scheme)).To(gomega.BeNil())24 parent := &batchv1.Job{}25 object := &corev1.Pod{}26 client := new(automock.K8sClient)27 client.On("Create", ctx, object).Return(nil).Once()28 defer client.AssertExpectations(t)29 resourceClient := resource.New(client, scheme)30 // When31 err := resourceClient.CreateWithReference(ctx, parent, object)32 // Then33 g.Expect(err).To(gomega.BeNil())34 })35 t.Run("WithoutParent", func(t *testing.T) {36 // Given37 g := gomega.NewGomegaWithT(t)38 scheme := runtime.NewScheme()39 g.Expect(clientgoscheme.AddToScheme(scheme)).To(gomega.BeNil())40 object := &corev1.Pod{}41 client := new(automock.K8sClient)42 client.On("Create", ctx, object).Return(nil).Once()43 defer client.AssertExpectations(t)44 resourceClient := resource.New(client, scheme)45 // When46 err := resourceClient.CreateWithReference(ctx, nil, object)47 // Then48 g.Expect(err).To(gomega.BeNil())49 })50 t.Run("AlreadyExists", func(t *testing.T) {51 // Given52 g := gomega.NewGomegaWithT(t)53 scheme := runtime.NewScheme()54 g.Expect(clientgoscheme.AddToScheme(scheme)).To(gomega.BeNil())55 parent := &batchv1.Job{}56 object := &corev1.Pod{}57 client := new(automock.K8sClient)58 client.On("Create", ctx, object).Return(errors.NewAlreadyExists(controllerruntime.GroupResource{}, "test")).Once()59 defer client.AssertExpectations(t)60 resourceClient := resource.New(client, scheme)61 // When62 err := resourceClient.CreateWithReference(ctx, parent, object)63 // Then64 g.Expect(errors.IsAlreadyExists(err)).To(gomega.BeTrue())65 })66 t.Run("SetReferenceError", func(t *testing.T) {67 // Given68 g := gomega.NewGomegaWithT(t)69 scheme := runtime.NewScheme()70 parent := &batchv1.Job{}71 object := &corev1.Pod{}72 resourceClient := resource.New(nil, scheme)73 // When74 err := resourceClient.CreateWithReference(ctx, parent, object)75 // Then76 g.Expect(runtime.IsNotRegisteredError(err)).To(gomega.BeTrue())77 })78}79func TestClient_ListByLabel(t *testing.T) {80 ctx := context.TODO()81 t.Run("Success", func(t *testing.T) {82 // Given83 g := gomega.NewGomegaWithT(t)84 list := &batchv1.JobList{}85 labels := map[string]string{"test": "test"}86 client := new(automock.K8sClient)87 client.On("List", ctx, list, mock.Anything).Return(nil).Once()88 defer client.AssertExpectations(t)89 resourceClient := resource.New(client, nil)90 // When91 err := resourceClient.ListByLabel(ctx, "test", labels, list)92 // Then93 g.Expect(err).To(gomega.BeNil())94 })95 t.Run("NoLabels", func(t *testing.T) {96 // Given97 g := gomega.NewGomegaWithT(t)98 list := &batchv1.JobList{}99 client := new(automock.K8sClient)100 client.On("List", ctx, list, mock.Anything).Return(nil).Once()101 defer client.AssertExpectations(t)102 resourceClient := resource.New(client, nil)103 // When104 err := resourceClient.ListByLabel(ctx, "test", nil, list)105 // Then106 g.Expect(err).To(gomega.BeNil())107 })108 t.Run("Error", func(t *testing.T) {109 // Given110 g := gomega.NewGomegaWithT(t)111 list := &batchv1.JobList{}112 labels := map[string]string{"test": "test"}113 client := new(automock.K8sClient)114 client.On("List", ctx, list, mock.Anything).Return(errors.NewBadRequest("bad")).Once()115 defer client.AssertExpectations(t)116 resourceClient := resource.New(client, nil)117 // When118 err := resourceClient.ListByLabel(ctx, "test", labels, list)119 // Then120 g.Expect(errors.IsBadRequest(err)).To(gomega.BeTrue())121 })122}123func TestClient_DeleteAllBySelector(t *testing.T) {124 ctx := context.TODO()125 t.Run("Success", func(t *testing.T) {126 // Given127 g := gomega.NewGomegaWithT(t)128 resourceType := &batchv1.Job{}129 labels := map[string]string{"test": "test"}130 selector := apilabels.SelectorFromSet(labels)131 client := new(automock.K8sClient)132 client.On("DeleteAllOf", ctx, resourceType, mock.Anything).Return(nil).Once()133 defer client.AssertExpectations(t)134 resourceClient := resource.New(client, nil)135 // When136 err := resourceClient.DeleteAllBySelector(ctx, resourceType, "test", selector)137 // Then138 g.Expect(err).To(gomega.BeNil())139 })140 t.Run("NoLabels", func(t *testing.T) {141 // Given142 g := gomega.NewGomegaWithT(t)143 resourceType := &batchv1.Job{}144 client := new(automock.K8sClient)145 client.On("DeleteAllOf", ctx, resourceType, mock.Anything).Return(nil).Once()146 defer client.AssertExpectations(t)147 resourceClient := resource.New(client, nil)148 // When149 err := resourceClient.DeleteAllBySelector(ctx, resourceType, "test", nil)150 // Then151 g.Expect(err).To(gomega.BeNil())152 })153 t.Run("Error", func(t *testing.T) {154 // Given155 g := gomega.NewGomegaWithT(t)156 resourceType := &batchv1.Job{}157 labels := map[string]string{"test": "test"}158 selector := apilabels.SelectorFromSet(labels)159 client := new(automock.K8sClient)160 client.On("DeleteAllOf", ctx, resourceType, mock.Anything).Return(errors.NewBadRequest("bad")).Once()161 defer client.AssertExpectations(t)162 resourceClient := resource.New(client, nil)163 // When164 err := resourceClient.DeleteAllBySelector(ctx, resourceType, "test", selector)165 // Then166 g.Expect(errors.IsBadRequest(err)).To(gomega.BeTrue())167 })168}...
hipchat_test.go
Source:hipchat_test.go
...18// Tests should register handlers on mux which provide mock responses for19// the API method being tested.20func setup() {21 // test server22 mux = http.NewServeMux()23 server = httptest.NewServer(mux)24 // github client configured to use test server25 client = NewClient("AuthToken")26 url, _ := url.Parse(server.URL)27 client.BaseURL = url28}29// teardown closes the test HTTP server.30func teardown() {31 server.Close()32}33func testMethod(t *testing.T, r *http.Request, want string) {34 if got := r.Method; got != want {35 t.Errorf("Request method: %v, want %v", got, want)36 }37}38type values map[string]string39func testFormValues(t *testing.T, r *http.Request, values values) {40 want := url.Values{}41 for k, v := range values {42 want.Add(k, v)43 }44 r.ParseForm()45 if got := r.Form; !reflect.DeepEqual(got, want) {46 t.Errorf("Request parameters: %v, want %v", got, want)47 }48}49func testHeader(t *testing.T, r *http.Request, header string, want string) {50 if got := r.Header.Get(header); got != want {51 t.Errorf("Header.Get(%q) returned %s, want %s", header, got, want)52 }53}54func TestNewClient(t *testing.T) {55 authToken := "AuthToken"56 c := NewClient(authToken)57 if c.authToken != authToken {58 t.Errorf("NewClient authToken %s, want %s", c.authToken, authToken)59 }60 if c.BaseURL.String() != defaultBaseURL {61 t.Errorf("NewClient BaseURL %s, want %s", c.BaseURL.String(), defaultBaseURL)62 }63 if c.client != http.DefaultClient {64 t.Errorf("SetHTTPClient client %v, want %p", c.client, http.DefaultClient)65 }66}67func TestSetHTTPClient(t *testing.T) {68 c := NewClient("AuthToken")69 httpClient := new(http.Client)70 c.SetHTTPClient(httpClient)71 if c.client != httpClient {72 t.Errorf("SetHTTPClient client %v, want %p", c.client, httpClient)73 }74}75type customHTTPClient struct{}76func (c customHTTPClient) Do(*http.Request) (*http.Response, error) {77 return nil, nil78}79func TestSetCustomHTTPClient(t *testing.T) {80 c := NewClient("AuthToken")81 httpClient := new(customHTTPClient)82 c.SetHTTPClient(httpClient)83 if c.client != httpClient {84 t.Errorf("SetHTTPClient client %v, want %p", c.client, httpClient)85 }86}87func TestSetHTTPClient_NilHTTPClient(t *testing.T) {88 c := NewClient("AuthToken")89 c.SetHTTPClient(nil)90 if c.client != http.DefaultClient {91 t.Errorf("SetHTTPClient client %v, want %p", c.client, http.DefaultClient)92 }93}94func TestNewRequest(t *testing.T) {95 c := NewClient("AuthToken")96 inURL, outURL := "foo", defaultBaseURL+"foo?max-results=100&start-index=1"97 opt := &ListOptions{StartIndex: 1, MaxResults: 100}98 inBody, outBody := &NotificationRequest{Message: "Hello"}, `{"message":"Hello"}`+"\n"99 r, _ := c.NewRequest("GET", inURL, opt, inBody)100 if r.URL.String() != outURL {101 t.Errorf("NewRequest URL %s, want %s", r.URL.String(), outURL)102 }103 body, _ := ioutil.ReadAll(r.Body)104 if string(body) != outBody {105 t.Errorf("NewRequest body %s, want %s", body, outBody)106 }107 authorization := r.Header.Get("Authorization")108 if authorization != "Bearer "+c.authToken {109 t.Errorf("NewRequest authorization header %s, want %s", authorization, "Bearer "+c.authToken)110 }111 contentType := r.Header.Get("Content-Type")112 if contentType != "application/json" {113 t.Errorf("NewRequest Content-Type header %s, want application/json", contentType)114 }115}116func TestNewRequest_AuthTestEnabled(t *testing.T) {117 AuthTest = true118 defer func() { AuthTest = false }()119 c := NewClient("AuthToken")120 inURL, outURL := "foo", defaultBaseURL+"foo?auth_test=true"121 r, _ := c.NewRequest("GET", inURL, nil, nil)122 if r.URL.String() != outURL {123 t.Errorf("NewRequest URL %s, want %s", r.URL.String(), outURL)124 }125}126func TestDo(t *testing.T) {127 setup()128 defer teardown()129 type foo struct {130 Bar int131 }132 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {133 if m := "GET"; m != r.Method {134 t.Errorf("Request method = %v, want %v", r.Method, m)135 }136 fmt.Fprintf(w, `{"Bar":1}`)137 })138 req, _ := client.NewRequest("GET", "/", nil, nil)139 body := new(foo)140 _, err := client.Do(req, body)141 if err != nil {142 t.Fatal(err)143 }144 want := &foo{Bar: 1}145 if !reflect.DeepEqual(body, want) {146 t.Errorf("Response body = %v, want %v", body, want)147 }148}149func TestDo_AuthTestEnabled(t *testing.T) {150 AuthTest = true151 defer func() { AuthTest = false }()152 setup()153 defer teardown()154 mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {155 if m := "GET"; m != r.Method {156 t.Errorf("Request method = %v, want %v", r.Method, m)157 }158 if r.URL.Query().Get("auth_test") == "true" {159 fmt.Fprintf(w, `{"success":{ "code": 202, "type": "Accepted", "message": "This auth_token has access to use this method." }}`)160 } else {161 fmt.Fprintf(w, `{"Bar":1}`)162 }163 })164 req, _ := client.NewRequest("GET", "/", nil, nil)165 _, err := client.Do(req, nil)166 if err != nil {167 t.Fatal(err)168 }169 if _, ok := AuthTestResponse["success"]; !ok {170 t.Errorf("Response body = %v, want succeed", AuthTestResponse)171 }172}...
New
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello I am a client")4 cc, err := grpc.Dial("localhost:50051", grpc.WithInsecure())5 if err != nil {6 log.Fatalf("could not connect: %v", err)7 }8 defer cc.Close()9 c := calculatorpb.NewCalculatorServiceClient(cc)10 doBiDiStreaming(c)11}12func doUnary(c calculatorpb.CalculatorServiceClient) {13 fmt.Println("Starting to do a Unary RPC...")14 req := &calculatorpb.SumRequest{15 }16 res, err := c.Sum(context.Background(), req)17 if err != nil {18 log.Fatalf("error while calling Sum RPC: %v", err)19 }20 log.Printf("Response from Sum: %v", res.SumResult)21}22func doServerStreaming(c calculatorpb.CalculatorServiceClient) {23 fmt.Println("Starting to do a Server Streaming RPC...")24 req := &calculatorpb.PrimeNumberDecompositionRequest{25 }26 resStream, err := c.PrimeNumberDecomposition(context.Background(), req)27 if err != nil {28 log.Fatalf("error while calling PrimeNumberDecomposition RPC: %v", err)29 }30 for {31 msg, err := resStream.Recv()32 if err == io.EOF {33 }34 if err != nil {35 log.Fatalf("something went wrong: %v", err)36 }37 log.Printf("Response from PrimeNumberDecomposition: %v", msg.GetPrimeFactor())38 }39}40func doClientStreaming(c calculatorpb.CalculatorServiceClient) {41 fmt.Println("Starting to do a Client Streaming RPC...")42 requests := []*calculatorpb.ComputeAverageRequest{43 &calculatorpb.ComputeAverageRequest{44 },45 &calculatorpb.ComputeAverageRequest{46 },47 &calculatorpb.ComputeAverageRequest{
New
Using AI Code Generation
1import (2func main() {3 client := &http.Client{}4 resp, _ := client.Do(req)5 fmt.Println(resp)6}7&{200 OK 200 HTTP/1.1 1 1 map[Content-Type:[text/html; charset=ISO-8859-1] Date:[Tue, 13 Nov 2018 10:10:38 GMT] Expires:[-1] Cache-Control:[private, max-age=0] P3p:[CP="This is not a P3P policy! See g.co/p3phelp for more info."] Server:[gws] X-Xss-Protection:[1; mode=block] X-Frame-Options:[SAMEORIGIN] Set-Cookie:[1P_JAR=2018-11-13-10; expires=Thu, 13-Dec-2018 10:1
New
Using AI Code Generation
1client := http.Client{2}3if err != nil {4 log.Fatal(err)5}6defer resp.Body.Close()7body, err := ioutil.ReadAll(resp.Body)8if err != nil {9 log.Fatal(err)10}11fmt.Println(string(body))12client := &http.Client{}13if err != nil {14 log.Fatal(err)15}16resp, err := client.Do(req)17if err != nil {18 log.Fatal(err)19}20defer resp.Body.Close()21body, err := ioutil.ReadAll(resp.Body)22if err != nil {23 log.Fatal(err)24}25fmt.Println(string(body))26if err != nil {27 log.Fatal(err)28}29defer resp.Body.Close()30body, err := ioutil.ReadAll(resp.Body)31if err != nil {32 log.Fatal(err)33}34fmt.Println(string(body))35if err != nil {36 log.Fatal(err)37}38defer resp.Body.Close()39body, err := ioutil.ReadAll(resp.Body)40if err != nil {41 log.Fatal(err)42}43fmt.Println(string(body))44if err != nil {45 log.Fatal(err)46}47defer resp.Body.Close()48body, err := ioutil.ReadAll(resp.Body)49if err != nil {50 log.Fatal(err)51}52fmt.Println(string(body))53if err != nil {54 log.Fatal(err)55}56defer resp.Body.Close()57body, err := ioutil.ReadAll(resp.Body)58if err != nil {59 log.Fatal(err)60}61fmt.Println(string(body))62if err != nil {63 log.Fatal(err)64}65defer resp.Body.Close()
New
Using AI Code Generation
1import (2const (3func main() {4 conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())5 if err != nil {6 log.Fatalf("did not connect: %v", err)7 }8 defer conn.Close()9 c := pb.NewClient(conn)10 ctx, cancel := context.WithTimeout(context.Background(), time.Second)11 defer cancel()12 r, err := c.New(ctx, &pb.NewRequest{Name: "test"})13 if err != nil {14 log.Fatalf("could not greet: %v", err)15 }16 fmt.Println(r.GetMessage())17}18import (19const (20func main() {21 conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())22 if err != nil {23 log.Fatalf("did not connect: %v", err)24 }25 defer conn.Close()26 c := pb.NewClient(conn)27 ctx, cancel := context.WithTimeout(context.Background(), time.Second)28 defer cancel()29 r, err := c.Get(ctx, &pb.GetRequest{Key: "test"})30 if err != nil {31 log.Fatalf("could not greet: %v", err)32 }33 fmt.Println(r.GetValue())34}35import (36const (37func main() {38 conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())39 if err != nil {40 log.Fatalf("did not connect: %v", err)41 }42 defer conn.Close()43 c := pb.NewClient(conn)44 ctx, cancel := context.WithTimeout(context.Background(), time.Second)45 defer cancel()46 r, err := c.Delete(ctx, &pb
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!