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
7 changes: 7 additions & 0 deletions reflect.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type Reflector struct {
EmitAllFields bool // don't skip struct fields which have no struct tags
SkipTagFieldNames bool // don't use json/bson tag names, even if theyre present
Mapper func(reflect.Type) any
NameMapping map[string]string // 改用 map
Namespace string
recordTypeCache map[string]reflect.Type
}
Expand Down Expand Up @@ -83,6 +84,12 @@ func (r *Reflector) handleRecord(t reflect.Type) *AvroSchema {
tokens := strings.Split(name, ".")
name = tokens[len(tokens)-1]

if r.NameMapping != nil {
if mappedName, ok := r.NameMapping[name]; ok {
name = mappedName
}
}

if _, ok := r.recordTypeCache[t.Name()]; ok {
return &AvroSchema{Name: name, Type: t.Name()}
}
Expand Down
27 changes: 27 additions & 0 deletions reflect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -661,3 +661,30 @@ func TestNamespace(t *testing.T) {
assert.Nil(t, err)
assert.JSONEq(t, expected, result)
}

func TestNameMapping(t *testing.T) {
type MyStruct struct {
Field string `json:"field"`
}

expected := `{
"name": "CustomName",
"type": "record",
"namespace": "com.example",
"fields": [
{"name": "field", "type": "string"}
]
}`

e := MyStruct{}
r := &Reflector{
Namespace: "com.example",
NameMapping: map[string]string{
"MyStruct": "CustomName",
},
}
result, err := r.Reflect(e)

assert.Nil(t, err)
assert.JSONEq(t, expected, result)
}