github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/service/client/grpc/response.go (about)

     1  // Copyright 2020 Asim Aslam
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     https://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  // Original source: github.com/micro/go-micro/v3/client/grpc/response.go
    16  
    17  package grpc
    18  
    19  import (
    20  	"encoding/json"
    21  	"strings"
    22  
    23  	"github.com/tickoalcantara12/micro/v3/service/errors"
    24  	"github.com/tickoalcantara12/micro/v3/util/codec"
    25  	"github.com/tickoalcantara12/micro/v3/util/codec/bytes"
    26  	"google.golang.org/grpc"
    27  	"google.golang.org/grpc/encoding"
    28  	"google.golang.org/grpc/status"
    29  )
    30  
    31  type response struct {
    32  	conn   *poolConn
    33  	stream grpc.ClientStream
    34  	codec  encoding.Codec
    35  	gcodec codec.Codec
    36  }
    37  
    38  // Read the response
    39  func (r *response) Codec() codec.Reader {
    40  	return r.gcodec
    41  }
    42  
    43  // read the header
    44  func (r *response) Header() map[string]string {
    45  	md, err := r.stream.Header()
    46  	if err != nil {
    47  		return map[string]string{}
    48  	}
    49  	hdr := make(map[string]string, len(md))
    50  	for k, v := range md {
    51  		hdr[k] = strings.Join(v, ",")
    52  	}
    53  	return hdr
    54  }
    55  
    56  // Read the undecoded response
    57  func (r *response) Read() ([]byte, error) {
    58  	f := &bytes.Frame{}
    59  	if err := r.gcodec.ReadBody(f); err != nil {
    60  		gerr, ok := status.FromError(err)
    61  		if ok {
    62  			return nil, grpcErrToMicroErr(gerr)
    63  		}
    64  		return nil, err
    65  	}
    66  	return f.Data, nil
    67  }
    68  
    69  func grpcErrToMicroErr(stat *status.Status) error {
    70  	// try to pull our a micro error from the message. Sometimes this is deeply nested so loop
    71  	errBytes := []byte(stat.Message())
    72  	var ret error
    73  	ret = stat.Err()
    74  	for {
    75  		merr := &errors.Error{}
    76  		if err := json.Unmarshal(errBytes, merr); err != nil {
    77  			return ret
    78  		}
    79  		ret = merr
    80  		errBytes = []byte(merr.Detail)
    81  	}
    82  }