github.com/cloudwego/dynamicgo@v0.2.6-0.20240519101509-707f41b6b834/conv/p2j/example_test.go (about)

     1  package p2j
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"reflect"
     7  
     8  	"github.com/cloudwego/dynamicgo/conv"
     9  	"github.com/cloudwego/dynamicgo/internal/util_test"
    10  	"github.com/cloudwego/dynamicgo/proto"
    11  	"github.com/cloudwego/dynamicgo/testdata/kitex_gen/pb/example2"
    12  	goprotowire "google.golang.org/protobuf/encoding/protowire"
    13  )
    14  
    15  var opts = conv.Options{}
    16  
    17  func ExampleBinaryConv_Do() {
    18  	// get descriptor and data
    19  	includeDirs := util_test.MustGitPath("testdata/idl/") // includeDirs is used to find the include files.
    20  	desc := proto.FnRequest(proto.GetFnDescFromFile(exampleIDLPath, "ExampleMethod", proto.Options{}, includeDirs))
    21  
    22  	// make BinaryConv
    23  	cv := NewBinaryConv(conv.Options{})
    24  	in := readExampleReqProtoBufData()
    25  
    26  	// do conversion
    27  	out, err := cv.Do(context.Background(), desc, in)
    28  	if err != nil {
    29  		panic(err)
    30  	}
    31  	exp := example2.ExampleReq{}
    32  
    33  	// use kitex_util to check proto data validity
    34  	l := 0
    35  	dataLen := len(in)
    36  	for l < dataLen {
    37  		id, wtyp, tagLen := goprotowire.ConsumeTag(in)
    38  		if tagLen < 0 {
    39  			panic("proto data error format")
    40  		}
    41  		l += tagLen
    42  		in = in[tagLen:]
    43  		offset, err := exp.FastRead(in, int8(wtyp), int32(id))
    44  		if err != nil {
    45  			panic(err)
    46  		}
    47  		in = in[offset:]
    48  		l += offset
    49  	}
    50  	if len(in) != 0 {
    51  		panic("proto data error format")
    52  	}
    53  
    54  	// validate result
    55  	var act example2.ExampleReq
    56  	err = json.Unmarshal([]byte(out), &act)
    57  	if err != nil {
    58  		panic(err)
    59  	}
    60  	if !reflect.DeepEqual(exp, act) {
    61  		panic("not equal")
    62  	}
    63  }