How To Use The Context Package In Golang?

  Рет қаралды 66,488

Anthony GG

Anthony GG

Күн бұрын

Пікірлер: 135
@anthonygg_
@anthonygg_ 2 жыл бұрын
► Join my Discord community for free education 👉 discord.com/invite/bDy8t4b3Rz ► Become a Patreon for exclusive tutorials👉 www.patreon.com/anthonygg_ Thanks for watching
@jondoe79
@jondoe79 Жыл бұрын
Context is like a bag or container that holds information that is shared between different parts of the program, especially when it comes to handling a request. This information can include things like timeouts, cancellation signals, and other data that is specific to that request. For example, imagine you are building a web server that handles a lot of incoming requests. Each request has its own specific needs and requirements, such as a deadline for how long it should take to complete. The context allows you to keep track of these individual requirements for each request, and make sure that they are handled properly.
@anthonygg_
@anthonygg_ Жыл бұрын
This is the best readable explanation I ever read. 🤝
@ThangTran-hi3es
@ThangTran-hi3es 10 ай бұрын
😊😊
@midrazh
@midrazh 2 ай бұрын
For real, I've been working with go for a while and only now I can say that I have finally understood what the god damn context is. Thank you.
@k0n3j0
@k0n3j0 Жыл бұрын
I've been putting off learning context because of its strange nature. You've cleared it up in 17 minutes, thank you.
@vitiok78
@vitiok78 Жыл бұрын
I like how you're providing almost real life examples with such a passion! Your videos helped me A LOT!
@anthonygg_
@anthonygg_ Жыл бұрын
Feels good to hear that! Much appreciate this comment
@lsd_btw
@lsd_btw 3 күн бұрын
Hello from Habr Viktor )
@vitiok78
@vitiok78 3 күн бұрын
@@lsd_btw Hi there!
@PavelBogart-cm2fz
@PavelBogart-cm2fz 11 ай бұрын
I have just started learning Go, there are lots of vids with basics but this sort of content gives you a good taste of what you actually should learn to become a good golang dev. Thanks a lot for your hard work!
@anthonygg_
@anthonygg_ 11 ай бұрын
Ty
@metoh757
@metoh757 Жыл бұрын
You don't actually need the for loop for the select. Since you don't have a default case, the select with just block until a response is received or the context is canceled.
@rdforte
@rdforte Жыл бұрын
I also wandered the same thing.
@chunkspiggle3916
@chunkspiggle3916 2 жыл бұрын
Keep the content coming man, following along the JSON API series to write my own project has helped me learn Go so fast its unreal
@anshkumargarhewal8582
@anshkumargarhewal8582 2 жыл бұрын
Thanks Anthony your videos from last few days are helping a lot man. 🍻
@koteshahoskote3480
@koteshahoskote3480 Жыл бұрын
Simplest and Effective Tutorial for Golang Context package! Thank you so much!!
@joevtap
@joevtap Жыл бұрын
you are simply the best teacher i could ever have
@Programming-lr1nb
@Programming-lr1nb Жыл бұрын
Surely the best explanation of contexts I've ever seen, thx
@parvizyuldashev4668
@parvizyuldashev4668 Жыл бұрын
the best context tutorial I've ever seen!
@anthonygg_
@anthonygg_ Жыл бұрын
Thank you
@Marlem80
@Marlem80 Жыл бұрын
Your channel is pure Gold! Thanks for sharing your knowledge with the world!
@nonlinearsound-001
@nonlinearsound-001 Жыл бұрын
The function fetchData alone is a perfect description of why Go is such a beautiful language and how much effort it actually takes away from you. Image, you would have to code all of these implicit functionalities (including something complex like coroutines, thread communication and sync) by yourself or take them from some repo and try to incorporate it into your project, in C++ for instance. Here, you get all of that, wrapped up in a nice syntax that it easy to understand and follow. :)
@delduked
@delduked Жыл бұрын
Dude, that last application of a request ID in a context is the exact project I’m working on for work but in typescript. I wish we were making our APIs in GO but sadly not. I’ve been using a Axios wrapper inside a library I made and then in the request middleware I add the axios wrapper to an inversify config for dependencies injection. That way when ever a developer uses the axios wrapper in our code, all the classes have my axios wrapper with the request id as a public read only property. GO would be so much better
@aevitas_
@aevitas_ 6 ай бұрын
Great video, thanks so much! As for your remark about what language can do this so cleanly, I think C#'s CancellationToken implementation is as clean, or perhaps even cleaner as it can be passed to any task, and the cancellation token expiring can be handled by catching the exception thrown, which realistically is the only code you'd need to implement to get the equivalent of this code in Go.
@phill13able
@phill13able 2 ай бұрын
Best golang channel. 🎉
@phill13able
@phill13able 2 ай бұрын
I've been looking for where to really learn golang and I found it. You're amazing man
@ashleyspianoprogress1341
@ashleyspianoprogress1341 7 ай бұрын
Literally the best explanation
@bambi4199
@bambi4199 Жыл бұрын
amazing video. I would love to see more about tracing, loging and grafana
@andreichicu2799
@andreichicu2799 7 ай бұрын
New to go. I didn't know about context and ended up making a struct to implement a shared state...
@tpotjj2979
@tpotjj2979 2 жыл бұрын
Keep the videos coming!👏👏
@mhcbon4606
@mhcbon4606 Жыл бұрын
next time you can consider using fmt.Errorf("some msg: %w", ctx.Err()) So the caller can rely on the embedded standard error to figure out it was a context related error on top of having a useful error message. Although, you could do all this stuff w/t the context package (func call with a cancel signaling), especially since generics has landed. this was not the in depth discussion i was looking for, but not your fault.
@amir.moqaddam
@amir.moqaddam 9 ай бұрын
very nice tutorial for who want starts golang. beautiful...
@ryanleemartin7758
@ryanleemartin7758 Жыл бұрын
I've been using Rust on my back end for web api / static file serving and it's great. I'm confident that after it compiles its going to run like a champ.... however, looking at how amazingly simple go code is and how beautiful concurrency is implemented I can't help thinking that I would be better off banging out web shit with Go. Rust, incredible power but as a solo dev the complexity weighs me down a bit. I feel like, from watching some of your vids I could be shipping code at light speed compared to what I'm able to do with Rust.
@mathiaslueer
@mathiaslueer Жыл бұрын
It always depends what you need. But as a solo dev Go is most likely a very good option because it's designed for fast development. I think in most cases Go is the better option. But if you for instance need really high performance web assembly like for a service like Figma then better go with Rust.
@lufalm
@lufalm 7 ай бұрын
You're a fantastic teacher, Anthony! Thanks for sharing your knowledge aways most smoothly and animatedly possible - I've learned heaps watching your videos
@Nalopotato
@Nalopotato 8 ай бұрын
Anyone reading this: This is *exactly* what we do in my company. So if you are looking for stuff to learn to get hired, this is one of those things!
@sachinmaurya3259
@sachinmaurya3259 Жыл бұрын
Great Video. Loving your content.
@sovrinfo
@sovrinfo 2 жыл бұрын
Great video. Thanks Anthony!
@savage3dgames510
@savage3dgames510 5 ай бұрын
Perfect explanation. Thanks
@sternparadis227
@sternparadis227 9 ай бұрын
Please note that the go-routine will not be cancelled, but will run until it's ended naturally (or the program exits). This is default Go behavior and as far as I know there's no way to cancel it from outside the go-routine.
@sargon7562
@sargon7562 Жыл бұрын
Thank you for your help! U r making a great job!
@shantanubadmanji7650
@shantanubadmanji7650 16 күн бұрын
Great stuff bro!! I'm starting to learn to Go. I'm coming from JAVA, CPP, JS, Py, etc and bro can this be any more simple !!
@hackebeil20
@hackebeil20 Жыл бұрын
Came for contexts, stayed for the Swiss accent :)
@myrachoantonio8832
@myrachoantonio8832 Жыл бұрын
cool video on context
@hafismuhammad7028
@hafismuhammad7028 Жыл бұрын
Great video sir❤❤❤
@dleonardo8755
@dleonardo8755 Жыл бұрын
wait go is really clean af wtf
@mathiaslueer
@mathiaslueer Жыл бұрын
Hi. First I wanna say I really love your channel. Seems you really have a deep knowledge of Go. I have one question. What is the reason you give a context.Background to fetchUserData and wrap it then inside the function with the context.WithTimeout? What were your thoughts behind this design decision ? why didn't you give the timeout context directly to the fetchUserData?
Жыл бұрын
Beautiful video, thanks!
@ftb2024_official
@ftb2024_official 6 ай бұрын
WOW. Cool 🔥. Really cool 🔥. Appreciate it 🤝
@donovanvanderlinde3478
@donovanvanderlinde3478 Жыл бұрын
Thank you for the good content
@KingCrylo
@KingCrylo Жыл бұрын
great vid!
@vacekto
@vacekto 9 ай бұрын
you are awesome, thanks for these videos
@Ladyhoat
@Ladyhoat 2 жыл бұрын
Very useful! Thanks! :)
@cypherop2608
@cypherop2608 8 ай бұрын
loving it
@TheedonCritic
@TheedonCritic 6 ай бұрын
Very educative! How do you move around so fast, do you use vim bindings?
@anthonygg_
@anthonygg_ 6 ай бұрын
Yes. Vim bindings
@valakutgame
@valakutgame Жыл бұрын
Hey Anthony, great video, but wouldn’t the fetchThirdPartyStuff function keep running in the background after fetchUserData times out and returns? I have had this happen in a very similar situation, but I used time.after instead of contexts. Would this still happen with context timeouts if the whole program ran for longer?
@amirhasanbasic2193
@amirhasanbasic2193 Жыл бұрын
you are right, i was wondering how there is no other comments that bring this up, the way it is done here the actual third party devil can stay alive indefinitely
@dan_le_brown
@dan_le_brown 11 ай бұрын
Damn, that's scary 🤯
@mehdisalimi43
@mehdisalimi43 Жыл бұрын
thank u Great Man
@chethan_r3152
@chethan_r3152 10 ай бұрын
thank you, great content. you talk like T Bag from prison break 😄
@rohit-ld6fc
@rohit-ld6fc Жыл бұрын
context code is explained well, but the infinite for loop is not placed well. it should be in a seperate goroutine as well
@anthonygg_
@anthonygg_ Жыл бұрын
True true my bad
@buntysingh7315
@buntysingh7315 2 жыл бұрын
thankyou this was informational
@anthonygg_
@anthonygg_ 2 жыл бұрын
Glad it was helpful!
@oscarllamas
@oscarllamas 2 жыл бұрын
Great video! Cheers from Guatemala
@anthonygg_
@anthonygg_ 2 жыл бұрын
Hey, thanks!
@baxiry.
@baxiry. Жыл бұрын
you are awesome
@anthonygg_
@anthonygg_ Жыл бұрын
😍
@pukito9123
@pukito9123 Жыл бұрын
amazing
@basantsaini4333
@basantsaini4333 6 ай бұрын
why infinite for loop was required ? select statement alone was sufficient. Select waits for one of the case channel operation to complete.
@anthonygg_
@anthonygg_ 6 ай бұрын
My mistake
@matheusdutrademoura
@matheusdutrademoura Жыл бұрын
Do you really need the select inside a for? In this case, isn't it going to work the same way if you remove the for?
@anthonygg_
@anthonygg_ Жыл бұрын
No, was my mistake
@MesheeKnight
@MesheeKnight 2 жыл бұрын
what the for loop is for?
@anthonygg_
@anthonygg_ 2 жыл бұрын
Can be deleted, my bad.
@Suraj-tz3oq
@Suraj-tz3oq 9 ай бұрын
Why for-select instead of only select?
@airkami
@airkami 6 ай бұрын
For-select continuously monitors the channels
@tylergabb2632
@tylergabb2632 5 ай бұрын
Yeah, otherwise it will fall through and the func will return if none of the channel operations are successful
@shammianand6980
@shammianand6980 5 ай бұрын
It is done to make the function synchronise with the timeout of 150 ms; the empty for is a while true loop(which will block the function for any of the 2 cases to happen); and since we are guaranteed to receive from ctx.Done channel after some time T; it will synchronise the go routine; give it time to run
@RomanSteiner_xD
@RomanSteiner_xD 2 ай бұрын
I'm still learning Go so I can't be sure. But a select without a default case is already blocking: it won't "fall through". Actually, putting a loop around it only happens to work because he returns (exits the loop) in all cases, otherwise he'd deterministically run both cases (one after 150ms, one after 200ms) and then he'd wait eternally for a third message to any of the channels that is never sent. Correct me if I'm wrong, but to me it looks like he's putting a loop around it because he's "used to" putting loops around channel stuff.
@bopon4090
@bopon4090 5 ай бұрын
@anthonygg_ why did we use infinite for loop to handle the select statement? That for loop will run only once and wait till the select statements are resolved and since select statement is terminating the function that infinite for loop seems unnecessary.
@anthonygg_
@anthonygg_ 5 ай бұрын
Ye my bad
@rajan-u6b
@rajan-u6b Жыл бұрын
omg you are ao cool🤩
@StephenDryden
@StephenDryden 8 ай бұрын
Apologies if I've missed this in this video or another video of yours but I'm struggling to work out how to test something similar to this. I have a AWS Lambda function written in go that has basic GET/PUT/POST/DELETE handlers that use context. The function just read/writes to DynamoDB. My function works but I'm struggling to work out how to unit test my handlers. I likely just need to rewatch this and do more digging but if you have anything or anyone can link to some examples that might help then I'd really appreciate it.
@mohamadbt4055
@mohamadbt4055 Жыл бұрын
very good
@irfanfauzi8704
@irfanfauzi8704 Жыл бұрын
nice vids
@mystifyingdude
@mystifyingdude 5 ай бұрын
Great video….
@Augustine_354
@Augustine_354 8 ай бұрын
I dont get why you wrapped select statement in for, since you return from each select branch?
@TimurSevimli
@TimurSevimli 4 ай бұрын
Hi Anthony! When we cancel a request with context to avoid a long wait for a response from a third-party server, does the mechanism also cancel the HTTP request operation at a low level (in a system call) ?
@90hijacked
@90hijacked Жыл бұрын
(16:00) How does one actually implement request tracing in grafana? Thinking about it, Would love a clip about integrating projects grafana / prometheus, pprof / opentelemetry etcetera :)
@baxiry.
@baxiry. 2 жыл бұрын
🤩
@naddar
@naddar 8 ай бұрын
nice
@Alibek11221
@Alibek11221 Жыл бұрын
I’m a chess player, hey, that’s not true😂😂😂
@lunchbreak7319
@lunchbreak7319 2 жыл бұрын
Hey, thanks for videos! Can you please share your VS Code theme?
@anthonygg_
@anthonygg_ 2 жыл бұрын
Gruvbox is the theme Im using
@ruslangabitov5202
@ruslangabitov5202 Жыл бұрын
I think the for around select is extranous. You could have the same results without it
@anthonygg_
@anthonygg_ Жыл бұрын
Jup. Little happy accident
@nurhusni
@nurhusni 2 жыл бұрын
The one thing I'm confused with is why does `context.WithTimeout()` & `context.WithValue()` need the `ctx` as parameter? What is it exactly? Why does that parameter matter? And, why does `ctx` need to be initiated from the main function (instead of on the `fetchUserData` right away? I mean before you started using `context.WithValue`.
@anthonygg_
@anthonygg_ 2 жыл бұрын
the `ctx` parameter is needed when creating new contexts because it will use that context as the "parent" context. The exact same reason why we need to pass in the `ctx` in fetchUserData. Because it could be that someone already has a context created with some values attached to it, so we can read that deeper in the stack without worrying about sharing a state that is unprotected by mutex guards. Values passed in the context are always safe to read from in other functions using that context as the parent. I hope this clears up your question.
@Tea-Spin
@Tea-Spin Жыл бұрын
ctx designed to be immutable, that’s why when adding new value/attribute(timeout, etc), you’re essentially creating new context based on last context plus whatever new attribute you’re adding
@garrywreck4291
@garrywreck4291 Жыл бұрын
Can somebody explain what will happen with the goroutine? Will not it hang infinitely waiting for the response? How it will be killed?
@what1heh3ck
@what1heh3ck 7 ай бұрын
think of it like 2 goroutine run simultaneously (one is context with timeout, one is request fetching). They both have channel to receive signal (or data). Now we put 2 of them inside a select statement to basically check which one send the signal first. In case the context send first, that means the request is timeout
@David-xy4nw
@David-xy4nw Жыл бұрын
I am struggling to understand the difference between context.WithDeadline and context.WithTimeout. they essentially do the same thing right ?
@anthonygg_
@anthonygg_ Жыл бұрын
Yes, dont worry about it.
@ThangTran-hi3es
@ThangTran-hi3es 10 ай бұрын
Hey Athony, could you please share how you use vim in your normal stuff? I really love your speed with vim. I've used vim for about 2 months but my speed really bad. I want high speed vimmer like you 😂
@what1heh3ck
@what1heh3ck 7 ай бұрын
you could go watch some primagen’s videos about vim
@ThangTran-hi3es
@ThangTran-hi3es 7 ай бұрын
@@what1heh3ck thanks
@matthewbridges3147
@matthewbridges3147 7 ай бұрын
I'm not sure why the select statement needed to be ran in a for loop
@anthonygg_
@anthonygg_ 7 ай бұрын
Not needed . My mistake
@emzx111
@emzx111 Жыл бұрын
Do you still need to use context pkg if you deploy this inside a service mesh like istio, which can handle timeouts in its envoy sidecars?
@XRoydX
@XRoydX 3 ай бұрын
So in typescript world this would be a promise.race with the fetchTerribleSlowFunction and setTimeout promise ?
@dranon0o
@dranon0o Жыл бұрын
> which language can those that, that clean? > * silence * > NONE exactly loved that part
@wuilliam321
@wuilliam321 Жыл бұрын
Is it possiblo to trigger a "cancel" on demand? I mean, what if you want to "cancel" a request not because the timeout, but because another arbitrary reason?
@anthonygg_
@anthonygg_ Жыл бұрын
You can just call the Cancel thats returned from creating a new context. Cancel()
@wuilliam321
@wuilliam321 Жыл бұрын
@@anthonygg_ :mmmm: I'm gonna try that
@Levelord92
@Levelord92 Жыл бұрын
Can somebody explain why do we need an infinite loop with select? Why not just select?
@anthonygg_
@anthonygg_ Жыл бұрын
A little happy accident of me
@MrCleverOnion
@MrCleverOnion Ай бұрын
Is this color scheme available in nvim?
@AnNguyen-uv9yc
@AnNguyen-uv9yc Жыл бұрын
what theme?
@arjunbakshi4657
@arjunbakshi4657 11 ай бұрын
Where can I get the code?
@РоманДвачевский-ц7к
@РоманДвачевский-ц7к Жыл бұрын
I like how the go makes it so cluttered to implement a piece of code which does exactly what a CancellationToken would do in c# in ~6 loc
@LukeEdwards05
@LukeEdwards05 11 ай бұрын
Great video but your keyboard / navigating stresses me out.
@botyironcastle
@botyironcastle 3 ай бұрын
cancellation token in c# is much more reasonable
@BlueIsLeet
@BlueIsLeet 6 ай бұрын
it's just a map it's really easy
@mishalray2309
@mishalray2309 7 ай бұрын
boring lecture
@anthonygg_
@anthonygg_ 7 ай бұрын
Timmy
@omarduadu4145
@omarduadu4145 Жыл бұрын
Excellent Video, thanks @anthonygg_ really appreciate your content. I am new to Microservices and how they can be connected in Golang. Can I ask if you have any video in which you join Microservice together in one app. Something like a part 2 for "How to build and structure a go microservice"
@ManhPham-fh6on
@ManhPham-fh6on 7 ай бұрын
Appreciate your content! Thanks so much!
How To Compose Typed Functions In Golang?!
10:05
Anthony GG
Рет қаралды 13 М.
How To Use Goroutines For Aggregating Data In Golang?!
17:15
Anthony GG
Рет қаралды 42 М.
МЕНЯ УКУСИЛ ПАУК #shorts
00:23
Паша Осадчий
Рет қаралды 5 МЛН
快乐总是短暂的!😂 #搞笑夫妻 #爱美食爱生活 #搞笑达人
00:14
朱大帅and依美姐
Рет қаралды 12 МЛН
How to deal with M1 processor that won't turn on?
4:47
SoFix Tool
Рет қаралды 5
This is the BEST Golang Context Package Tutorial
12:18
Melkey
Рет қаралды 14 М.
Go Pointers: When & How To Use Them Efficiently
14:09
Anthony GG
Рет қаралды 86 М.
Go Iterators Are Bad
36:12
ThePrimeTime
Рет қаралды 105 М.
How To Build And Structure A Microservice In Golang?!
23:03
Anthony GG
Рет қаралды 54 М.
Understanding Contexts in Go in 5(-ish?) Minutes
15:14
TutorialEdge
Рет қаралды 65 М.
A Practical Example How To Use Interfaces In Golang
14:42
Anthony GG
Рет қаралды 28 М.
МЕНЯ УКУСИЛ ПАУК #shorts
00:23
Паша Осадчий
Рет қаралды 5 МЛН