Re:Better HTTP server routing in Go 1.22
by earthboundkid on Monday October 16, 2023 @12:53PM
(#37902692)
Go's flag, log, image, and sql packages all work this way, so it's not just the HTTP router. I sort of see both sides. Having implicit registration makes it very easy to have different teams working on different packages and you just import the package and it registers itself. But it also makes the behavior of the resulting final binary hard to understand and based on implicit code instead of explicit. I personally try to just have one big routes() http.Handler function that returns everything all in one place, but I get why that isn't always practical.
[ Parent
| on HN ]
Re:Better HTTP server routing in Go 1.22
by silasdavis on Monday October 16, 2023 @01:46PM
(#37903488)
It doesn't feel to me like much of a gain over having said team expose a specific default self registration function. Then that act can be explicit rather than action at a distance on some dependency defined global state.
I think this pattern in the standard library is a mistake.
Yeah, the trade-off is literally:
import _ "thing"
Vs: import "thing"
thing.Register()
But one uses a strange construct to save a single line, loses the ability to control order, and encourages people to use globals that they can't control.thing.Register() may register a route that conflicts with yours and it will never be matched in this case if declaration order was taken into account.
You may discover this too late when you either have missed important calls on that thing or when requests intended for that thing are causing unintended effects on your first declared route.
That is all also true when doing the same thing in an init func.
I very much dislike import side effects in any language. Im a lot happier where thing.Register() is still forced to happen in the main function.
Still, I can understand it for some components like loggers to not add boiler plate to every library. However, I was very uneasy to see that enabling gzip decompression in a gRPC server is done through a magic _ import. You have to initialize the server anyways, so why not just make it an explicit function argument?
Well, yeah, with the "implicit registration" model you can either split it up or do it in a central place, whereas if they would require you to do it in a central place, you wouldn't have that choice. It probably boils down to "library" vs. "framework" - Go's standard library doesn't want (as much as possible) to be a framework that forces you to do things its way, and as far as I'm concerned that's ok...