github.com/polarismesh/polaris@v1.17.8/common/utils/ptypes.go (about)

     1  /**
     2   * Tencent is pleased to support the open source community by making Polaris available.
     3   *
     4   * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
     5   *
     6   * Licensed under the BSD 3-Clause License (the "License");
     7   * you may not use this file except in compliance with the License.
     8   * You may obtain a copy of the License at
     9   *
    10   * https://opensource.org/licenses/BSD-3-Clause
    11   *
    12   * Unless required by applicable law or agreed to in writing, software distributed
    13   * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
    14   * CONDITIONS OF ANY KIND, either express or implied. See the License for the
    15   * specific language governing permissions and limitations under the License.
    16   */
    17  
    18  package utils
    19  
    20  import (
    21  	"bytes"
    22  
    23  	"github.com/golang/protobuf/jsonpb"
    24  	"github.com/golang/protobuf/proto"
    25  	"github.com/golang/protobuf/ptypes/wrappers"
    26  )
    27  
    28  // NewStringValue returns a new StringValue with the given value.
    29  func NewStringValue(value string) *wrappers.StringValue {
    30  	return &wrappers.StringValue{Value: value}
    31  }
    32  
    33  // NewUInt32Value returns a new UInt32Value with the given value.
    34  func NewUInt32Value(value uint32) *wrappers.UInt32Value {
    35  	return &wrappers.UInt32Value{Value: value}
    36  }
    37  
    38  // NewUInt64Value returns a new UInt64Value with the given value.
    39  func NewUInt64Value(value uint64) *wrappers.UInt64Value {
    40  	return &wrappers.UInt64Value{Value: value}
    41  }
    42  
    43  // NewBoolValue returns a new BoolValue with the given value.
    44  func NewBoolValue(value bool) *wrappers.BoolValue {
    45  	return &wrappers.BoolValue{Value: value}
    46  }
    47  
    48  // MarshalToJsonString marshal json message to string
    49  func MarshalToJsonString(message proto.Message) (string, error) {
    50  	marshaler := jsonpb.Marshaler{}
    51  	return marshaler.MarshalToString(message)
    52  }
    53  
    54  // UnmarshalFromJsonString unmarshal message from json string
    55  func UnmarshalFromJsonString(message proto.Message, text string) error {
    56  	unmarshaler := jsonpb.Unmarshaler{}
    57  	buf := bytes.NewBuffer([]byte(text))
    58  	return unmarshaler.Unmarshal(buf, message)
    59  }
    60  
    61  // ConvertSameStructureMessage convert the same structure 2 message
    62  // func ConvertSameStructureMessage(from proto.Message, to proto.Message) error {
    63  //	 sourceJsonText, err := MarshalToJsonString(from)
    64  //	 if nil != err {
    65  //		 return err
    66  //	 }
    67  //	 return UnmarshalFromJsonString(to, sourceJsonText)
    68  // }