logoalt Hacker News

sluongng01/21/20254 repliesview on HN

Let me try to take the other side:

`ctx.Value` is an `any -> any` kv store that does not come with any documentation, type checking for which key and value should be available. It's quick and dirty, but in a large code base, it can be quite tricky to check if you are passing too many values down the chain, or too little, and handle the failure cases.

What if you just use a custom struct with all the fields you may need to be defined inside? Then at least all the field types are properly defined and documented. You can also use multiple custom "context" structs in different call paths, or even compose them if there are overlapping fields.


Replies

Thaxll01/21/2025

Because you should wrapp that in a type safe function. You should not use the context.GetValue() directly but use your own function, the context is just a transport mechanism.

show 1 reply
bluetech01/21/2025

> `ctx.Value` is an `any -> any` kv store that does not come with any documentation, type checking for which key and value should be available

The docs https://pkg.go.dev/context#Context suggest a way to make it type-safe (use an unexported key type and provide getter/setter). Seems fine to me.

> What if you just use a custom struct with all the fields you may need to be defined inside?

Can't seamlessly cross module boundaries.

smarkov01/21/2025

> `ctx.Value` is an `any -> any` kv store that does not come with any documentation, type checking for which key and value should be available.

On a similar note, this is also why I highly dislike struct tags. They're string magic that should be used sparingly, yet we've integrated them into data parsing, validation, type definitions and who knows what else just to avoid a bit of verbosity.

show 1 reply
throw_m23933901/21/2025

> `ctx.Value` is an `any -> any`

It did not have to be this way, this is a shortcoming of Go itself. Generic interfaces makes things a bit better, but Go designers chose that dumb typing at first place. The std lib is full of interface {} use iteself.

context itself is an after thought, because people were building thread unsafe leaky code on top of http request with no good way to easily scope variables that would scale concurrently.

I remember the web session lib for instance back then, a hack.

ctx.Value is made for each go routine scoped data, that's the whole point.

If it is an antipattern well, it is an antipattern designed by go designers themselves.