go.fuchsia.dev/infra@v0.0.0-20240507153436-9b593402251b/cmd/roller-configurator/proto/util.go (about)

     1  // Copyright 2023 The Fuchsia Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style license that can be
     3  // found in the LICENSE file.
     4  
     5  package proto
     6  
     7  import (
     8  	"encoding/json"
     9  
    10  	"google.golang.org/protobuf/encoding/protojson"
    11  	"google.golang.org/protobuf/proto"
    12  )
    13  
    14  // ProtoToMap converts a proto message to a Go map.
    15  func ProtoToMap(m proto.Message) (map[string]any, error) {
    16  	opts := protojson.MarshalOptions{
    17  		UseProtoNames:   true,
    18  		EmitUnpopulated: true,
    19  	}
    20  	b, err := opts.Marshal(m)
    21  	if err != nil {
    22  		return nil, err
    23  	}
    24  	res := make(map[string]any)
    25  	if err := json.Unmarshal(b, &res); err != nil {
    26  		return nil, err
    27  	}
    28  	return res, nil
    29  }