From 8230e09a606bc4406ac15768b470e8051bfdff59 Mon Sep 17 00:00:00 2001 From: CT Wu Date: Thu, 13 Mar 2025 09:53:40 +0800 Subject: [PATCH] feat: add namespace to reflect --- reflect.go | 7 ++++++- reflect_test.go | 43 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/reflect.go b/reflect.go index 36cfb35..67e3453 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 + Namespace string recordTypeCache map[string]reflect.Type } @@ -86,7 +87,11 @@ func (r *Reflector) handleRecord(t reflect.Type) *AvroSchema { return &AvroSchema{Name: name, Type: t.Name()} } - ret := &AvroSchema{Name: name, Type: "record"} + ret := &AvroSchema{ + Name: name, + Type: "record", + Namespace: r.Namespace, + } for i, n := 0, t.NumField(); i < n; i++ { // handle fields f := t.Field(i) diff --git a/reflect_test.go b/reflect_test.go index f64f303..1540e79 100644 --- a/reflect_test.go +++ b/reflect_test.go @@ -618,3 +618,46 @@ func TestGoEmitAllFieldsGoNaming(t *testing.T) { assert.Nil(t, err) assert.JSONEq(t, expected, r) } + +func TestNamespace(t *testing.T) { + type Address struct { + Street string `json:"street"` + City string `json:"city"` + Country string `json:"country"` + } + + type Person struct { + Name string `json:"name"` + Age int `json:"age"` + Address Address `json:"address"` + } + + expected := `{ + "name": "Person", + "type": "record", + "namespace": "com.example", + "fields": [ + {"name": "name", "type": "string"}, + {"name": "age", "type": "int"}, + {"name": "address", "type": { + "name": "Address", + "type": "record", + "namespace": "com.example", + "fields": [ + {"name": "street", "type": "string"}, + {"name": "city", "type": "string"}, + {"name": "country", "type": "string"} + ] + }} + ] + }` + + p := Person{} + r := &Reflector{ + Namespace: "com.example", + } + result, err := r.Reflect(p) + + assert.Nil(t, err) + assert.JSONEq(t, expected, result) +}