The standard library now has all you need for advanced routing in Go.

  Переглядів 79,110

Dreams of Code

Dreams of Code

День тому

Use my link sponsr.is/tld_dreamsofcode and code APPDEVFOO5 and get a .dev, .app, or .foo domain name for only $5!
This video is sponsored by Porkbun.
Since 1.22, the Go standard library now has everything we need to perform advanced routing without the need of a third party dependency. However, knowing how to perform tasks such as middleware, path parameters, subrouting and more can be difficult to know. So, in this video, we look at how to do advanced routing features in Go.
Become a better developer in 4 minutes: bit.ly/45C7a29 👈
Code from project:
github.com/dreamsofcode-io/ne...
Join this channel to get access to perks:
/ @dreamsofcode
Join my Discord: / discord
Follow me on Twitter: / dreamsofcode_io
00:00:00 Intro
00:00:22 Path parameters
00:02:09 Method based routing
00:03:45 Host based routing + sponsor
00:06:07 Middleware
00:08:56 Middleware chaining
00:10:04 Subrouting
00:11:24 Context

КОМЕНТАРІ: 139
@dreamsofcode
@dreamsofcode Місяць тому
Use my link sponsr.is/tld_dreamsofcode and code APPDEVFOO5 and get a .dev, .app, or .foo domain name for only $5!
@nyashachiroro2531
@nyashachiroro2531 Місяць тому
I can't explain just how good the quality of this video is. The Go team should just point to this video for anyone who needs to know about these routing patterns.
@Peshyy
@Peshyy Місяць тому
Go 1.22 is such a blessing. And this video explains everything in such a clear and concise way, it definitely deserves more views and subscribers.
@deado7282
@deado7282 Місяць тому
Thank you! I had the most annoying discussions with people who were like: "net/http has no middlewares we need to adopt a framework and 15 fancy libs bla bla". In the future ill just link this video & tell em to learn the basics (because I still don't feel like dealing with them in a overly constructive way)
@jeffreysmith9837
@jeffreysmith9837 15 днів тому
Using Stdlib in teams still sucks. Conventions are important in teams. No one wants to read 20 different implementations of boilerplate functions
@inithinx
@inithinx Місяць тому
Been learning go as my first proper language after c and java for my university degree. Go's a lot more fun.
@dreamsofcode
@dreamsofcode Місяць тому
Go really is a lot of fun! I think it's simplicity and the power of the standard library help to make it so. You get to spend more time building and less time fighting the compiler or re implementing things.
@inithinx
@inithinx Місяць тому
@@dreamsofcode I'm just glad I'm not doing extremely verbose object oriented stuff like I did in java. Oh and Go basically feels like c on steroids. The decision to not include header files in Go is awesome, coming from c.
@flannn6
@flannn6 Місяць тому
Welcome!
@IllllIIllllI
@IllllIIllllI Місяць тому
8:18 one thing to note is that creating a wrapper for ResponseWriter like this may cause some issues and performance problems, because most ResponseWriter implementations also have methods that are not part of the interface (like http.Flusher, http.Pusher or http.Hijacker, used for WebSocket connections). If you want a battle-tested RW wrapper, you should take a look at the Chi router's WrapWriter middleware.
@h4ckedneko
@h4ckedneko Місяць тому
The API is very similar to chi. It's like chi is now a part of the standard library, which is great. Although, it lacks centralized error handling like what in Fiber has managed to perfect.
@TheQxY
@TheQxY 18 днів тому
I hear this a lot, but I don't think it's such an issue. For small projects, centralised error handling is not really necessary. And for larger projects you can implement a middleware that wraps a handler func that returns an error, logs it, and returns an handler func that does not return an error in less than 10 lines of code.
@h4ckedneko
@h4ckedneko 18 днів тому
@@TheQxY That is what I do in our older projects that uses net/http + chi. I created my own custom handler signature which is close to http.Handler but it returns error. Then the wrapper will catch that error, logs it in Sentry if it's fatal, then creates an HTTP response for that error. Though once we migrated to Fiber, I never got to do all those boilerplates again because the handler signature in Fiber returns an error just like in my custom handler, and you only need to register an error handler function in the router for catching those errors, no more tedious wrapping. I agree that it's not necessary but it's convenient to have.
@orterves
@orterves Місяць тому
As a long time C# Dev just now getting into Go, it seems I picked a very good time to get into Go.
@VictorVelazquezCid
@VictorVelazquezCid Місяць тому
Same here. Typescript developer
@smnomad9276
@smnomad9276 Місяць тому
You'll be very surprised how simple and straightforward the language is for the kind of performance it offers. That is why Go is called a "boring language" lol.
@orterves
@orterves Місяць тому
@@smnomad9276 these days I'm less concerned about performance and more concerned about developer productivity and code maintainability - luckily Go provides both!
@heldim92
@heldim92 День тому
I am about to begin as well, still in doubt between Go and C#... Any insights?
@orterves
@orterves День тому
@heldim92 go wants to be simple - minimal hierarchy and interfaces, tests colocated with code, etc; c# wants to be formal - well-defined hierarchy with dependency injection, distinct test projects and separation of concerns. Both approaches can be productive and valuable; both approaches can be taken too far and cause issues. The right choice for any particular project comes down to business requirements, team knowledge and the deployment target and what features of the SDK and supporting ecosystem you have a need for. All that said, I think C# (especially now with .net 8) is fantastic - and yet my default these days for projects is Go.
@djanthony6662
@djanthony6662 Місяць тому
Coming from PHP & Laravel and just started playing around with Go 2 weeks ago and now I have this sweet video landed on my recommendation. I am so happy, I will stick to making quality Go + std lib videos in the future. Thank you, subbed!
@Aedaeum
@Aedaeum Місяць тому
This was such an incredible wealth of information and it came at just the right time for me haha. Keep up the quality work!! This channel is slowly becoming invaluable to me as I'm learning Go.
@CaffeineForCode
@CaffeineForCode Місяць тому
Simply put, this is a masterpiece. Well done
@dreamsofcode
@dreamsofcode Місяць тому
Thank you! I'm glad you enjoyed it!
@vercolit
@vercolit Місяць тому
Simply POST
@thepisewigeon
@thepisewigeon Місяць тому
@@vercolitsimply GET
@younglion0451
@younglion0451 Місяць тому
Absolutely amazing! You've been inspired me to try go
@MohammadLsk
@MohammadLsk Місяць тому
Thanks for the awesome content. Your videos are short but packed with valuable knowledge, which is more helpful than lengthy courses. Would love to see more Go programming videos from you.
@dreamsofcode
@dreamsofcode Місяць тому
Thank you! I'm glad you enjoyed it! This certainly feels like the year of Go, and so I'll definitely be doing more content 😁
@leffaq
@leffaq Місяць тому
Damn I started learning golang 3 weeks ago and I already love it. Thank you for content!
@keshavakumar9828
@keshavakumar9828 Місяць тому
I really want to learn golang from you. the way you teach and express is so intuitive and natural. Please keep making more such videos
@lutherwaves6929
@lutherwaves6929 Місяць тому
Thanks @dreamsofcode for the video, really well explained! I actually managed to translate my whole go chi project into stdlib upon updating to 1.22 with the help of your video! One thing that caught my eye was during the demonstration of sub-routing, the v1 mux was initialized, but then the http.Server definition below still receives router as the Handler, instead of the v1 router. This did not work for me. I am either misunderstanding how this works, or there might be something unclear/incorrect in the video. Note that I am new to Go net/http. Would appreciate your feedback on this, so we can make it clearer for everyone!
@dreamsofcode
@dreamsofcode Місяць тому
This might be a simple editing mistake! You'll want to pass the v1 router as the handler to the server! Apologies for that!
@lutherwaves6929
@lutherwaves6929 Місяць тому
Thanks for clarifying! Imposter syndrome picked me up as it didn't work for me 😅 Keep up the good work - awesome video!
@RootsterAnon
@RootsterAnon Місяць тому
Awesome video. I used Chi and was very happy with it but now I will try standard net/http.
@enz1222
@enz1222 Місяць тому
Top quality and clear explanations
@melanovapedia7924
@melanovapedia7924 Місяць тому
Top-notch information, thanks DoC
@user-kq1yv8tc7v
@user-kq1yv8tc7v Місяць тому
I think this is a really good video. I started using Gin for my current project that I'm working on. I only did this because it had clear documentation on how to test. Maybe if there were a video on how I could write tests for this stuff, I would definitely choose the standard library for the next project.
@fakegermano
@fakegermano Місяць тому
great video! quick tip: you can use a custom type as a key on context, this way there is no risk (due to type safety) of other packages accessing or overwriting your value
@kurshadqaya1684
@kurshadqaya1684 Місяць тому
Man, this is so cool. Thank you!
@emptystuff1593
@emptystuff1593 Місяць тому
I'm learning Golang and creating some SSR website to apply it, and you literally covered every question I had. I was just done writing logging middleware when I was wondering how to pass information (request id and context to sqlc) downstream...
@JugglingGamer
@JugglingGamer Місяць тому
Porkbun is awesome, it's cool to see them sponsor videos like these!
@adyanf
@adyanf Місяць тому
Love your content, great job!
@souravlayek1662
@souravlayek1662 Місяць тому
Most needed video right now for me ❤
@giovanni.tirloni
@giovanni.tirloni Місяць тому
I appreciate the new visuals, they are pretty.cool, buy the stream of short phrases with filling space cut out feels like a Fireship video and I had trouble following it.
@aghileslounis
@aghileslounis Місяць тому
The biggest reason I still use Echo, is for the middlewares they have available, especially for security, i don't need to write them or search for third party middlewares one by one I'm new to Golang, maybe there is a good pkg that handles all the security things i need, especially when using HTMX, security is very important since it's server side sending html
@iwolfman37
@iwolfman37 Місяць тому
I simply use a switch statement to call the correct handler and use structures and their methods to pass middleware functionality. Like a structure with fields for a database connection and a custom logger. Then your handler method can just make calls to the structure's fields' methods.
@Fudmottin
@Fudmottin Місяць тому
Pretty cool stuff. I definitely need to upgrade my typing skills!
@matthiashermsen9464
@matthiashermsen9464 Місяць тому
Thanks for your awesome content! Would you mind making a video about your distro setup ( I guess you are using Arch with some theming )
@attilao
@attilao Місяць тому
It seems a bit odd to download a private key… I'd rather generate one locally and request it to be signed. But then again, the goal here is simplicity I guess.
@FloWoelki
@FloWoelki Місяць тому
i really do love the standard library of go
@MattRobinsonDev
@MattRobinsonDev Місяць тому
Excellent vid always!
@metaltyphoon
@metaltyphoon Місяць тому
All I need now is for Go to add a way to know what StatusCode has been written by a middleware without having to wrap the ResponseWriter
@mycode0
@mycode0 Місяць тому
This is beautiful
@kaspariito
@kaspariito Місяць тому
thanks, man!
@malikfajar4841
@malikfajar4841 9 днів тому
Nice video sir. I'm just learning golang, and this video is useful.
@duongphuhiep
@duongphuhiep Місяць тому
as the std library extends, other frameworks / library will slowly die.. though I think it's natural.. Great content. it makes me want to have another try with go
@Strawberry_Htet
@Strawberry_Htet Місяць тому
OMG, I learned a lot from this.
@abdoolkareem_
@abdoolkareem_ Місяць тому
This video was 🔥🔥. Subscribing
@roganl
@roganl Місяць тому
Excellent Video. Lots of hand holding. I like it. However in spite of two cups of coffee in my system it felt "rushed" from a cadence perspective..
@dreamsofcode
@dreamsofcode Місяць тому
Thank you for the feedback! It's tough to balance between keeping it engaging and concise whilst also ensuring it's understandable. I'll aim to do better in future;
@paw565
@paw565 Місяць тому
I would love to see a comparison with some framework. It's interesting if they are still really relevant.
@PhanorColl
@PhanorColl Місяць тому
yes please, do a video on Certbot
@Dozer456123
@Dozer456123 Місяць тому
1:55 I think you could argue that because the wildcard is farther down the path specification, that path 1 is more specific than path 2.
@pettymanny6487
@pettymanny6487 Місяць тому
Useful, TX
@awesomedavid2012
@awesomedavid2012 25 днів тому
I'm having a problem with the subrouting 10:45 The problem is that you cannot POST to "/" under the subrouter when you strip the prefix. The other routes work because there is no trailing slash, but suppose you want to POST to /v1 itself, there is no way to set up that route as far as I know. You can only set up /v1/ which is different, so http issues a redirect.
@p.wagner3995
@p.wagner3995 Місяць тому
I dont want a CertBot vid, I want a LEGO (Letsencrypt-go) vid!
@dejanduh2645
@dejanduh2645 Місяць тому
Should a new router be run in the main gorutine or should it be run in a separate gorutine for max performance?
@dicmaster2697
@dicmaster2697 Місяць тому
very good video
@thang1144
@thang1144 Місяць тому
at 10:00, what can we do if there are multiple stacks?
@iuliancarnaru954
@iuliancarnaru954 Місяць тому
Can you please make a video with certbot and http2 (can I also ask how to make my nvim chad theme to have more keywords highlighted)
@phenvrc
@phenvrc 27 днів тому
Hey, which mic are you using? I loved the sound quality
@dreamsofcode
@dreamsofcode 27 днів тому
Thank you! I use the Sennheiser MKH 50. It's a really great mic but not cheap.
@joaovictorcesa9443
@joaovictorcesa9443 Місяць тому
Your videos are really good, I put you up there with Fireship. Keep it up.
@dreamsofcode
@dreamsofcode Місяць тому
I'm honored. The man is a legend.
@srki22
@srki22 Місяць тому
@@dreamsofcode I found your channel because of Fireship channel. It's seems that people who follow Fireship also follow you so youtube suggested that to me as well. Nice channel.
@tonycheng1614
@tonycheng1614 11 днів тому
Given the updates of net package, is the framework like gin still necessary for some good reason?
@dreamsofcode
@dreamsofcode 11 днів тому
Gin does provide a lot of helper functionality to do things with less lines of code, but for me it breaks the contract with the standard library, so I prefer net/http.
@PanicAtProduction
@PanicAtProduction Місяць тому
Basically, you wrote your own framework. Behind the scenes, 3rd party libraries do the same thing that you said maybe more efficient in terms of complexity. I check real world benchmarks, crud operations, caching, https routing etc before I start a project. I didn't care this before, but when we receive the invoice from AWS, we can easily see it matters and worth it. You can handle thousand of operations in a small vps with go. It is impossible to handle same operations with JS(express or koi) under the same conditions.
@jazzdestructor
@jazzdestructor Місяць тому
Hey Dreams of Code and other fellas, i am confident with express node and am thinking of learning a new backend lang but am pretty torn atm between golang and rust , could you suggest me or guide me here? it would really help me. Thanks and cheers 🍻🍻
@dreamsofcode
@dreamsofcode Місяць тому
I think it depends what you're looking for. Go is probably one of the best technologies to learn if you're interested in primarily building web applications, server side, infra and MPAs On the other hand, if you want more systems level programming, Rust will take you further. But Rust is much more challenging to learn and use than Go.
@blackaccel
@blackaccel 16 днів тому
Dream how to I get to use my terminal with those numbers 1.Nvim, 2.Proyect, I’m using I term on Mac and using nvim as my editor also
@rahulagarwal968
@rahulagarwal968 Місяць тому
Hi. If I have to implement a monthly or yearly subscription model for my mobile application. Then is it mandatory to use In-App-Purchases ? I mean we cannot use an external payment gateway. How Netflix is redirecting users to its website to avoid 30% fees. Please talk about this.
@jeremybuckets
@jeremybuckets Місяць тому
11:22 it runs the middleware but it still creates the invoice. Is this just because you didn't actually implement auth for the demo, or what's going on there?
@bijayaprasadkuikel5162
@bijayaprasadkuikel5162 Місяць тому
Please make a video on certbot. I really want to see a full Microservices code in go from scratch to production. Please make it happen.
@dreamsofcode
@dreamsofcode Місяць тому
I am working on a course looking exactly at this!
@bijayaprasadkuikel5162
@bijayaprasadkuikel5162 Місяць тому
@@dreamsofcode i would be really really happy. Your contents are out of the world.
@lilzin69
@lilzin69 Місяць тому
8:58 would be a nice PR
@anthonycavagne4880
@anthonycavagne4880 Місяць тому
Hi ! Just one question here, why loop in inverse order in the create stack function ?
@dreamsofcode
@dreamsofcode Місяць тому
Great question! This is so that the first element in the array acts as the top of the stack. The middleware isn't necessarily calling the next handler, more like wrapping each middleware inside. i.e. [a,b,c] needs to be a(b(c)) so it's easier to wrap it with a reverse iterator
@Jake-bh1hm
@Jake-bh1hm 21 день тому
Question: Is there a framework for GO that is like svelt? Or svelte like?
@dreamsofcode
@dreamsofcode 21 день тому
The closest thing would be Templ, but it's still rendered on the server rather than rendered on the client.
@AlexandruVladutu
@AlexandruVladutu Місяць тому
The trick with wrapping the ReponseWriter to get the statusCode fails with stackoverflow if using the "/v1" Handle func that strips the prefix. Try that scenario with /v1/ and without in the path and you'll see the app crashing.
@dreamsofcode
@dreamsofcode Місяць тому
Hmm, I just tested this and couldn't get it to crash. http.StripPrefix only affects the request, not the response. If you're on discord (or anywhere else), mind sharing your code with me so I can take a look?
@rogerramjet8395
@rogerramjet8395 Місяць тому
So weird hearing an Englishman pronounce "router" like the tool, or an American. (And "status", although many do, tbf.) Great videos though! And, about time, eh?! 👍👏
@dreamsofcode
@dreamsofcode Місяць тому
Haha, believe it or not I'm actually British/American. I get the worst parts of both languages.
@crix_h3eadshotgg992
@crix_h3eadshotgg992 Місяць тому
@@dreamsofcode relatable
@rogerramjet8395
@rogerramjet8395 Місяць тому
lol @@dreamsofcode! You'd never know. You have a perfect "home-counties" accent. You could present the news for the BBC! Well, except for the American "router" pronunciation! They wouldn't have that! 😉😂
@joelhowell5402
@joelhowell5402 Місяць тому
I would pay for classes from this guy
@guitaripod
@guitaripod Місяць тому
You can super thanks the video, unless you're all talk of course
@olegcharnyshevich1127
@olegcharnyshevich1127 Місяць тому
What about error handling?
@saramshshrestha7641
@saramshshrestha7641 Місяць тому
🎉🎉❤
@rudde7251
@rudde7251 Місяць тому
Does the other libraries like, echo, go, chi, mux use net/http, or are they all a complete reimplementation of http in go?
@dreamsofcode
@dreamsofcode Місяць тому
Some use a lot of the net/http package underneath. I believe chi has it's own router implementation internally.
@anmol-fzr
@anmol-fzr Місяць тому
Need a video on http client like postman within the neovim
@ClariNerd
@ClariNerd Місяць тому
Ball’s in Deno’s court now.
@danielgospodinow
@danielgospodinow Місяць тому
11:13 - Can't/shouldn't we add this auth middleware not to `router` but to `adminRouter` instead? Since that way, we're adding admin-specific logic into the main router which doesn't seem ideal to me. And btw, fascinating content!
@dreamsofcode
@dreamsofcode Місяць тому
It looks a little confusing, but basically we are doing that by wrapping the admin router only. It could have probably been explained a little easier if I added a /admin to that path!
@tbranch227
@tbranch227 Місяць тому
hey look, go is finally maturing to the level of all the web stacks that came before it....
@joelhowell5402
@joelhowell5402 Місяць тому
Bro tell me how I opened PorkBun before his ad played.
@phoneywheeze9959
@phoneywheeze9959 Місяць тому
Someone should make a standard template out of this that works like Laravel works with php
@danko95bgd
@danko95bgd Місяць тому
Annoying thing is that you have to manually parse data from query params, form, path etc to be type safe unlike for example echo bind where you can just bind to struct.
@rohit_ambre
@rohit_ambre Місяць тому
certbot video for sure
@dracula5752
@dracula5752 Місяць тому
had hard time finding how to override 404 page
@Nonsense116
@Nonsense116 Місяць тому
brb upgrading my side project to go 1.22 and migrating away from gin.
@samueladole6074
@samueladole6074 Місяць тому
Middleware chaining 🎉
@fkondratov
@fkondratov Місяць тому
didnt quite get - first we write statusOk , but then we read different statusCodes in wrapped
@dreamsofcode
@dreamsofcode Місяць тому
Correct, the next handler in the chain will either modify the status code if there was a different one to 200.
@jaymason7097
@jaymason7097 28 днів тому
Accept for handlers that return an error
@dreamsofcode
@dreamsofcode 28 днів тому
I'm actually not a fan of handlers that return an error, personally! I know some people are though!
@erikslorenz
@erikslorenz Місяць тому
I don’t think most of the established routers and such provide enough now to use over the std library for the most part. I really like Huma for APIs since it’s giving you OpenAI for free which I think is worth it for sure.
@avishjha4030
@avishjha4030 Місяць тому
What's Huma?
@gokhanuysal_dev
@gokhanuysal_dev Місяць тому
Amazing nothing to say
@revoktorment440
@revoktorment440 3 дні тому
Dreams of code makes really good videos but as a frontend dev learning go, I gotta watch his vids on 0.75 speed...
@dreamsofcode
@dreamsofcode 3 дні тому
:sob: I apologize. I have a much slower paced video coming out tomorrow.
@seannewell397
@seannewell397 Місяць тому
im shook go std lib doesn't expose statusCode without a wrapper like that for middleware. wut.
@babakfp
@babakfp 9 днів тому
Why the methods are written as a string? Welcome to no auto-completion and typos and the whitespace thing! LOL
@andreasorlow3420
@andreasorlow3420 Місяць тому
can I use porkbun if I'm muslim?
@gustavojoaquin_arch
@gustavojoaquin_arch 10 днів тому
Idk, why are you Muslim?
@Jzhongzhi
@Jzhongzhi Місяць тому
second nice
@natescode
@natescode Місяць тому
Go is catching up to C# from a decade ago 😂
@danko95bgd
@danko95bgd Місяць тому
No, they still need to add 500 keywords to the language
@Dozer456123
@Dozer456123 Місяць тому
The string definition of the required method is so garbage. It requires a single space after a string defined value? Wtf is this? 1995?
@theinhumaneme
@theinhumaneme Місяць тому
first
@theinhumaneme
@theinhumaneme Місяць тому
first
Function Iterators might just change the way we write loops in Go
11:35
Dreams of Code
Переглядів 43 тис.
When RESTful architecture isn't enough...
21:02
Dreams of Code
Переглядів 237 тис.
skibidi toilet 73 (part 2)
04:15
DaFuq!?Boom!
Переглядів 31 млн
Teenagers Show Kindness by Repairing Grandmother's Old Fence #shorts
00:37
Fabiosa Best Lifehacks
Переглядів 33 млн
THIS is the BEST Way to Write HTTP Services in Golang
13:53
Melkey
Переглядів 16 тис.
What makes Binary Search is so important?
7:00
Dreams of Code
Переглядів 16 тис.
Философия Unsafe Rust
22:35
Bitωise
Переглядів 4,5 тис.
How To Use The Context Package In Golang?
17:03
Anthony GG
Переглядів 49 тис.
Should you learn Elixir in 2024?
6:34
Dreams of Code
Переглядів 69 тис.
You Are WRONG About 0 Based Indexing
25:02
ThePrimeTime
Переглядів 144 тис.
Beginners Should Think Differently When Writing Golang
11:35
Anthony GG
Переглядів 87 тис.
NEW GPT-4o: My Mind is Blown.
6:28
Joshua Chang
Переглядів 6 тис.
Why I Quit Copilot | Prime Reacts
35:56
ThePrimeTime
Переглядів 242 тис.
Master Go Programming With These Concurrency Patterns (in 40 minutes)
46:15
ПОЛГОДА строгого режима для Lenovo Legion 5 pro. Чем может обернуться обычный ремонт ноутбука?
31:47
ААНТ КОНТАКТ Сервис по ремонту техники в ЕКБ, СПБ
Переглядів 33 тис.
Купите ЭТОТ БЮДЖЕТНИК вместо флагманов от Samsung, Xiaomi и Apple!
13:03
Thebox - о технике и гаджетах
Переглядів 33 тис.
📱 SAMSUNG, ЧТО С ЛИЦОМ? 🤡
0:46
Яблочный Маньяк
Переглядів 629 тис.
Samsung UE40D5520RU перезагружается, замена nand памяти
0:46
Слава 100пудово!
Переглядів 3,8 млн