converter.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // Copyright 2022 EMQ Technologies Co., Ltd.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package protobuf
  15. import (
  16. "fmt"
  17. "github.com/jhump/protoreflect/desc"
  18. "github.com/jhump/protoreflect/desc/protoparse"
  19. "strings"
  20. )
  21. type Converter struct {
  22. descriptor *desc.MessageDescriptor
  23. fc *FieldConverter
  24. }
  25. var protoParser *protoparse.Parser
  26. func init() {
  27. //etcDir, err := conf.GetConfLoc()
  28. //if err != nil {
  29. // panic(err)
  30. //}
  31. protoParser = &protoparse.Parser{}
  32. }
  33. func NewConverter(schemaId string, fileName string) (*Converter, error) {
  34. des := strings.Split(schemaId, ".")
  35. if len(des) != 2 {
  36. return nil, fmt.Errorf("invalid schema id %s for protobuf, the format must be protoName.mesageName", schemaId)
  37. }
  38. if fds, err := protoParser.ParseFiles(fileName); err != nil {
  39. return nil, fmt.Errorf("parse schema file %s failed: %s", fileName, err)
  40. } else {
  41. messageDescriptor := fds[0].FindMessage(des[1])
  42. if messageDescriptor == nil {
  43. return nil, fmt.Errorf("message type %s not found in schema file %s", des[1], fileName)
  44. }
  45. return &Converter{
  46. descriptor: messageDescriptor,
  47. fc: GetFieldConverter(),
  48. }, nil
  49. }
  50. }
  51. func (c *Converter) Encode(d interface{}) ([]byte, error) {
  52. switch m := d.(type) {
  53. case map[string]interface{}:
  54. msg, err := c.fc.encodeMap(c.descriptor, m)
  55. if err != nil {
  56. return nil, err
  57. }
  58. return msg.Marshal()
  59. default:
  60. return nil, fmt.Errorf("unsupported type %v, must be a map", d)
  61. }
  62. }
  63. func (c *Converter) Decode(b []byte) (interface{}, error) {
  64. result := mf.NewDynamicMessage(c.descriptor)
  65. err := result.Unmarshal(b)
  66. if err != nil {
  67. return nil, err
  68. }
  69. return c.fc.DecodeMessage(result, c.descriptor), nil
  70. }