Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor marshalling funcs for anypb.Any #45

Merged
merged 1 commit into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
gogoproto "github.com/gogo/protobuf/proto"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/known/anypb"
)

var (
Expand Down Expand Up @@ -196,6 +197,31 @@ func UnmarshalToByTypeURL(typeURL string, value []byte, out interface{}) error {
return err
}

// MarshalProto converts typeurl.Any to google.golang.org/protobuf/types/known/anypb.Any.
func MarshalProto(from Any) *anypb.Any {
if from == nil {
return nil
}

if pbany, ok := from.(*anypb.Any); ok {
return pbany
}

return &anypb.Any{
TypeUrl: from.GetTypeUrl(),
Value: from.GetValue(),
}
}

// MarshalAnyToProto converts an arbitrary interface to google.golang.org/protobuf/types/known/anypb.Any.
func MarshalAnyToProto(from interface{}) (*anypb.Any, error) {
anyType, err := MarshalAny(from)
if err != nil {
return nil, err
}
return MarshalProto(anyType), nil
}

func unmarshal(typeURL string, value []byte, v interface{}) (interface{}, error) {
t, err := getTypeByUrl(typeURL)
if err != nil {
Expand Down
7 changes: 7 additions & 0 deletions types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,13 @@ func TestUnmarshalToInvalid(t *testing.T) {
}
}

func TestFromAny(t *testing.T) {
actual := MarshalProto(nil)
if actual != nil {
t.Fatalf("expected nil, got %v", actual)
}
}

func TestIs(t *testing.T) {
clear()
Register(&test{}, "test")
Expand Down
Loading