Skip to content
This repository has been archived by the owner on Sep 15, 2023. It is now read-only.

chore(eredis): avoid collisions between packages using context #178

Merged
merged 2 commits into from
Apr 10, 2022

Conversation

zcong1993
Copy link
Contributor

@zcong1993 zcong1993 commented Apr 7, 2022

@zcong1993 zcong1993 changed the title chore(eredis): avoid collisions between packages using context, fix h… chore(eredis): avoid collisions between packages using context Apr 7, 2022
@askuy
Copy link
Contributor

askuy commented Apr 9, 2022

thanks for your pr. we can do it better, please fix like this: https://github.com/gotomicro/ego/blob/34fbc797c77cbdfe6d6b057af80c3de45cfec291/client/ehttp/interceptor.go#L79
https://stackoverflow.com/questions/40891345/fix-should-not-use-basic-type-string-as-key-in-context-withvalue-golint https://blog.golang.org/context#TOC_3.2. https://golang.org/pkg/context/#WithValue

done

Use type struct{} much better.

type ctxKey struct{} // or exported to use outside the package

ctx = context.WithValue(ctx, ctxKey{}, 123)
fmt.Println(ctx.Value(ctxKey{}).(int) == 123) // true
Reference: https://golang.org/pkg/context/#WithValue

The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context. Users of WithValue should define their own types for keys. To avoid allocating when assigning to an interface{}, context keys often have concrete type struct{}. Alternatively, exported context key variables' static type should be a pointer or interface.

@zcong1993
Copy link
Contributor Author

thanks for your pr. we can do it better, please fix like this: https://github.com/gotomicro/ego/blob/34fbc797c77cbdfe6d6b057af80c3de45cfec291/client/ehttp/interceptor.go#L79
https://stackoverflow.com/questions/40891345/fix-should-not-use-basic-type-string-as-key-in-context-withvalue-golint https://blog.golang.org/context#TOC_3.2. https://golang.org/pkg/context/#WithValue

done

Use type struct{} much better.

type ctxKey struct{} // or exported to use outside the package

ctx = context.WithValue(ctx, ctxKey{}, 123) fmt.Println(ctx.Value(ctxKey{}).(int) == 123) // true Reference: https://golang.org/pkg/context/#WithValue

The provided key must be comparable and should not be of type string or any other built-in type to avoid collisions between packages using context. Users of WithValue should define their own types for keys. To avoid allocating when assigning to an interface{}, context keys often have concrete type struct{}. Alternatively, exported context key variables' static type should be a pointer or interface.

already use type struct{}

@askuy askuy merged commit 658e72b into gotomicro:master Apr 10, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants