From 968546fd12788c5d445ec4cc6315d17b2ce76c8c Mon Sep 17 00:00:00 2001 From: Masayoshi Mizutani Date: Wed, 13 Nov 2024 07:52:44 +0900 Subject: [PATCH] Update default tag key with custom tag key handling --- masq.go | 6 +++++- options.go | 6 +++++- options_test.go | 10 ++++++++++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/masq.go b/masq.go index 669ed59..fa32e6b 100644 --- a/masq.go +++ b/masq.go @@ -8,6 +8,10 @@ import ( ) const ( + // DefaultTagKey is a default key name of struct tag for masq. WithCustomTagKey option can change this value. + DefaultTagKey = "masq" + + // DefaultRedactMessage is a default message to replace redacted value. WithRedactMessage option can change this value. DefaultRedactMessage = "[REDACTED]" ) @@ -31,7 +35,7 @@ func newMasq(options ...Option) *masq { m := &masq{ redactMessage: DefaultRedactMessage, allowedTypes: map[reflect.Type]struct{}{}, - tagKey: "masq", + tagKey: DefaultTagKey, } m.defaultRedactor = func(src, dst reflect.Value) bool { switch src.Kind() { diff --git a/options.go b/options.go index 971c90b..4d306a9 100644 --- a/options.go +++ b/options.go @@ -35,8 +35,12 @@ func WithTag(tag string, redactors ...Redactor) Option { return WithCensor(newTagCensor(tag), redactors...) } -// WithCustomTagKey is an option to set the custom tag key. The default tag key is `masq`. +// WithCustomTagKey is an option to set the custom tag key. The default tag key is `masq`. If the field has the target tag in the custom tag key AND the field is matched with the target tag specified by WithTag, the field will be redacted. If tagKey is empty, WithCustomTagKey panics. func WithCustomTagKey(tagKey string) Option { + if tagKey == "" { + panic("masq: tag key must not be empty") + } + return func(m *masq) { m.tagKey = tagKey } diff --git a/options_test.go b/options_test.go index 3a48ed0..c4fe300 100644 --- a/options_test.go +++ b/options_test.go @@ -149,6 +149,16 @@ func ExampleWithCustomTagKey() { // {"level":"INFO","msg":"Got record","record":{"EMail":"[REDACTED]","ID":"m-mizutani"},"time":"2022-12-25T09:00:00.123456789"} } +func TestCustomTagKeyPanic(t *testing.T) { + defer func() { + if recover() == nil { + t.Errorf("Failed to panic") + } + }() + + masq.New(masq.WithCustomTagKey("")) +} + func ExampleWithFieldName() { out := &fixedTimeWriter{}