How To Use The Context Package In Golang?

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what is up everyone in this video I'm going to teach you everything you need to know about golang's context package it's very very important because a lot of interviews calling interviews for some kind of a job are asking everything about Googling context package they are probably going to ask you to implement something like that so it's very common use case in the industry but before we continue if you like the content I'm providing to you consider subscribing to my channel give me a thumbs up leave some questions in the comments jump into my Discord community so you can level up and turn into a high value software engineer so without any further Ado let's get started so basically first of all we're going to mimic some kind of a real use case and let's make a function which is going to be a fetch are we going to call this fetch dirt party stuff and we're gonna say which uh can be slow which is not a correct function name but hey for the sake of this tutorial because in a very common use case is that you are in one of your handlers in your HTTP handles you're going to enrich some music strict or something or you're going to call some third-party apis and you have actually no clue how long it's going to take because it's their servers and a lot of people think that making resilience systems is all about handling errors but that's not the case a lot of time you also wanna minimize or reduce the inconsistency of functions that's going to take a long time especially these third-party functions right because they are the cause of all evil because we don't have any control right so we're going to say fetch dot party stuff which can be slow and it's going to return it could return anything right but we are going to return an end and we're also going to return an error because a lot of people were asking me yeah but how am I going to handle errors coming from go routine and all that stuff right so hey I'm going to teach you everything you know so uh that's what we're gonna do um of course we need to mimic we need to rapidly replicate some kind of an HTTP round trip lack delay so you're going to say time uh we're gonna sleep it and we're gonna say time uh milliseconds and that's gonna be let's say 500 which is a which is slow right and then we're gonna return in this case what are we gonna return I think you're gonna return the devil which is 666 666 rather and uh no right so that's this or a fetch third party stuff which can be slow right then we are going to make actually our own function right because this main will basically replicate uh for example an HTTP Handler which users are getting can call and then it will basically call some some of your own business logic and that's exactly this function so we're going to say uh fetch uh user data for example right but we are good Engineers so we provided a context which is going to be a CTX context context and I'm going to say a user ID which is going to be an end and it's going to return exactly what we want and ends and an errors like this and then we're going to say something like uh we could do a lot of stuff but for the sake of we're gonna call let's save this first uh we're gonna call this fetch third party stuff which can be slow yes so we're gonna say that the value and the error is going to be fetch third party so if it's going to be slow you're going to say if the errors is not nil we're going to return zero and an uh error hit and then in this case we're going to return the value and no right and you could say yeah but Anthony why are you what are you doing this you could actually just return fetch third party stuff which can be slow so we don't need to do this here you're 100 right but we are gonna we're gonna use this right so hey I'm already thinking up front I'm a chess player that's that's not true but hey so that's that's thing so then in our HTTP Handler what you're going to do is basically we're going to say uh Val SC code please uh we're gonna say Val ER is going to be a fetch user data right we're gonna give it a context and actually you should do it like this context is going to be uh context for example background and then we're going to place in this context here and then we're going to give it a user ID and to make it super clean we're going to say a user ID is going to be 10 for example and we're going to place this user ID in here then we're going to fetch this address we're going to check it like this and if there is an error you're going to say lock fatal uh like this errors right and in that case we're going to actually when there is no errors we're going to print around the result you're going to say actually result it's going to be the value yes and then we're going to see we're going to match it right we need to measure this so we're going to say start it's going to be time now I'm going to copy this and we're going to say this whole shebang took us time since start right and then if we do a go run main.go and then we're gonna see it takes us exactly 500 milliseconds to fetch the devil to fetch our result right and you can already see it coming right this could actually take a a minute two minutes we don't know right so it's inconsistent it could be an inconsistent Behavior Uh where we have no we don't we cannot control this or do we yes we can so how can we control this how can we make this deterministic right and that's basically by using go links context package so of course we already have this context hit and not fetch user data so what we're going what we're gonna do is basically we're gonna say and we're going to make an uh a new context and we're going to say a cancel and you will see why why this is needed and that's going to be a context with timeout right and with timeout basically means that we're going to create some kind of a context that will time out after a certain after a certain duration which we can choose right so we're going to first of all put in the pattern context and then we're going to say time [Music] um milliseconds and we're going to say a 200 milliseconds that's the Maxima which is already a lot but uh Hey 200 milliseconds that's the maximum amount I want Disturbed party Shenanigans will take to fetch me the results I want right and this cancer is very important because what you need to do is basically defer this guy right defer this why because otherwise we could have a leaking contexts right we don't want that so we're going to defer cancel which basically means that if this function returns it's going to I cannot GD it but it's going to to close it to stop it to cancel it right cool um so that's that's that's okay the next problem we have is this flat third party stuff which can be slow so we need to basically schedule this guy in a go routine so we're going to say go funk you're gonna put this guy you're gonna schedule him somewhere else um and of course because it's a girlfriend we cannot return right uh it it's basically just it's not gonna work so what we're going to do is we're gonna delete all this stuff right and we're gonna say we need to find a way to basically communicate back these values into our main routine how are we going to do this well we can do this with channels right so first of all we're gonna make a response which is going to be a strict and we're going to say it has a value right and this value is going to be an INT and it's going to have an ad which is going to be an error right which is basically this response is exactly these two values here right you see and n10 and error is basically our response right so then we're going to make a channel we're going to say that the response channel is going to be make me a Channel of response like that and then we can actually do this right you could say yo response Channel I'm Gonna Write a response in this from this go routine response and we're going to say that Val the value is going to be the vowel right and the edge is going to be the edge perfectly fine so that's all set up then we're going to basically do a four select right because we need to wait right so everybody is doing a Shenanigans in different Guru teams the context is doing his stuff uh the context package and and this fetch third-party stuff which can be slow is doing his stuff in SQL routine so we are gonna synchronize we're gonna have some Synergy in our function that's why we're going to do a fort and we're going to do a select because we don't need to listen for one channel we're gonna listen for two channels right and I will say uh I'm gonna show you exactly which these two channels are going to be the first is going to be um case uh I'm gonna say case which is this guy right this new city XP we just created we're going to say City X Dom like that right we need to also do a select that's my bad so I'm going to do a select each wrap it in heat and save it for formatting yes so we're gonna say Casey City so that basically means that that basically means Dom is getting called from the moment or timeout is being triggered right and when is when is that being triggered is being triggered after 200 milliseconds so after if we call fetch user data after 200 milliseconds this channel will be closed right and this done channel is basically an anti-strict right it's just closing an empty strict because an empty strict has no bytes so it's basically a free thing you just close nothing it's just compile the stuff the compiler will compile this into what it needs to compile but it will not allocate any bytes because it's an empty strict right no memory right in this economical crisis no bytes is perfectly fine right need to save money so we have this uh case this is done what we're gonna do what what or what would you do when this timeout is being triggered when your function is too slow exactly you're going to return nether right so we're going to say return 0 because we don't return an end could do zero minus one whatever just in your case this would be maybe a strict or something right maybe a pointer to a strict you could return nail or something right in our case it's just an end so we're going to return zero which means that it's not so we're going to return this and then we're gonna return um Avanti error f and we're going to say um function actually let's make it better we're going to say uh third fetching wait we're gonna say fetching data from dirt body tooks took to one something like that right so that's very simple if it takes longer than we expected we're going to return a network that it took too long um and then we are gonna do another case which is basically a response right we're gonna say that the response when the function actually Returns on time it will return a response which is basically this guy right it's going to be returning the devil and no errors so we're going to say case response I'm going to assign that to a channel and it's going to be yes it's going to be the response Channel you're already I see you thinking and you're right so we have this response and then actually what we're going to return is basically the response value and the response uh ad right why am I capping this like this but and now we can delete this so it can block and tell something is happening so that's fine so basically right now everything is set up this fetch user data is being refactored in a way that is being deterministic based on the timeout we provided so at this we are 100 sure that dispatch user data will not not take longer than 200 milliseconds which is amazing right and which language can which kind of language can do this so fast so clean exactly no um all right so let's let's run this let's run this bad boy we're going to say go run may not go uh okay cool and we see another right we see fetching data from third party took too long why because we have a timeout of 200 milliseconds but this fetch third-party slow thingy will take 500 milliseconds it's too long it's too slow for example let's make this guy behave like it should be for example we're going to say 150 milliseconds for example which is basically much faster than our context and if we run this again go run may not go like this boom now we have a result and it took 150 milliseconds you see that's basically how you can re-implement golang's context package and it's going to be the most um that this use case is going to be the most useful of course you could also store valuables inside context right you could say this context you could say uh for example with value right and then we also need to provide probably a context uh we're gonna say a context with background yeah fine and I'm going to say a key is going to be hello uh Foo and the value is going to be but or something right so now we have and of course it's gonna it's gonna it's a little warning about the key types and everything but don't worry about that so because it's a string right um but it's fine so this CTX basically right now is a context with value which basically means that if we pipe this in a fetch user data uh we can actually um here we could actually retrieve this value we could say value I think it's going to be CTX um value let me quickly see what is this we need to provide a key it's going to be full I guess is that true what I'm saying yes uh and then we could actually fmt print Ln the value and you could say Val you could go you need to cast this right because uh now it's a string but uh so it printerland will work fine but if you want to use this for example you do you put a strict inside of this you will need to cost because it's an interface type and any type so you need to cost that but in our case it's a string uh so we could do this uh Foo right and then we print what am I doing it and then we print a value like that and then we can actually uh go run main.go and you see it's bar right that's why you can use this context because uh you can already imagine if you want to share State between all these go routines popping up uh putting putting in placing assigning it inside of a context value is very interesting what's a very good use case for doing that how I am doing it is with request IDs right you have some kind of a middleware in your system in your microservices and some requests is coming in and you're calling all these other stuff um in your application and the first request you can actually generate a request ID put it inside of a context and each time your each time there is an error occurring in one of your functions you can actually also lock the request ID so you can trace the user's Behavior you can trace your application based on the request ID in carafana elasticsearch or something like that yeah yeah this is next level shift that's actually uh industry stuff that's what you're gonna do uh if you if you have a job if you do this in a day-to-day basis in a decent company right so uh if you like this video if you like the content I'm providing to you subscribe to my channel give me a thumbs up leave some questions in the comment to boost the YouTube algorithm because the YouTube algorithm is a nasty filthy whatever it's filthy so we need to boost this video so everybody can enjoy the value I am providing right and also jump into the Discord very important I have a Discord Community with over I think 350 people where we basically uh where I'm helping people uh watching my videos having some questions I'm answering them personally myself and I'm looking forward to see you in one of my future videos or in my live streams thanks for watching peace out
Info
Channel: Anthony GG
Views: 55,151
Rating: undefined out of 5
Keywords: golang, golang tutorial, golang tutorial for beginners, golang for beginners, learn golang, golang 2022, go lang, go programming, go programming language, golang programming, golang in 2022, go programming tutorial, go language, golang tutorials, go tutorial, golang introduction, golang goroutines, golang async, goroutines and channels in golang, goroutines, goroutines in golang, programming, golang concurrency, go concurrency, golang context, context api tutorial
Id: kaZOXRqFPCw
Channel Id: undefined
Length: 17min 2sec (1022 seconds)
Published: Tue Nov 22 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.