diff --git a/reflect.go b/reflect.go index 67e3453..d25ce35 100644 --- a/reflect.go +++ b/reflect.go @@ -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 } @@ -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()} } diff --git a/reflect_test.go b/reflect_test.go index 1540e79..3266ad9 100644 --- a/reflect_test.go +++ b/reflect_test.go @@ -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) +}