Golang Context Explained - How To Use With Timeout

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this video I'm going to describe the go context package because I got a lot of question about it with people's asking how do I really use it why should I use it I don't really understand it Melky can you do a video on this and obviously I can I make Go videos all the time we love go here look at this look at this pink plushie over there they love go the go context package is actually super important but there's some misconception about it you don't need context in every app you build but there are particular use cases where the contacts library is very crucial so the context package typically seen when you have concurrent operations like such as a go routine so you don't have a leaky go routine or you don't have an execution that takes forever and your application is hanging but contact is also used heavily when you're just making you know HTTP requests or database queries it's use predominant definitely with its context with context timeout method and property to really control and make sure your application or your code is actually designed correctly not only is it about handling errors which is also very important but also handling the behaviors of when you call third-party apis or when you query a your database which is massive or your query is just not optimized so on my screen here I have a very simple diagram I'll showcase more in detail in just a second here of how context is typically handled in a very high level overview of it so initially you have your parent functions could be a main.go this could be you know the entry point your application typically if you're using serverless is like the Handler for your Lambda function but this is where you declare your context and this is where you declare a context with a timeout with a deadline meaning if within the context the proper this context whether it's passed through one API function or multiple API functions the execution has to be contained within that timeout and if it gets passed down to you know an app or a function called call Api function this could be called third-party function query database function whatever it is then you basically have to ask yourself is time to fulfill call greater than contacts meaning if I've executed the call to this third party and I'm hanging I'm waiting for the result and it's longer than my contacts or the time is exceeded beyond my context then we will error out otherwise no and we'll continue and handle the logic as needed Okay cool so I have my editor open there's absolutely nothing there's a Gold Dot mod file and a main.go file and the main.go file is pretty much empty but I'm going to show you an example of how context matters and how it's super important in the examples I just talked about so let's go ahead and Define a main function uh just you know it doesn't do anything it's going to be the entry point of our function if you will but this function all it's responsible for is calling a third part API so you know calling third party API and what this API will do is it will check if a user is subscribed to a YouTube channel or not I'm not actually going to call a YouTube API or Google API but this is going to be a high level example all right so let's define this third-party API function so first it's going to be funk call third party API it's going to take two arguments the first is contact context dot context and then let's just say it's going to take a user ID which is type int um and all this is going to do is just a placeholder but I'm exaggering the the functionality of an API all right and it's going to return a Boolean which is true or false or an error all right and so let's say this third-party API when you call it it takes 400 seconds right 400 times time dot milliseconds so to complete this call it's going to take you 400 seconds and we're going to do just return uh if nothing happens we're gonna return true and we're gonna return the uh nil okay so we're not going to get error anymore now I'm going to skip back to our main function because I'm actually going to declare our context in the parent function so again if you go back to the example here this is our parent function this is we're going to declare the timeout for the context Handler so you're going to CTX context cancel is uh context dot with timeout and here you can put in the actual time that you can put in the context so you're going to declare context.background this is the first time you can instantiate a context and you're going to give it the timeout so let's say for our purpose our pair function our use case our client need this needs us to execute in 200 milliseconds and you can already see that since our call to the third party API text 600 or 400 I should say this is going to be a problem I'm going to do defer cancel because if you don't it's going to leak your context timeout it's going to just it could bleed over it could be a mess so defer cancel super easy it will probably complain if you don't add it all right let's just say user ID is something like 420 69 just some random numbers I have you know nothing crazy so let's go ahead and call the third party API so we're going to do is user subbed and error is call third party API we're going to pass it in our context here and we're gonna pass in that user ID if error does not equal to no then we can simply just log it and create a new error or do a fatal log so we can do something like log dot fatal and we can say something like uh error fetching user status right four and we can put percent D and put user ID here otherwise if is user subbed then what we can do is just for the sake of this example format fmt printf we can say this user is subbed okay so we already know if we call this call all third party API function it's going to error our context is for 200 milliseconds while we have a Time sleep for 400 milliseconds exemplifying a slow API and this could be fun you could do some error handling here but we could do much better so if you do if CTX if our context has an error and that error is context slash dot deadline exceeded then this is where we can handle that error so in this we're going to just return false meaning the user is not subscribed even though they may be but we have an internal server error however the error message we're going to use the errors Library here I'm going to create a new error and say context timeout exceeded and this is now mimic a correct way of a slow API and a context that is clamped down for a specific purpose and I actually just noticed I didn't actually handle this error at all or the error message so error fetching user status for the user and then we can put here error percent s and then we can append it to error here perfect now this should be fine so if you open up our terminal and run go run main dot go we can see here error fetching user status for 42069 error contacts timeout exceeded exit status one exactly what we expect but if we go back and actually do one of two things we can increase our context how much let's say this is 500 milliseconds and we go back and run the exact same go run main.go you can see it this user is subbed for 2069 so this is an example of how context is used to handle any dependencies your application may have on third-party apis or again database quiz or whatever go contacts or concurrent execution executions you may have let me know what you think of this video in comment section below let me know if you want me to explore any other package or if you have anything I may have missed in this video please I would love to see that comment we're so close to 10K so let's get the subscribers if you haven't already it means the absolute world to me but I gotta leave you guys out with two things one do you use contacts a lot do you use it all the time are you a master at the context let me know what your use cases and two you gotta power it
Info
Channel: Melkey
Views: 17,792
Rating: undefined out of 5
Keywords: video sharing, video, sharing, computer science, software engineer, silicon valley, computer programming, coding, learn to code, machine learning, artificial intelligence, cloud, python, javascript, how to code, Data scientist, AI developer, Machine Learning, golang, go, go programming, context package, standard library
Id: fXzzF5y6UEU
Channel Id: undefined
Length: 8min 22sec (502 seconds)
Published: Tue Sep 26 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.