Learning Golang: Context package: Cancellations, Deadlines and Request-scoped values

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi my name is mario welcome to another video in today's episode we're going to be learning about go specifically about the context package so the context package is something that you most likely are already using if you have been using the database sql package well it's most likely that you have seen these two methods the dbquery context and the exact context that belong to the db type what does receive a context package another context package a context type in the first argument not only that the net http as well has a method called not new request with a with context that happens to be also using the context package so it's most likely you're familiar with this package although maybe you don't know exactly what is happening behind the scenes and not only that if you happen to use an open telemetry well you're also using the context package so what is in the context package well the context package defines a type called context that defines deadlines cancellation signals as well as well as request the scope values so let's look at these three things and more precisely and i will give you examples of one of them in real life let's start with the deadlines so the deadlines there are two ways to do this the first one will be using this function called with deadline that receives a parent and a time and returns a context and a cancel func function if you think about it will be sort of like hey it's beginning at this point in time and i want it to end at this point in time specifically on the other side we have this function called with timeout that similarly receives a context as a parent as well as a time and returns similar values which will be the context as well as well as the cancel func the difference will be that instead of saying hey and at x time you say and after x amount of time and the way i want to show you i want to explain this with you to you is is by showing you an example so let's jump into the code and i will show you what is happening behind the scenes so right here we have a function called deadline all right a file called main deadline that what it does is um what is supposed to be doing this is defining a timeout that says hey there's a short duration so this is supposed to be ending after one millisecond and the way i'm trying to demonstrate this is that there is this uh select that if you're not familiar with this the way this works is that a in goal select is a keyword for grouping different go routines and whatever happens whatever guru things are grouped in that block will be executed when those are triggered so in this case there is a time that will be triggered after one second and this one will be triggered after the timeout is happened so if i run this if i run main deadline it will be timing out and the reason being is that it says hey finish after one second and this one says hey finish after all right finish after one millisecond and this one is hey finish after one second if i change this to something like second two seconds what is going to happen is that hey you are supposed to be timing or timing out after two seconds so i'm going to be sleeping for one second and if nothing happens after two seconds i will be failing if i run this again you will notice that it says overslept because this means that this was triggered and this one never happened all right so let's go back to the and discuss the other functions available in the context package besides that lines we also have cancellation signals and the way this works is that you have this function called with cancel that receives a parent returns a context as well as a cancellation func and instead of waiting for a time you literally have to call it to trigger to trigger all the cancellations that happened to be associated with the with the context that was derived from the initial context let me show you how this works in practice so this one is a little bit more complicated because there are a few different things that if you are not familiar with but still i will i will explain you all of them so we have a main function we have a channel we have we have a function right here that does some work we have the important bit that i'm trying to explain which will be calling with cancel and as well as running the function that we define above it now the important thing is that i have a few different comments right here that say hey when this happens this will be trigger and then in the end this will be trigger so let's run it first to see what happens and i will give you sort of like a step by step to what happens behind the scenes so there's a waiting to cancel there is a goodbye exiting and buy okay so let's let's again go into the code and see what happens i'm defining a channel okay and defining a function then i'm defining a with cancel context that happens to be running a go routine that is for two seconds and then it calls cancel then i'm also writing a good thing that happens to be running this function right here that is just listening and printing out values every 300 milliseconds so what is going to happen what is happening if you notice if you go back to the to the output is that every 300 milliseconds i'm printing i'm printing out a an int okay however if i receive a signal that says hey this is this context is cancel i'm going to stop printing out values and also i'm going to be closing the channel that i define above which is right here and this channel is just for demonstration purposes and to show you how to do some sort of great graceful shutdown but really the important bit is that because i'm canceling right here what is triggering is this this this execution right here that in the end stops this goal routine that indicates that everything after or associated to my contacts should stop so that's the difference between the deadline and the timeout that we saw before is that this one is sort of a trigger manually and the other one is triggered by a time or by some sort of uh elapsed time all right so those are the two differences between the two two ways to cancel things now let's jump into the last way or the last method that is defined in the context package so the last thing included in the context package will be request scope values and these are as a little bit complicated and not because they are difficult to use more but more that when the idea when we should be using them okay so please follow me along okay so we have this function called with value that happens to receive an apparent a key and a value and return as a context and you have to use that context to pass it down to whatever request you're supposed to be doing so the way it works is that you define some key value values with whatever you want to use or whatever you're supposed to be using and then from there you pass them down to a different requests so how does this work in practice let's look at the code and i will show you the example that i have so we have this example that is called main value and this is a bit hard to explain with these i don't know six lines of code but i want you to think about hey when i'm trying to pass down um context a context value between different layers if for example i have a request that is coming from a customer that happens to be including a an authentication header and i need to use that authentication header as an argument for a different request perhaps it makes sense to include that as part of the in in the context as well so that's what i'm trying to explain right here so i have a call called with value that receive the context whatever that is it defines this a cons called oauth to allow you to explicitly indicate indicate what the value is in this case and then some whatever while i'm trying to pass down to the subsequent call then i use the api that is defined in the context type called value to get the actual value that happens to be a string i just do some type casting and then i just print it out again this is one of those things that it's a bit hard to not to use it i mean it's pretty straightforward but rather to make a good use of it okay so don't overuse it this is one of the things that i'm trying to explain so let's go back to the things that we should be doing next and the best practices when using the context package okay so what are the best practices when using the context package well if you happen to need a context in your api you should be defining the context argument as your first argument in your api if you have seen my previous videos for the microservices uh how to build microservices in go you will notice that most of the requests that happen to be using something that requires some deadliners or some cancellation all of them have an argument context or ctx context context as the first argument the other one will be if you are defining deadlines and cancellations you need to make sure to call that function or otherwise you are going to be linking memory and licking goroutines obviously like i was mentioning just now a few minutes ago when using width value you just need to make sure you are not over using it it's one of those things that you you need to be you need to be careful with that because it's really specific the use case is really specific and and and again i will leaving you i will be leaving you a few a few links in the description so you can read about that that the things that you shouldn't be doing okay so with that being said uh why is this important why this package is important obviously because it's not only useful for defining a few different timeouts when you're working with external apis but also at the same time to trigger um information between different services like when we disclose open telemetry but also at the same time you can define your own different logic when when when trying to say hey i want to spend this much time when working or depending on different apis or perhaps i need to pass down some some logic between different services and whatnot so context is one of those things that we all need to understand perfectly before digging you know digging down into more specific uh features in in the language so hopefully that makes sense and obviously if you have any comments or questions please please let me know i will do my best to answer them until then please take care and be safe talk to you next time goodbye
Info
Channel: Mario Carrion
Views: 2,328
Rating: undefined out of 5
Keywords: golang, golang context, golang context tutorial, golang context deadlines, golang deadlines, golang cancellation, golang context cancellation, golang context timeount, golang timeout, golang context scopes, golang deadline context, golang context deadline tutorial, golang withtimeout, golang withdeadline, golang withcancel
Id: mgJMIZsWfB4
Channel Id: undefined
Length: 12min 20sec (740 seconds)
Published: Fri May 07 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.