amit.ghosh | 258d14c | 2020-10-02 15:13:38 +0200 | [diff] [blame] | 1 | // Copyright 2015 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Package jsonpb provides functionality to marshal and unmarshal between a |
| 6 | // protocol buffer message and JSON. It follows the specification at |
| 7 | // https://developers.google.com/protocol-buffers/docs/proto3#json. |
| 8 | // |
| 9 | // Do not rely on the default behavior of the standard encoding/json package |
| 10 | // when called on generated message types as it does not operate correctly. |
| 11 | // |
| 12 | // Deprecated: Use the "google.golang.org/protobuf/encoding/protojson" |
| 13 | // package instead. |
| 14 | package jsonpb |
| 15 | |
| 16 | import ( |
| 17 | "github.com/golang/protobuf/proto" |
| 18 | "google.golang.org/protobuf/reflect/protoreflect" |
| 19 | "google.golang.org/protobuf/reflect/protoregistry" |
| 20 | "google.golang.org/protobuf/runtime/protoimpl" |
| 21 | ) |
| 22 | |
| 23 | // AnyResolver takes a type URL, present in an Any message, |
| 24 | // and resolves it into an instance of the associated message. |
| 25 | type AnyResolver interface { |
| 26 | Resolve(typeURL string) (proto.Message, error) |
| 27 | } |
| 28 | |
| 29 | type anyResolver struct{ AnyResolver } |
| 30 | |
| 31 | func (r anyResolver) FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) { |
| 32 | return r.FindMessageByURL(string(message)) |
| 33 | } |
| 34 | |
| 35 | func (r anyResolver) FindMessageByURL(url string) (protoreflect.MessageType, error) { |
| 36 | m, err := r.Resolve(url) |
| 37 | if err != nil { |
| 38 | return nil, err |
| 39 | } |
| 40 | return protoimpl.X.MessageTypeOf(m), nil |
| 41 | } |
| 42 | |
| 43 | func (r anyResolver) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) { |
| 44 | return protoregistry.GlobalTypes.FindExtensionByName(field) |
| 45 | } |
| 46 | |
| 47 | func (r anyResolver) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) { |
| 48 | return protoregistry.GlobalTypes.FindExtensionByNumber(message, field) |
| 49 | } |
| 50 | |
| 51 | func wellKnownType(s protoreflect.FullName) string { |
| 52 | if s.Parent() == "google.protobuf" { |
| 53 | switch s.Name() { |
| 54 | case "Empty", "Any", |
| 55 | "BoolValue", "BytesValue", "StringValue", |
| 56 | "Int32Value", "UInt32Value", "FloatValue", |
| 57 | "Int64Value", "UInt64Value", "DoubleValue", |
| 58 | "Duration", "Timestamp", |
| 59 | "NullValue", "Struct", "Value", "ListValue": |
| 60 | return string(s.Name()) |
| 61 | } |
| 62 | } |
| 63 | return "" |
| 64 | } |
| 65 | |
| 66 | func isMessageSet(md protoreflect.MessageDescriptor) bool { |
| 67 | ms, ok := md.(interface{ IsMessageSet() bool }) |
| 68 | return ok && ms.IsMessageSet() |
| 69 | } |