Skip to content

Commit

Permalink
Support nil any
Browse files Browse the repository at this point in the history
  • Loading branch information
chriso committed Jun 28, 2024
1 parent beb6bd0 commit f4a1fa5
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
13 changes: 11 additions & 2 deletions dispatchproto/any.go
Original file line number Diff line number Diff line change
Expand Up @@ -437,7 +437,11 @@ func newStructpbValue(rv reflect.Value) (*structpb.Value, error) {
return structpb.NewStringValue(rv.String()), nil
case reflect.Interface:
if rv.NumMethod() == 0 { // interface{} aka. any
return newStructpbValue(reflect.ValueOf(rv.Interface()))
v := rv.Interface()
if v == nil {
return structpb.NewNullValue(), nil
}
return newStructpbValue(reflect.ValueOf(v))
}
case reflect.Slice:
list := &structpb.ListValue{Values: make([]*structpb.Value, rv.Len())}
Expand Down Expand Up @@ -495,7 +499,12 @@ func fromStructpbValue(rv reflect.Value, s *structpb.Value) error {
}
case reflect.Interface:
if rv.NumMethod() == 0 { // interface{} aka. any
rv.Set(reflect.ValueOf(s.AsInterface()))
v := s.AsInterface()
if v == nil {
rv.SetZero()
} else {
rv.Set(reflect.ValueOf(s.AsInterface()))
}
return nil
}
}
Expand Down
2 changes: 1 addition & 1 deletion dispatchproto/any_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -362,7 +362,7 @@ func TestAny(t *testing.T) {
[]bool{true, false, true},
[]float64{3.14, 1.25},
[][]string{{"foo", "bar"}, {"abc", "xyz"}},
[]any{3.14, true, "x"},
[]any{3.14, true, "x", nil},
} {
t.Run(fmt.Sprintf("%v", v), func(t *testing.T) {
boxed, err := dispatchproto.Marshal(v)
Expand Down

0 comments on commit f4a1fa5

Please sign in to comment.