Why The Golang 1.22 HTTP Router Is Not Great

  Рет қаралды 13,181

Anthony GG

Anthony GG

2 ай бұрын

► Join my Discord community for free education 👉 / discord
► Exclusive Lessons, Mentorship, And Videos 👉 / anthonygg_
► 33% OFF on my Go + HTMX + Templ Course PRESALE 👉bit.ly/3UFruxO
► Enjoy a 60% Black Friday Discount on My Golang Course 👉 fulltimegodev.com
► Learn how I became a self-taught software engineer 👉fulltimegodev.com/#mystory
► Follow me on Twitter 👉 / anthdm
► Follow me on GitHub 👉 github.com/anthdm
Grab yourself a 33% OFF on the PRESALE event of my building production ready applications with GO + HTMX + Templ + Tailwindcss + JQuery course here: bit.ly/3UFruxO
SUBSCRIBE OR NO MARGARITAS
╔═╦╗╔╦╗╔═╦═╦╦╦╦╗╔═╗
║╚╣║║║╚╣╚╣╔╣╔╣║╚╣═╣
╠╗║╚╝║║╠╗║╚╣║║║║║═╣
╚═╩══╩═╩═╩═╩╝╚╩═╩═╝

Пікірлер: 88
@anthonygg_
@anthonygg_ 2 ай бұрын
► 33% OFF on my Go + HTMX + Templ Course PRESALE 👉bit.ly/3UFruxO ► Join my Discord community for free education 👉 discord.com/invite/Ac7CWREe58 ► Exclusive Lessons, Mentorship, And Videos 👉 www.patreon.com/anthonygg_ ► 60% OFF on my Golang course 👉 fulltimegodev.com Thanks for watching
@ferdinandsteenkamp1333
@ferdinandsteenkamp1333 2 ай бұрын
I don't agree that the stdlib handler should return an error, how would that error be handled (other than closing the server)?. I do, however, create my own handler type that returns an error so that I can pass results to middlewares. By not returning an error, the stdlib is forcing you to handle the error...which is the correct behaviour.
@trexiath
@trexiath 2 ай бұрын
I used to use middleware for error handling in net/http, but have migrated to using a wrapper function called WithError that accepts a handler func that returns an error, and an error handler func that takes an error and the request/resp writer. WithError just returns a new handlefunc that calls the provided handler and calls the error handler if it returns err...but, even then, i find myself using that very rarely because i prefer to deal with errors in the handler itself, right where they crop up, as is the go way xD
@yarcat
@yarcat Ай бұрын
Yup, error handling is done like that, because HTTP handlers are terminal functions. The only purpose of the handlers is to parse requests, call something and write output. And this is application/service specific.
@jay.rhoden
@jay.rhoden 25 күн бұрын
I see what he is saying in the video, but I also don't agree. Pushing the error handling out of the context of the request handler would feel convenient, but it would also be against the spirit of Go in my personal opinion. There's not _that_ much difference between returning with an error, or calling a function to output an error.
@gordonfreimann
@gordonfreimann 5 күн бұрын
EXACTLY what i was thinking. what a waste of a complaint here. “just return err and forget about it” lol. And this guy decides how a good engineer should be
@JoeyJurjens
@JoeyJurjens 2 ай бұрын
I agree that you don't need to stop using other routers. However, I've had a few projects now that are fine with those improvements. Dreams Of Code uploaded a video a few days ago, where he went in depth of the new router which also gives examples for middleware chaining & sub routers, which isn't as much boilerplate as you expect.
@zyracelreyes3059
@zyracelreyes3059 2 ай бұрын
That video was really good. I wasn't happy with the Gin router because I couldn't figure out a way to handle without an http.Method. I would like to refactor back to stdlib and that video truly shows me what I can do.
@susiebaka3388
@susiebaka3388 2 ай бұрын
That was a good video, but it sort of proves the point that you can still just use Chi instead of following all those idioms. It's a good video. But you can still just use chi which has been good for a while
@JoeyJurjens
@JoeyJurjens 2 ай бұрын
@@susiebaka3388Yeah I agree, that's why I said you don't need to stop using other routers. They come with benefits and probably a nicer API.
@JohanStrandOne
@JohanStrandOne 2 ай бұрын
I usually agree with Anthony most of the time but... For once I don't agree with most points he's making. Opinion incoming: Anything that doesn't "have to" return an error shouldn't. Grouping and middlewear is fairly straightforward. Boils down to the fact that I'd rather maintain 20 lines I wrote to hide away whatever annoys me, over depending on a framework. I do believe there are reasons to use libraries but these aren't the reasons. Currently my strategy is to go without dependencies until I have a clear reason to add one. I guess I'm old-fashioned 😂
@matiasbpg
@matiasbpg 2 ай бұрын
There is no built in grouping, but because mux is a http.Handler, you can make child routers that manage the grouping. For example, config a mux AdminMux :=.... And set it routes. The you can use middlewere for the whole mux ( because it's an http.Handler) and pass this mux to the parent mux for the route /admin/ ( always forget it's the training slash is necessary). You can also omit de admin prefix in the child router bit that requires the extra step of triming the request url with a middlewere before the adminMux can process the request
@vitiok78
@vitiok78 2 ай бұрын
Handler functions run as goroutines. There's no point in returning errors. All error handling must be inside. Fiber uses panics to handle those errors. I hate when people use panics as the standard use case. Panic must be the serious exception not the regular error
@anthonygg_
@anthonygg_ 2 ай бұрын
You are missing an important point. The error is key. Trust me. Running a million dollar company on this.
@potassium5703
@potassium5703 2 ай бұрын
handlefunc is func what implements handler interface, i think you can change handlerfunc just a little bit for better error handling you can write your custom HandleFuncWithError just like that: func (f HandleFunc) ServeHTTP(w, r) { err := f(w,r) }
@arturfil
@arturfil 2 ай бұрын
Any router that adheres to the std lib, a created handler doesn't return an error. The error comes from the service that's called within the handler in any case
@comedyclub333
@comedyclub333 5 күн бұрын
I mean, yes, it's not a replacement for the plethora of frameworks out there. But sometimes you want some bare-bones HTTP server with just a handful of fixed routes (e.g. for a simple UI or for providing a websocket server in your otherwise non-web app or something). And for that the changes make things way easier than before.
@stefanbogdanovic590
@stefanbogdanovic590 2 ай бұрын
We are using Go Fiber at work, and we are quite satisfied with it, easy to use, has error handler. Love it, good video Antonio :D
@raptorate2872
@raptorate2872 2 ай бұрын
Thank you again for the knowledge, I have taken your advice and playing around with Go + HTMX. For developing and deployment, you advice against containers and I see that you have a WSL Ubuntu installation you directly working in. Could you elaborate why you prefer that way to develop ?
@Omikronik
@Omikronik Ай бұрын
Hes on windows
@raptorate2872
@raptorate2872 Ай бұрын
@@Omikronik he is but he is working on Ubuntu through Windows WSL. You can see it in his VSCode connections tab at the bottom left, highlighted in blue in his case.
@0zema
@0zema 2 ай бұрын
Agreed, centralized error handling is not a luxury, it's a necessity for larger projects, I find myself going back to Echo time and time again.
@inaccessiblecardinal9352
@inaccessiblecardinal9352 2 ай бұрын
I'm pleased with the loops versus pointers change. I pulled some code from last year and a func I knew was broken just worked on my new work computer. Wasn't even paying attention, and voila!Almost like I knew what I was doing.
@asparkoffire220
@asparkoffire220 2 ай бұрын
Fiber is one of the best frameworks but one of the reasons I switched from Fiber to Gin was that Fiber is built on top of fasthttp which doesn’t support response flushing, and hence there is no easy way to Implement server-sent events (SSEs) in fiber.
@RA-xx4mz
@RA-xx4mz 2 ай бұрын
I switched from Gin to Echo because I like specifying params and a return type for my handlers. Gin just takes in context. Ironically, gin is “martini-like”, but one of the best parts of martini is that it has typed params and return types.
@rogerramjet69
@rogerramjet69 Ай бұрын
Bro your a smart guy... write your own simple router using 1.22... I would love to see what you come up with.
@hobord
@hobord 2 ай бұрын
If I have error in handler then I usually do an error reponse (ResponseWriter). Also I can indicate the error with adding into the request context. If the handler is in the middleware chain...
@cureadvocate1
@cureadvocate1 2 ай бұрын
I agree on returning error. Adding a net/http/v2 would be nice, though. Or an adapter on ServeMux to generate an updated mux.
@kaspariito
@kaspariito 2 ай бұрын
for the next one -> show how would you build a small vanilla project using mux and new router possibilities, even if not your favorite way to do it :/ :( :) thanks for great content!!
@DeanRTaylor
@DeanRTaylor 2 ай бұрын
Interesting video, in my opinion using the std lib in go makes sense for a couple of rewsons, firstly because you'll be a better developer. Secondly I have worked on projects that outlasted frameworks, packages and ORMs which means you have to maintain these packages yourself. Sure you might be more productive now, but in five years? Ten years? I guess it depends how long you think the project will go and how big the team is. As with most things there are trade offs. I think these changes definitely make it more straightforward for me to use the std lib or a package that has no dependencies but does some of the boiler plate in advance.
@jeffreysmith9837
@jeffreysmith9837 Ай бұрын
Stdlib + htmx is enough when you are solo dev and want the benefit of never needing to maintain the project once it's done. Which can be really nice sometimes. But the larger the team gets, the more necessary a 3rd party library/framework becomes. Would you agree?
@awesomedavid2012
@awesomedavid2012 2 ай бұрын
I think it is an improvement, but it still requires a lot of boilerplate. I also prefer handlers that return errors like with Fiber or Echo. It may be a nitpick, but I also don't like how large the parameter types are. EDIT: yeah, it seems like you agree.
@Microphunktv-jb3kj
@Microphunktv-jb3kj 2 ай бұрын
wich one would u suggest Fiber or Echo.. for someone who comes from JS world.. and familiar with Express/Koa
@athirsonsilva3808
@athirsonsilva3808 2 ай бұрын
​@@Microphunktv-jb3kjEcho 100%
@Microphunktv-jb3kj
@Microphunktv-jb3kj 2 ай бұрын
@@athirsonsilva3808 just checked Fiber docs.. literally on frontpage saysd its completely inspired by Express lol.. i probably will end up checking them both out.. im one of those people who dont learn anything by justt reading language docs/syntax... i need to press thru mountains of errors to learn languages and frameworks, monkeycoder ; ))) checked echo docs out... the syntax for endpoints is practically identical... whats the difference of fiber and echo then? they all look literally Koa to me.
@patrickkdev
@patrickkdev 2 ай бұрын
@@Microphunktv-jb3kj I come from node js and I am very happy with Fiber. Happier then I was with Echo
@athirsonsilva3808
@athirsonsilva3808 2 ай бұрын
@@Microphunktv-jb3kj Fiber is based on fasthttp and Echo is based on Golang's standard lib net/http, so that's why i recommend Echo, because it's compatible with basically all other Golang libs while Fiber isn't.
@mundanesquirrel8687
@mundanesquirrel8687 2 ай бұрын
my main gripe with the Go router is that it does substring matching. So a request for /foobar will end up in the /foo handler unless you terminated the expression. this is lame.
@baxiry.
@baxiry. 2 ай бұрын
Echo is the first lib return error
@CheezePie
@CheezePie 2 ай бұрын
Right when I needed this video! Thanks a bunch man
@juliknl
@juliknl 2 ай бұрын
Not returning errors combined with package privates has been my beef with Go stdlib since very early days (if you create an interface which is really not nice - at least don't isolate it behind all this privateness bs)
@stack.1
@stack.1 Ай бұрын
That's not the philosophy of handlers, your errors need to be passed to the calling client or a log aggregator etc. Agree on the middle-ware functionality though
@edcodes9167
@edcodes9167 2 ай бұрын
I think your wrong about handlers returning errors. Goes against the language design in regards to error handling. It's my personal opinion that it's better to explicitly handle the errors than have some middleware do it, even if writing the code is a little bit tiresome.
@rmkohlman
@rmkohlman 2 ай бұрын
I truly appreciate your videos Anthony 💪🤜🤛👍
@EricDBrown
@EricDBrown 2 ай бұрын
My question and curiosity goes more along… has anybody run benchmarks against this new ServeMux compared to Chi, etc.? Performance is what I’m interested in.
@varanasi47
@varanasi47 2 ай бұрын
*font size is huge* for my blind homies!! LMAO , luv this...
@BlueIsLeet
@BlueIsLeet 2 ай бұрын
For simple servers it is so easy to use. So for me it's great that they added first class pathvalue (parameter) support
@chasgames
@chasgames 2 ай бұрын
ThePrimeTime just reacted to you! 😎
@aleksandrkravtsov8727
@aleksandrkravtsov8727 3 күн бұрын
if handler return error how http server should handle it then? should it log error or should it panic or should it exit? handler is the last part that you as user can control so you should deal with errors by yourself 🙂
Ай бұрын
i hear you brother. totally agreed... still requires improvements...
@juscilan
@juscilan Ай бұрын
I use gin-gonic lib. I was wondering about migrating from gin to std lib. After this video, perhaps I will change my mind. Great video by the way.
@coffeeintocode
@coffeeintocode 2 ай бұрын
I still think it gets you pretty far, especially when you’re learning Go. I wouldn’t build a serious application in it though, Framework eases the pain of production
@P3PPING
@P3PPING 2 ай бұрын
Im on the no error train, you should always be forced to handle any errors with a response in your handlers and not pass the buck down the line. Coming to a general consensus in the stdlib around what the appropriate default should be for an error would be a nightmare and not something I'd want the stdlib contributors wasting their time on trying to agree on.
@pldcanfly
@pldcanfly 2 ай бұрын
So the only thing they really implemented was url-parsing. I like it in a way that for some projects that might be just enough. I have to feel it to see if I like it for the more complex stuff, Writing a wrapper around that is funnily a pattern I learned from you.
@michelvandermeiren8661
@michelvandermeiren8661 11 күн бұрын
Why is java so fast versus GO ?
@cyrillcheckout
@cyrillcheckout 2 ай бұрын
Ok. If we don't have errors in the handler, we can decorate it and get profit :-) I think it's not big deal
@nexovec
@nexovec 2 ай бұрын
fiber FTW. Gimme those errors.
@derpenstocks
@derpenstocks 2 ай бұрын
I agree on error. Less on grouping since you can still nest in stdlib. I agree it doesn’t fully replace 3rd party, but it does at least make stdlib an option for a larger variety of project sizes. I do wish it was just “better”, but at the same time, I like that they are such sticklers about backwards compatibility. Leave a typescript project idle for 6 months and good luck getting that sucker working.
@Grahamaan27
@Grahamaan27 2 ай бұрын
No mention if the string grouping of path and method? I think its criminal
@MarcosVMSoares
@MarcosVMSoares 16 күн бұрын
Why don't you try liveview 1.0?
@RA-xx4mz
@RA-xx4mz 2 ай бұрын
For sure. The new std lib handlers are ok but it neither innovates on how some existing frameworks already implement handlers. 🤷‍♀️
@thachnnguyen
@thachnnguyen 2 ай бұрын
I'll just keep using gin.
@CrynogarTM
@CrynogarTM 2 ай бұрын
I always return error, that's why I use something like echo.
@maazmunir9213
@maazmunir9213 2 ай бұрын
how does this man deliver every single time
@johnxisde
@johnxisde 2 ай бұрын
i don't agree at all, you can implement a router group and middlewares like others packages (kzbin.info/www/bejne/fmjXk52Be7iaa5o) and about the error, you can make a wrapper for your handleFunc threat that error and return just what the golang needs to satisfy the interface.
@amit_go
@amit_go 2 ай бұрын
But 1.22 brought great improvement to mux
@manee427
@manee427 2 ай бұрын
agree on returning an error. make code cleaner
@PedroPauloAlmeida0
@PedroPauloAlmeida0 Ай бұрын
Have you guys seen how Laravel handle all these routing thing? Just saying...
@anthonygg_
@anthonygg_ Ай бұрын
You are right.
@xpamamadeus
@xpamamadeus 2 ай бұрын
its std lib and its great. chi use it underhood and and its soo simple code to abstract what u want.
@SR-ti6jj
@SR-ti6jj 2 ай бұрын
chi 😎
@MrTheGurra
@MrTheGurra 2 ай бұрын
Just panic and recover :D 🦆🦆🦆
@surilkhedia
@surilkhedia 2 ай бұрын
Api endpoints are different from browser urls and http handler does not need error output but the error is logged and written as http error. Please get your own programming concepts clear before teaching others.
@anthonygg_
@anthonygg_ 2 ай бұрын
You make no sense buddy. Back to Javascript for you little man
@itsothie1196
@itsothie1196 2 ай бұрын
​@@anthonygg_this young man is a little naive about what he says even the best node js framework (to me) called nest actually takes into consideration what he is against and it works best according to most industry experts
@surilkhedia
@surilkhedia 2 ай бұрын
@@anthonygg_ javascript? little man? so you have no idea how handlers work in go. Your audience is most probably javascript beginners not understanding go. I have production go apps running and have more experience than you buddy. keep selling lies to others but don't expect the people who know their stuff to take the L from you.
@surilkhedia
@surilkhedia 2 ай бұрын
@@itsothie1196 buddy we are talking go here not javascript. get your facts straight.
@Grahamaan27
@Grahamaan27 2 ай бұрын
​@@surilkhediaplease, go on!
@paulooliveiracastro
@paulooliveiracastro 14 күн бұрын
What a bad video
@darthvader4899
@darthvader4899 2 ай бұрын
You are mid.
@anthonygg_
@anthonygg_ 2 ай бұрын
I cant deny that.
@AntonVanleeuw
@AntonVanleeuw 2 ай бұрын
I just create my own implementation for http.Handler. Looks like this: type HandlerFunc func(w http.ResponseWriter, r *http.Request) http.Handler func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) { if handler := f(w, r); handler != nil { handler.ServeHTTP(w, r) } } And then you can do stuff like this. func Error(err error) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { // do whatever you want to do } } func Status(code int) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(code) } } http.Handle("POST /something", myHttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) http.Handler { ... if err != nil { return myHttp.Error(err) } return myHttp.Status(http.StatusOK) }))
@AntonVanleeuw
@AntonVanleeuw 2 ай бұрын
Just switched to the 1.22 router. Still use chi's middleware + chi.chain since it's convenient.
The standard library now has all you need for advanced routing in Go.
13:52
Go Pointers: When & How To Use Them Efficiently
14:09
Anthony GG
Рет қаралды 64 М.
ELE QUEBROU A TAÇA DE FUTEBOL
00:45
Matheus Kriwat
Рет қаралды 24 МЛН
КАРМАНЧИК 2 СЕЗОН 6 СЕРИЯ
21:57
Inter Production
Рет қаралды 445 М.
A Beautiful Way To Deal With ERRORS in Golang HTTP Handlers
8:42
ThePrimeagen Hacks My Productivity
3:30
Scott Macchia
Рет қаралды 32 М.
I'm Starting To Like This Configuration Pattern In Go
11:49
Anthony GG
Рет қаралды 18 М.
THIS is the BEST Way to Write HTTP Services in Golang
13:53
Structure Your Golang Service With Layers Like This
7:59
Anthony GG
Рет қаралды 11 М.
Beginners Should Think Differently When Writing Golang
11:35
Anthony GG
Рет қаралды 91 М.
Why We Switched From Svelte Kit To Golang + HTMX
9:54
Anthony GG
Рет қаралды 72 М.
Function Iterators might just change the way we write loops in Go
11:35