github.com/cloudwego/dynamicgo@v0.2.6-0.20240519101509-707f41b6b834/conv/j2t/example_test.go (about) 1 package j2t 2 3 import ( 4 "context" 5 "encoding/json" 6 stdhttp "net/http" 7 "reflect" 8 "strings" 9 10 "github.com/cloudwego/dynamicgo/conv" 11 "github.com/cloudwego/dynamicgo/http" 12 "github.com/cloudwego/dynamicgo/meta" 13 "github.com/cloudwego/dynamicgo/testdata/kitex_gen/example3" 14 "github.com/cloudwego/dynamicgo/thrift" 15 "github.com/davecgh/go-spew/spew" 16 ) 17 18 var opts = conv.Options{ 19 EnableValueMapping: true, 20 EnableHttpMapping: true, 21 } 22 23 func ExampleBinaryConv_Do() { 24 // get descriptor and data 25 desc := getExampleDesc() 26 data := getExampleData() 27 28 // make BinaryConv 29 cv := NewBinaryConv(opts) 30 31 // do conversion 32 out, err := cv.Do(context.Background(), desc, data) 33 if err != nil { 34 panic(err) 35 } 36 37 // validate result 38 exp := example3.NewExampleReq() 39 err = json.Unmarshal(data, exp) 40 if err != nil { 41 panic(err) 42 } 43 act := example3.NewExampleReq() 44 _, err = act.FastRead(out) 45 if err != nil { 46 panic(err) 47 } 48 if !reflect.DeepEqual(exp, act) { 49 panic("not equal") 50 } 51 } 52 53 func ExampleHTTPConv_DoInto() { 54 // get function descriptor 55 svc, err := thrift.NewDescritorFromPath(context.Background(), exampleIDLPath) 56 if err != nil { 57 panic(err) 58 } 59 fn := svc.Functions()["ExampleMethod"] 60 61 // make HTTPConv 62 cv := NewHTTPConv(meta.EncodingThriftBinary, fn) 63 64 // make std http request 65 jdata := `{"msg":"hello","InnerBase":{}}` 66 stdreq, err := stdhttp.NewRequest("POST", 67 "http://localhost:8080/example?query=1,2,3&inner_query=中文", 68 strings.NewReader(jdata)) 69 if err != nil { 70 panic(err) 71 } 72 stdreq.Header.Set("Content-Type", "application/json") 73 stdreq.Header.Set("heeader", "true") 74 stdreq.Header.Set("inner_string", "igorned") 75 76 // wrap std http request as http.RequestGetter 77 req, err := http.NewHTTPRequestFromStdReq( 78 stdreq, 79 http.Param{Key: "path", Value: "OK"}, 80 http.Param{Key: "inner_string", Value: "priority"}, 81 ) 82 83 // allocate output buffer 84 // TIPS: json data size is usually 1.5x times of thrift data size 85 buf := make([]byte, 0, len(jdata)*2/3) 86 87 // do conversion 88 err = cv.DoInto(context.Background(), req, &buf, opts) 89 if err != nil { 90 panic(err) 91 } 92 93 // unwrap thrift message 94 p := thrift.NewBinaryProtocol(buf) 95 method, mType, seqID, reqID, stru, err := p.UnwrapBody() 96 println(method, mType, seqID, reqID) // ExampleMethod 1 0 1 97 98 // validate result 99 act := example3.NewExampleReq() 100 _, err = act.FastRead(stru) 101 if err != nil { 102 panic(err) 103 } 104 spew.Dump(act) 105 }