ctx: Modify WithContext to use a non-pointer receiver (#409)

This commit is contained in:
Nick Corin 2022-02-24 02:17:11 +02:00 committed by GitHub
parent 361cdf616a
commit 588a61c2df
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 7 additions and 7 deletions

6
ctx.go
View File

@ -25,9 +25,9 @@ type ctxKey struct{}
// l.UpdateContext(func(c Context) Context { // l.UpdateContext(func(c Context) Context {
// return c.Str("bar", "baz") // return c.Str("bar", "baz")
// }) // })
func (l *Logger) WithContext(ctx context.Context) context.Context { func (l Logger) WithContext(ctx context.Context) context.Context {
if lp, ok := ctx.Value(ctxKey{}).(*Logger); ok { if lp, ok := ctx.Value(ctxKey{}).(*Logger); ok {
if lp == l { if lp == &l {
// Do not store same logger. // Do not store same logger.
return ctx return ctx
} }
@ -35,7 +35,7 @@ func (l *Logger) WithContext(ctx context.Context) context.Context {
// Do not store disabled logger. // Do not store disabled logger.
return ctx return ctx
} }
return context.WithValue(ctx, ctxKey{}, l) return context.WithValue(ctx, ctxKey{}, &l)
} }
// Ctx returns the Logger associated with the ctx. If no logger // Ctx returns the Logger associated with the ctx. If no logger

View File

@ -45,7 +45,7 @@ func TestCtxDisabled(t *testing.T) {
l := New(ioutil.Discard).With().Str("foo", "bar").Logger() l := New(ioutil.Discard).With().Str("foo", "bar").Logger()
ctx = l.WithContext(ctx) ctx = l.WithContext(ctx)
if Ctx(ctx) != &l { if !reflect.DeepEqual(Ctx(ctx), &l) {
t.Error("WithContext did not store logger") t.Error("WithContext did not store logger")
} }
@ -53,18 +53,18 @@ func TestCtxDisabled(t *testing.T) {
return c.Str("bar", "baz") return c.Str("bar", "baz")
}) })
ctx = l.WithContext(ctx) ctx = l.WithContext(ctx)
if Ctx(ctx) != &l { if !reflect.DeepEqual(Ctx(ctx), &l) {
t.Error("WithContext did not store updated logger") t.Error("WithContext did not store updated logger")
} }
l = l.Level(DebugLevel) l = l.Level(DebugLevel)
ctx = l.WithContext(ctx) ctx = l.WithContext(ctx)
if Ctx(ctx) != &l { if !reflect.DeepEqual(Ctx(ctx), &l) {
t.Error("WithContext did not store copied logger") t.Error("WithContext did not store copied logger")
} }
ctx = dl.WithContext(ctx) ctx = dl.WithContext(ctx)
if Ctx(ctx) != &dl { if !reflect.DeepEqual(Ctx(ctx), &dl) {
t.Error("WithContext did not override logger with a disabled logger") t.Error("WithContext did not override logger with a disabled logger")
} }
} }