nicksnyder / go-i18n

Translate your Go program into multiple languages.
MIT License
2.96k stars 271 forks source link

Add context awareness #323

Open dkotik opened 7 months ago

dkotik commented 7 months ago

It is expected for Golang APIs to be context-aware by default. I assume many projects are relying on context to pass a localizer down the call stack as I am doing. It makes sense to scope the context key to the same package.

I added two functions:

nicksnyder commented 7 months ago

Can you be more specific why you need this? It seems like you can pass around a Localizer however you want in your project, but I don't see the benefit of having this as part of the public API.

dkotik commented 7 months ago

@nicksnyder I don't really need this. I just noticed that if you try to localize all the error messages in a project, not just the templates, you are likely to encounter a situation where you have to pass the localizer through the context.

At that point you have to create a new context key in that project and accessors for it.

The idea is that mature projects will do this anyway sooner or later. Having it in the package itself may save humanity some cumulative work hours over the long term.

dkotik commented 6 months ago

@nicksnyder I had another situation come up today that warrants this. I am internationalizing a library, which will be used in an internationalized webservice. Both of those will have a context get/set pair, redundantly.

slsyy commented 4 months ago

It is expected for Golang APIs to be context-aware by default

Context-aware means that you receive ctx in a function/method params and you support cancellation based on that ctx value. In case of that library it does not make sense as there is no IO nor operations are slow.

FromContext, WithContext is for sure useful, but it has nothing in common with the context awareness

dkotik commented 4 months ago

FromContext, WithContext is for sure useful, but it has nothing in common with the context awareness

@slsyy By itself certainly not, but those functions would greese the implementation of context awareness when the library is used.

@nicksnyder Jonathan Amsterdam was adamant about having ContextWithLogger and LoggerFromContext methods for the standard library log/slog package. He folded to peer pressure and they were removed, but he openly stated last Gophercon that he still thinks it was a mistake not to include them. I think he is on to something.