3 Star 0 Fork 0

Gitee 极速下载 / dynamicgo

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
此仓库是为了提升国内下载速度的镜像仓库,每日同步一次。 原始仓库: https://github.com/cloudwego/dynamicgo
克隆/下载
README.md 3.57 KB
一键复制 编辑 原始数据 按行查看 历史

p2j

import "github.com/cloudwego/dynamicgo/conv/p2j"

Index

type BinaryConv

type BinaryConv struct {
    // contains filtered or unexported fields
}

func NewBinaryConv

func NewBinaryConv(opts conv.Options) BinaryConv

NewBinaryConv returns a new BinaryConv

func (*BinaryConv) Do

func (self *BinaryConv) Do(ctx context.Context, desc *proto.TypeDescriptor, pbytes []byte) (json []byte, err error)

Do converts protobuf binary (pbytes) to json bytes (jbytes) desc is the protobuf type descriptor of the protobuf binary, usually it is a response Message type

Example

package main

import (
	"context"
	"encoding/json"
	"reflect"

	"github.com/cloudwego/dynamicgo/conv"
	"github.com/cloudwego/dynamicgo/internal/util_test"
	"github.com/cloudwego/dynamicgo/proto"
	"github.com/cloudwego/dynamicgo/testdata/kitex_gen/pb/example2"
	goprotowire "google.golang.org/protobuf/encoding/protowire"
)

var opts = conv.Options{}

func main() {
	// get descriptor and data
	includeDirs := util_test.MustGitPath("testdata/idl/") // includeDirs is used to find the include files.
	desc := proto.FnRequest(proto.GetFnDescFromFile(exampleIDLPath, "ExampleMethod", proto.Options{}, includeDirs))

	// make BinaryConv
	cv := NewBinaryConv(conv.Options{})
	in := readExampleReqProtoBufData()

	// do conversion
	out, err := cv.Do(context.Background(), desc, in)
	if err != nil {
		panic(err)
	}
	exp := example2.ExampleReq{}

	// use kitex_util to check proto data validity
	l := 0
	dataLen := len(in)
	for l < dataLen {
		id, wtyp, tagLen := goprotowire.ConsumeTag(in)
		if tagLen < 0 {
			panic("proto data error format")
		}
		l += tagLen
		in = in[tagLen:]
		offset, err := exp.FastRead(in, int8(wtyp), int32(id))
		if err != nil {
			panic(err)
		}
		in = in[offset:]
		l += offset
	}
	if len(in) != 0 {
		panic("proto data error format")
	}

	// validate result
	var act example2.ExampleReq
	err = json.Unmarshal([]byte(out), &act)
	if err != nil {
		panic(err)
	}
	if !reflect.DeepEqual(exp, act) {
		panic("not equal")
	}
}

func (*BinaryConv) DoInto

func (self *BinaryConv) DoInto(ctx context.Context, desc *proto.TypeDescriptor, pbytes []byte, buf *[]byte) (err error)

DoInto behaves like Do, but it writes the result to buffer directly instead of returning a new buffer

func (*BinaryConv) SetOptions

func (self *BinaryConv) SetOptions(opts conv.Options)

SetOptions sets options

Generated by gomarkdoc

1
https://gitee.com/mirrors/dynamicgo.git
git@gitee.com:mirrors/dynamicgo.git
mirrors
dynamicgo
dynamicgo
main

搜索帮助