Skip to content

Commit

Permalink
Merge pull request #24 from m-mizutani/fix/json-unmarshal-type-error
Browse files Browse the repository at this point in the history
fix(clone): Ignore `reflect.rtype`
  • Loading branch information
m-mizutani authored Dec 9, 2024
2 parents 8100258 + 403f373 commit 351da57
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
10 changes: 10 additions & 0 deletions clone.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,13 @@ const (
maxDepth = 32
)

var (
// ignoreTypes is a map of types that should not be redacted. It lists types that can not be copied. For example, reflect.Type is a pointer to a struct and copying it causes panic. Especially, reflect.rtype is unexported type. Then, the ignoreTypes is list of string of type name.
ignoreTypes = map[string]struct{}{
"*reflect.rtype": {},
}
)

func (x *masq) clone(ctx context.Context, fieldName string, src reflect.Value, tag string) reflect.Value {
if v, ok := ctx.Value(ctxKeyDepth{}).(int); !ok {
ctx = context.WithValue(ctx, ctxKeyDepth{}, 0)
Expand All @@ -26,6 +33,9 @@ func (x *masq) clone(ctx context.Context, fieldName string, src reflect.Value, t
if _, ok := x.allowedTypes[src.Type()]; ok {
return src
}
if _, ok := ignoreTypes[src.Type().String()]; ok {
return src
}

if src.Kind() == reflect.Ptr && src.IsNil() {
return reflect.New(src.Type()).Elem()
Expand Down
18 changes: 18 additions & 0 deletions clone_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -343,3 +343,21 @@ func TestCircularReference(t *testing.T) {
newData := c.Redact(data).(*myStruct)
gt.V(t, newData.Child.Child.Str).Equal("[REDACTED]")
}

func TestCloneFunc(t *testing.T) {
type myFunc func() string
src := myFunc(func() string { return "blue" })
dst := masq.NewMasq().Redact(src).(myFunc)
gt.Equal(t, dst(), "blue")
}

func TestUnmarshalTypeError(t *testing.T) {
var buf bytes.Buffer
logger := slog.New(slog.NewJSONHandler(&buf, &slog.HandlerOptions{
ReplaceAttr: masq.New(),
}))
var s string
err := json.Unmarshal([]byte(`["foo"]`), &s)
logger.Info("error", slog.Any("err", err))
gt.S(t, buf.String()).Contains("error")
}

0 comments on commit 351da57

Please sign in to comment.