Ai
1 Star 0 Fork 0

iotas/toolkit

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
gen_md_test.go 1.54 KB
一键复制 编辑 原始数据 按行查看 历史
xuthus 提交于 2021-12-14 18:45 +08:00 . fix
package proto_parser
import (
"encoding/json"
"fmt"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/jhump/protoreflect/desc"
"testing"
)
func Test_convertMessageToMap(t *testing.T) {
f := getProtoFileDescriptor("parser.proto")
fd := f.FindMessage("proto_parser.ModelOperLog")
if fd == nil {
panic("fd nil")
}
var convertMessageToMap = func(message *desc.MessageDescriptor) map[string]interface{} {
m := make(map[string]interface{})
for _, fieldDescriptor := range message.GetFields() {
fieldName := fieldDescriptor.GetName()
switch fieldDescriptor.GetType() {
case descriptor.FieldDescriptorProto_TYPE_MESSAGE:
fmt.Println("type message", fieldDescriptor.GetMessageType())
if fieldDescriptor.IsRepeated() {
// 如果是一个数组的话
m[fieldName] = []interface{}{convertMessageToMap(fieldDescriptor.GetMessageType())}
continue
}
m[fieldName] = convertMessageToMap(fieldDescriptor.GetMessageType())
continue
default:
if fieldDescriptor.IsRepeated() {
switch fieldDescriptor.GetType() {
case descriptor.FieldDescriptorProto_TYPE_BOOL:
m[fieldName] = []interface{}{false, true}
case descriptor.FieldDescriptorProto_TYPE_STRING:
m[fieldName] = []interface{}{""}
default:
m[fieldName] = []interface{}{0}
}
continue
}
m[fieldName] = fieldDescriptor.GetDefaultValue()
}
}
return m
}
data := convertMessageToMap(fd)
bs, err := json.MarshalIndent(data, "", "\t")
if err != nil {
panic(err)
}
fmt.Println(string(bs))
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/iotas/toolkit.git
git@gitee.com:iotas/toolkit.git
iotas
toolkit
toolkit
6a2c4ec13c63

搜索帮助