diff --git a/broker/common/common.go b/broker/common/common.go index 2421e8c4..9106e210 100644 --- a/broker/common/common.go +++ b/broker/common/common.go @@ -3,6 +3,7 @@ package common import ( "fmt" "reflect" + "strings" ) func StructToMap(obj interface{}) (map[string]interface{}, error) { @@ -22,6 +23,15 @@ func StructToMap(obj interface{}) (map[string]interface{}, error) { for i := 0; i < val.NumField(); i++ { field := val.Field(i) fieldName := typ.Field(i).Name + jsonTag, ok := typ.Field(i).Tag.Lookup("json") + if ok { + before, _, found := strings.Cut(jsonTag, ",") + if found { + fieldName = before + } else { + fieldName = jsonTag + } + } result[fieldName] = field.Interface() } diff --git a/broker/common/common_test.go b/broker/common/common_test.go index 35f58ebb..5c14bca9 100644 --- a/broker/common/common_test.go +++ b/broker/common/common_test.go @@ -6,11 +6,14 @@ import ( ) type User struct { - ID int - Name string + ID int `json:"id"` + Name *string `json:"name,omitempty"` Active bool } +var bob = "Bob" +var alice = "Alice" + func TestStructToMap(t *testing.T) { tests := []struct { name string @@ -20,20 +23,20 @@ func TestStructToMap(t *testing.T) { }{ { name: "Basic struct conversion", - input: User{ID: 1, Name: "Alice", Active: true}, + input: User{ID: 1, Name: &alice, Active: true}, want: map[string]interface{}{ - "ID": 1, - "Name": "Alice", + "id": 1, + "name": &alice, "Active": true, }, wantErr: false, }, { name: "Pointer to struct", - input: &User{ID: 2, Name: "Bob", Active: false}, + input: &User{ID: 2, Name: &bob, Active: false}, want: map[string]interface{}{ - "ID": 2, - "Name": "Bob", + "id": 2, + "name": &bob, "Active": false, }, wantErr: false, diff --git a/broker/events/eventmodels.go b/broker/events/eventmodels.go index ef4b7080..fcbf369c 100644 --- a/broker/events/eventmodels.go +++ b/broker/events/eventmodels.go @@ -58,7 +58,7 @@ const ( type EventData struct { CommonEventData - CustomData map[string]any + CustomData map[string]any `json:"customData,omitempty"` } type CommonEventData struct {