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

     1  package t2j
     2  
     3  import (
     4  	"context"
     5  	"encoding/json"
     6  	"reflect"
     7  
     8  	"github.com/cloudwego/dynamicgo/conv"
     9  	"github.com/cloudwego/dynamicgo/http"
    10  	"github.com/cloudwego/dynamicgo/meta"
    11  	"github.com/cloudwego/dynamicgo/testdata/kitex_gen/example3"
    12  	"github.com/cloudwego/dynamicgo/thrift"
    13  	"github.com/davecgh/go-spew/spew"
    14  )
    15  
    16  var opts = conv.Options{
    17  	EnableHttpMapping: true,
    18  }
    19  
    20  func ExampleBinaryConv_Do() {
    21  	// get descriptor and data
    22  	desc := thrift.FnResponse(thrift.GetFnDescFromFile("testdata/idl/example3.thrift", "ExampleMethod", thrift.Options{}))
    23  	data := getExample3Data()
    24  	// make BinaryConv
    25  	cv := NewBinaryConv(opts)
    26  
    27  	// do conversion
    28  	out, err := cv.Do(context.Background(), desc, data)
    29  	if err != nil {
    30  		panic(err)
    31  	}
    32  
    33  	// validate result
    34  	var exp, act example3.ExampleResp
    35  	_, err = exp.FastRead(data)
    36  	if err != nil {
    37  		panic(err)
    38  	}
    39  	err = json.Unmarshal(out, &act)
    40  	if err != nil {
    41  		panic(err)
    42  	}
    43  	if !reflect.DeepEqual(exp, act) {
    44  		panic("not equal")
    45  	}
    46  }
    47  
    48  func ExampleHTTPConv_DoInto() {
    49  	// get function descriptor
    50  	desc := thrift.GetFnDescFromFile("testdata/idl/example3.thrift", "ExampleMethod", thrift.Options{})
    51  
    52  	// make thrift message
    53  	data := getExample3Data()
    54  	in, err := thrift.WrapBinaryBody(data, "ExampleMethod", thrift.REPLY, thrift.FieldID(0), 1)
    55  	if err != nil {
    56  		panic(err)
    57  	}
    58  
    59  	// get http.ResponseSetter
    60  	resp := http.NewHTTPResponse()
    61  	resp.StatusCode = 200
    62  
    63  	// make HTTPConv
    64  	cv := NewHTTPConv(meta.EncodingThriftBinary, desc)
    65  
    66  	// do conversion
    67  	buf := make([]byte, 0, len(data)*2)
    68  	err = cv.DoInto(context.Background(), resp, in, &buf, opts)
    69  	if err != nil {
    70  		panic(err)
    71  	}
    72  
    73  	// validate result
    74  	var act example3.ExampleResp
    75  	err = json.Unmarshal(buf, &act)
    76  	if err != nil {
    77  		panic(err)
    78  	}
    79  	// non-http annotations fields
    80  	spew.Dump(act)
    81  	// http annotations fields
    82  	spew.Dump(resp)
    83  }