github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/go-control-plane/pkg/conversion/struct.go (about)

     1  // Copyright 2018 Envoyproxy Authors
     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  
    15  // Package conversion contains shared utility functions for converting xDS resources.
    16  package conversion
    17  
    18  import (
    19  	"bytes"
    20  	"errors"
    21  
    22  	"github.com/golang/protobuf/jsonpb"
    23  	"github.com/golang/protobuf/proto"
    24  	pstruct "github.com/golang/protobuf/ptypes/struct"
    25  )
    26  
    27  // MessageToStruct encodes a protobuf Message into a Struct. Hilariously, it
    28  // uses JSON as the intermediary
    29  // author:glen@turbinelabs.io
    30  func MessageToStruct(msg proto.Message) (*pstruct.Struct, error) {
    31  	if msg == nil {
    32  		return nil, errors.New("nil message")
    33  	}
    34  
    35  	buf := &bytes.Buffer{}
    36  	if err := (&jsonpb.Marshaler{OrigName: true}).Marshal(buf, msg); err != nil {
    37  		return nil, err
    38  	}
    39  
    40  	pbs := &pstruct.Struct{}
    41  	if err := jsonpb.Unmarshal(buf, pbs); err != nil {
    42  		return nil, err
    43  	}
    44  
    45  	return pbs, nil
    46  }
    47  
    48  // StructToMessage decodes a protobuf Message from a Struct.
    49  func StructToMessage(pbst *pstruct.Struct, out proto.Message) error {
    50  	if pbst == nil {
    51  		return errors.New("nil struct")
    52  	}
    53  
    54  	buf := &bytes.Buffer{}
    55  	if err := (&jsonpb.Marshaler{OrigName: true}).Marshal(buf, pbst); err != nil {
    56  		return err
    57  	}
    58  
    59  	return jsonpb.Unmarshal(buf, out)
    60  }