mirror of
https://github.com/pomerium/pomerium.git
synced 2025-05-22 05:27:13 +02:00
protoutil: add support for converting arbitrary protobuf messages into structs (#3106)
This commit is contained in:
parent
8cc9c9c8fb
commit
9e4edb8003
2 changed files with 14 additions and 0 deletions
|
@ -5,6 +5,8 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
|
||||||
|
"google.golang.org/protobuf/encoding/protojson"
|
||||||
|
"google.golang.org/protobuf/proto"
|
||||||
"google.golang.org/protobuf/types/known/structpb"
|
"google.golang.org/protobuf/types/known/structpb"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -45,6 +47,15 @@ func ToStruct(value interface{}) *structpb.Value {
|
||||||
return NewStructNumber(float64(v))
|
return NewStructNumber(float64(v))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if msg, ok := value.(proto.Message); ok {
|
||||||
|
bs, _ := protojson.Marshal(msg)
|
||||||
|
var s structpb.Struct
|
||||||
|
_ = protojson.Unmarshal(bs, &s)
|
||||||
|
return &structpb.Value{
|
||||||
|
Kind: &structpb.Value_StructValue{StructValue: &s},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
rv := reflect.ValueOf(value)
|
rv := reflect.ValueOf(value)
|
||||||
switch rv.Kind() {
|
switch rv.Kind() {
|
||||||
case reflect.Slice:
|
case reflect.Slice:
|
||||||
|
|
|
@ -3,6 +3,8 @@ package protoutil
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"google.golang.org/protobuf/types/known/apipb"
|
||||||
|
|
||||||
"github.com/pomerium/pomerium/internal/testutil"
|
"github.com/pomerium/pomerium/internal/testutil"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -28,6 +30,7 @@ func TestToValue(t *testing.T) {
|
||||||
{"uint64", uint64(1), "1"},
|
{"uint64", uint64(1), "1"},
|
||||||
{"[]interface{}", []interface{}{1, 2, 3, 4}, `[1,2,3,4]`},
|
{"[]interface{}", []interface{}{1, 2, 3, 4}, `[1,2,3,4]`},
|
||||||
{"map[string]interface{}", map[string]interface{}{"k1": "v1", "k2": "v2"}, `{"k1":"v1","k2":"v2"}`},
|
{"map[string]interface{}", map[string]interface{}{"k1": "v1", "k2": "v2"}, `{"k1":"v1","k2":"v2"}`},
|
||||||
|
{"Message", &apipb.Method{Name: "example"}, `{"name": "example"}`},
|
||||||
}
|
}
|
||||||
for _, tc := range testCases {
|
for _, tc := range testCases {
|
||||||
tc := tc
|
tc := tc
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue