add some routes
This commit is contained in:
54
pbutil/pbutil.go
Normal file
54
pbutil/pbutil.go
Normal file
@@ -0,0 +1,54 @@
|
||||
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) (proto.Message, 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 msg, nil
|
||||
}
|
||||
|
||||
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.Marshal(data)
|
||||
if err := protojson.Unmarshal(jsonBytes, msg); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return proto.Marshal(msg)
|
||||
}
|
||||
Reference in New Issue
Block a user