...

Source file src/cloud.google.com/go/internal/protostruct/protostruct.go

Documentation: cloud.google.com/go/internal/protostruct

     1  // Copyright 2017 Google LLC
     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 protostruct supports operations on the protocol buffer Struct message.
    16  package protostruct
    17  
    18  import (
    19  	pb "google.golang.org/protobuf/types/known/structpb"
    20  )
    21  
    22  // DecodeToMap converts a pb.Struct to a map from strings to Go types.
    23  // DecodeToMap panics if s is invalid.
    24  func DecodeToMap(s *pb.Struct) map[string]interface{} {
    25  	if s == nil {
    26  		return nil
    27  	}
    28  	m := map[string]interface{}{}
    29  	for k, v := range s.Fields {
    30  		m[k] = decodeValue(v)
    31  	}
    32  	return m
    33  }
    34  
    35  func decodeValue(v *pb.Value) interface{} {
    36  	switch k := v.Kind.(type) {
    37  	case *pb.Value_NullValue:
    38  		return nil
    39  	case *pb.Value_NumberValue:
    40  		return k.NumberValue
    41  	case *pb.Value_StringValue:
    42  		return k.StringValue
    43  	case *pb.Value_BoolValue:
    44  		return k.BoolValue
    45  	case *pb.Value_StructValue:
    46  		return DecodeToMap(k.StructValue)
    47  	case *pb.Value_ListValue:
    48  		s := make([]interface{}, len(k.ListValue.Values))
    49  		for i, e := range k.ListValue.Values {
    50  			s[i] = decodeValue(e)
    51  		}
    52  		return s
    53  	default:
    54  		panic("protostruct: unknown kind")
    55  	}
    56  }
    57  

View as plain text