Skip to content
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
10 changes: 10 additions & 0 deletions broker/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package common
import (
"fmt"
"reflect"
"strings"
)

func StructToMap(obj interface{}) (map[string]interface{}, error) {
Expand All @@ -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()
}

Expand Down
19 changes: 11 additions & 8 deletions broker/common/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion broker/events/eventmodels.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const (

type EventData struct {
CommonEventData
CustomData map[string]any
CustomData map[string]any `json:"customData,omitempty"`
}

type CommonEventData struct {
Expand Down
Loading