github.com/blend/go-sdk@v1.20220411.3/protoutil/any.go (about)

     1  /*
     2  
     3  Copyright (c) 2022 - Present. Blend Labs, Inc. All rights reserved
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file.
     5  
     6  */
     7  
     8  package protoutil
     9  
    10  import (
    11  	"strings"
    12  
    13  	"github.com/golang/protobuf/ptypes/any"
    14  	"google.golang.org/protobuf/proto"
    15  	"google.golang.org/protobuf/reflect/protoregistry"
    16  	"google.golang.org/protobuf/types/known/anypb"
    17  
    18  	"github.com/blend/go-sdk/ex"
    19  )
    20  
    21  // TypeURLPrefix is the type url prefix for type urls.
    22  const TypeURLPrefix = "type.googleapis.com/"
    23  
    24  // Any packs a message as an Any.
    25  func Any(msg proto.Message) (*any.Any, error) {
    26  	m, err := anypb.New(msg)
    27  	if err != nil {
    28  		return nil, ex.New(err)
    29  	}
    30  	return &any.Any{
    31  		TypeUrl: m.TypeUrl,
    32  		Value:   m.Value,
    33  	}, nil
    34  }
    35  
    36  // FromAny unpacks a message any into a type message.
    37  func FromAny(m *any.Any) (proto.Message, error) {
    38  	if m == nil {
    39  		return nil, ex.New("cannot unpack message from nil *any.Any")
    40  	}
    41  	return anypb.UnmarshalNew(&anypb.Any{
    42  		TypeUrl: m.TypeUrl,
    43  		Value:   m.Value,
    44  	}, proto.UnmarshalOptions{
    45  		AllowPartial: true,
    46  	})
    47  }
    48  
    49  // FromTypeURL returns a message from the global types proto registry.
    50  func FromTypeURL(typeURL string) (proto.Message, error) {
    51  	if !strings.HasPrefix(typeURL, TypeURLPrefix) {
    52  		typeURL = TypeURLPrefix + typeURL
    53  	}
    54  	mt, err := protoregistry.GlobalTypes.FindMessageByURL(typeURL)
    55  	if err != nil {
    56  		return nil, ex.New(err)
    57  	}
    58  	return mt.New().Interface(), nil
    59  }
    60  
    61  // TypeURL returns the typeURL for a given message.
    62  //
    63  // The bulk of this method was lifted from the anypb source.
    64  func TypeURL(msg proto.Message) string {
    65  	return TypeURLPrefix + string(MessageTypeName(msg))
    66  }
    67  
    68  // MessageTypeFromTypeURL returns the message type from a given any type url.
    69  func MessageTypeFromTypeURL(typeURL string) string {
    70  	return strings.TrimPrefix(typeURL, TypeURLPrefix)
    71  }