Skip to content

Commit

Permalink
Ensure gRPC struct data is always a (nested) string map.
Browse files Browse the repository at this point in the history
  • Loading branch information
adewes committed Sep 15, 2021
1 parent b494a57 commit 48aa25c
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 2 deletions.
13 changes: 11 additions & 2 deletions grpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"context"
"fmt"
"github.com/iris-connect/eps"
"github.com/iris-connect/eps/helpers"
epsNet "github.com/iris-connect/eps/net"
"github.com/iris-connect/eps/protobuf"
"github.com/iris-connect/eps/tls"
Expand Down Expand Up @@ -227,7 +228,11 @@ func (s *Server) Call(context context.Context, pbRequest *protobuf.Request) (*pr
}
if response != nil {
if response.Result != nil {
resultStruct, err := structpb.NewStruct(response.Result)
stringMap, err := helpers.ToStringMap(response.Result)
if err != nil {
return nil, fmt.Errorf("error converting result to string map: %w", err)
}
resultStruct, err := structpb.NewStruct(stringMap)
if err != nil {
return nil, fmt.Errorf("error serializing response for gRPC: %w", err)
}
Expand All @@ -240,7 +245,11 @@ func (s *Server) Call(context context.Context, pbRequest *protobuf.Request) (*pr
}

if response.Error.Data != nil {
errorStruct, err := structpb.NewStruct(response.Error.Data)
stringMap, err := helpers.ToStringMap(response.Error.Data)
if err != nil {
return nil, fmt.Errorf("error converting error data to string map: %w", err)
}
errorStruct, err := structpb.NewStruct(stringMap)
if err != nil {
return nil, fmt.Errorf("error serializing error data for gRPC: %w", err)
}
Expand Down
17 changes: 17 additions & 0 deletions helpers/structs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package helpers

import (
"encoding/json"
)

// convert an arbitrary structure to a string map via the JSON encoding
func ToStringMap(value interface{}) (map[string]interface{}, error) {
var out map[string]interface{}
if jsonData, err := json.Marshal(value); err != nil {
return nil, err
} else if err := json.Unmarshal(jsonData, &out); err != nil {
return nil, err
} else {
return out, nil
}
}

0 comments on commit 48aa25c

Please sign in to comment.