66 lines
1.5 KiB
Go
66 lines
1.5 KiB
Go
package pbutil
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
|
|
_ "bdgrp_go/proto/cn"
|
|
_ "bdgrp_go/proto/gl"
|
|
_ "bdgrp_go/proto/jp"
|
|
_ "bdgrp_go/proto/tw"
|
|
|
|
"google.golang.org/protobuf/encoding/protojson"
|
|
"google.golang.org/protobuf/proto"
|
|
"google.golang.org/protobuf/reflect/protoreflect"
|
|
"google.golang.org/protobuf/reflect/protoregistry"
|
|
)
|
|
|
|
func fullName(message string) protoreflect.FullName {
|
|
server := strings.ToLower(os.Getenv("SERVER"))
|
|
// twdori.proto.ce.UserLogin
|
|
return protoreflect.FullName(fmt.Sprintf("%sdori.proto.ce.%s", server, message))
|
|
}
|
|
|
|
func Decode(message string, data []byte) (map[string]any, error) {
|
|
mt, err := protoregistry.GlobalTypes.FindMessageByName(fullName(message))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("message %s not found", message)
|
|
}
|
|
|
|
msg := mt.New().Interface()
|
|
if err := proto.Unmarshal(data, msg); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return ToMap(msg)
|
|
}
|
|
|
|
func Encode(message string, data map[string]any) ([]byte, error) {
|
|
mt, err := protoregistry.GlobalTypes.FindMessageByName(fullName(message))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("message %s not found", message)
|
|
}
|
|
|
|
msg := mt.New().Interface()
|
|
// map → json → proto
|
|
jsonBytes, _ := json.MarshalIndent(data, "", " ")
|
|
if err := protojson.Unmarshal(jsonBytes, msg); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return proto.Marshal(msg)
|
|
}
|
|
|
|
func ToMap(msg proto.Message) (map[string]any, error) {
|
|
jsonBytes, err := protojson.Marshal(msg)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var result map[string]any
|
|
json.Unmarshal(jsonBytes, &result)
|
|
return result, nil
|
|
}
|