Learning Golang Context!! Never Looked At It!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
there you go go by example there we go all right so we're going to look a little bit about context because I know nothing about go context I see it used from time to time as far as I can tell it's like a cancellation feature that you can use to be able to pass context around and use that as a form of cancelling I don't really quite get what it means but let's kind of look at this okay in the previous example we looked at setting up a simple HTTP server HTP servers are useful for demonstrating the usage of context. context for controlling cancellation a context carries deadlines cancellation signals and other request scoped values across API boundaries and go routines okay so this is something like an abort controller in JavaScript all right let's look at the code really quickly we have a little hello response writer request we create a context from the or we grab the context off the request we say hey we're started we say hey the thing is ended we do a little select in which we're doing hey time after 10 seconds print hello or when the context is done we do a little context error we print the error internal server error and then we write the error as the error is that what we're doing doing here yeah we take the writer and we write the error as the internal error it timed out okay cool yeah that's the writer so little writer contract here we do a little uh handle Funk hello serve it up okay cool okay okay so I think I understand that so there is like a done so from the outside we can time out things from the outside okay that's cool I didn't realize that it's like a little Channel little channel right a little Channel that's cool you know about that uh let's see a context context is created for each request by net HTTP machinery and is available with context method wait a few seconds before sending a reply to a client this could simulate some work the server is doing while working keep an eye on the contacts done channel for the signal that we should cancel the work and return as soon as possible the contact airor method Returns the airr that explains why the done channel was closed okay cool as before we register our Handler on the Hello route and start serving okay cool cool okay okay I I think I have a gen I think we have a general understanding of this get rid of norming keywords okay go doesn't need a framework go does not need a framework yeah you don't even need a framework for me the easiest way to understand was just looking at the package documentation it's very well written yeah I was going to go through these two things and then go from there all right let's look at one more go concurrency patterns context okay let's see in go servers each incoming request is handled on its own go routine uh request handlers often start additional go routines to access backends such as databases and RPC services to set uh the set of go routines working on a request typically needs to access a request specific value such as identity of the user authorization tokens and request deadlines when a request is canceled or times out all the go routines working on that request should exit quickly so the system can reclaim any resources they are using facts at Google we developed a context package that makes it easy to pass request scoped values cancellation signals and deadlines across API boundaries to all the go routines involved in handling a request this package is publicly available as context this article describes how to use the package and provides a complete working example Okay cool so let's see the context type it's an interface it has a a done an error a deadline and a value the value return let's see the value Returns the value associated with the key or nil if none interesting a key value store on a context huh I didn't know about that did you know about that I didn't I didn't know that there's a value what would you use a what would you use a key value for on a context is that so you can store the authorized user so it's literally there's two types of there's two things going on here so it's like context with values how do you set values on that oh yeah an au user is one example okay that makes sense so how would I set a value on that because I don't see anything that is for me setting values context. with value okay oh okay well that's not on the interface dog I don't see I don't see no I don't see no values okay context well where's this with value oh you pass a context with it oh it's a package level function oh I see what you're saying yeah yeah yeah yeah yeah yeah yeah yeah yeah yeah and then the the argument the it literally must be just an argument that is the context itself and bada bing bada boom all right this description is condensed the Google Doc uh uh is authorative okay the go do is authorative nice uh the done method returns a channel that acts as a cancellation signal to functions running on behalf of the context when the channel is closed the function should abandon their work and return the error method Returns the error indicate or indicating why the context was canceled the pipeline and cancellations articles discusses the done Channel idiom in more detail a context does not have a cancel method for the same reason the done channel is receive only the function receiving the cancellation signal is usually not the one uh that sends the signal in particular when a parent operation starts go routines for sub routines those sub operation should not be able to cancel the parent instead with cancel function described below provides a way to cancel a new context value okay okay so if you want to be able to have because you could imagine there are reasons why like there are reasons why you'd want to be able to have children being able to cancel the entirety of the request I think that makes sense in some level I think so note that when you always let's see note uh also that you always constructing a new one from a previous using a with X function so they uh they get very Atomic it's hard to screw them up uh by reference they're super safe and it's amazing okay okay imagine JS having something like uh go routines go routines are just they're out of control right we you you don't get that you can't have there's like there's reasons why you can't have that uh I mean obviously the engine expects JavaScript to only be executing you know one at a time so there'd be a whole locking problem that would exist but number two you'd also have the follow-up problem with if an error is just randomly thrown in some undefined context who who's whose problem is it right because you can imagine that you have a call back function that just throws a top level error an unhandled exception so you so that's why typically they use uh they use V8 isolates like they actually have their own isolated run context of a JavaScript engine each running and so that way if there's an un like just an err that is thrown in some some place that is not handled it's able to just say like this whole thing is effed you know what I mean uh go routines must have problems with interrupt that's why they created channels right um all right let's see context is safe uh for simultaneous use by multiple go go routines code can be passed uh can pass a single context to any number of co- routines uh and cancel that context to Signal all of them the deadline method allows functions to determine whether they should start work at all uh if too little time is left it may not be worthwhile code may also use a deadline to set timeouts for Io operations value allows context to carry request scoped data the data must be safe for simultaneous use by multiple go routines cool that's super cool so yeah that would definitely make handling like request specific values that's pretty cool request specific values you can then pass around to everything you know executing below okay context is pretty cool okay cool I'm glad I've read this because you know we're making a the the SSH app with uh wish and bubble te and I was thinking about how do I pass in who is like who's running like what is the thing that's running in everything and so I could use context as my general method to be able to handle it though there would be no cancellation signal that I can think of I mean maybe there would be the problem is that bubble te itself is the one that determines when the thing is done huh but we have a way to we have a command for that to exit so I guess I don't need any sort of cancellation in that kind of sense okay that's kind of interesting I like all this I like this control c yeah well control C is sent through and then you do a bubble you do like a bubble te uh command exit there's no I'd have no deadline but instead I would have context values associated with it I like it yeah t. quit yeah I'm not super I'm not super familiar with it yet but I know that it exists uh background is the root of any context tree is never cancelable okay that makes sense it's the top level with cancel and with timeout return derived context values that can be canceled sooner than the parent context the context associated with an incoming request is typically canceled when the request Handler returns with uh cancel a crap I made with cancel is also useful for canceling redundant requests when using multiple replicas with timeout is useful for setting deadlines on request for backend servers this is super useful stuff this is like super duper useful stuff here uh with value provides a way to let's see to associate request scoped values with the context oh man this is great parent context key interface key uh value dang the best way to see how to use the context package is through worked example okay let's look at this an example Google web search our main our example is an HP server that handles URLs like search all this crap forwarding J let's see forwarding the query goang uh to the Google web search API and rendering the results the timeout parameter tells the server to cancel the request after a duration elapses the code split across three packages server provides the main function okay uh user rip uh user rip oh damn or user IP it's probably what it is use use rip uh provides functions for extracting user IP uh address from the request and associated with the context provides search functions okay server program handles a request like this okay by serving a few Google search results for goang it registers handle search to handle the search endpoint the Handler creates an initial context called context and arranges uh for it to be canceled within uh when the hand Handler returns if the request includes the timeout URL parameter the context is canceled automatically when the timeout elapses okay let's see this we create a quick context okay we have a cancel function and we have a context timeout error parse duration form value all right if air equals nil then context cancel equals with timeout background timeout else with cancel okay so with timeout and with cancel defer cancel okay cool I get that this is shock you know every time I read go code the concepts are always shockingly easy isn't that just weird isn't that just like just bizarre about how easy a lot of these things man I love go 17 when I dropped the beautiful piece of code on us yeah see I the language is crap though I just don't think it's crap I think it's simple I think it's only crap because you want it to be something else you know like that's the thing is like Vim is crap if you want Vim to be like vs code right if you wanted rust to be like go rust would be terrible you know what I mean if you want a JavaScript to be like a really good backend language it would be terrible like do you see like you see how that works like you don't try to make a language into something that it's not dark net you little rascal thanks for those five gifted subs thank you baby let's go let's go let's go all right the Handler extracts the query from the request and extracts the client IPS address by calling a user rip uh package the user client or the client's IP address is needed for back in request so handle search attach attes it to the context okay uh request form value query uh user IP equals get that from the request okay we get it and then we say new context user IP new context from our context with the IP okay interesting interesting so this must okay so every time you do a with value it actually creates a new context so is context almost is context almost monad here Are we almost monad almost so close there's just no inner value you so close so close uh the Handler uh the Handler calls google. search with uh context and the query starts let's see starts time now results air search with this query oh yeah because then you can do a search with the context and a query and if the and if the context times out it just goes oh my goodness yes that is actually pretty Grand because then you could just pass your context with however you want it to be timed out and it just works darket what are you doing that's 20 gifted subs from you sir that's actually super cool yo that's pretty cool that's pretty good uh go channels and Associated stuff definitely has some function uh functional earling inspiration to them whenever you do any sort of message passing yeah okay this is cool again I'm a super I'm I fully admit I'm a terrible goer okay I don't know a lot of go but this is super cool this is honestly this is super cool what I don't get here is what happens to the old context is it consumed it's it's a I I assume say I can kind of I feel like I understand what's happening without knowing a lot about context is that you have your background context which is like the tippity top one when you create a new one my assumption is that it's actually it actually creates a tree of context right every time a new context is created so when you create a with value or you add this value it creates a new one so you still have your previous one which has no values in it and then you have your next one which has values in it and whichever one you cancel my assumption is that it cancels down the tree right so if I canel at this level I would assume that all cancellations would go from here down the tree that's kind of like how I'm envisioning how this works so if I cancel at this level I don't cancel the top level context that was P like I don't cancel at the level above me I cancel at my level and down that's how I would assume that this all works they do indeed propagate down the tree like that yeah yeah correct okay cool okay I didn't think that uh but it's sharing key values yeah of course it's sharing key values so up at the tippity top you build your context with your base level of key values this is how I would use it at least right now right so I have my key values key one value one right key2 value two right and then my service we'll call it search as well for this for the sake of understanding things we'll call it search and in here when I get a context I can have my search context which maybe I add with timeout right and I have a timeout and I hand this to my Sur like my subservices that I'm going to go do all my little subservice stuff so the top level doesn't have to be timed out instead my search level can be timed out like hey this is what I expect wow this looks like a person's face did I just draw face did we just draw a face right there that's how I look at that at least that's how I've built it so far in my head from what we've read does does that make sense literally Facebook I literally I literally Drew Facebook new t-shirt logo yeah yeah that's my face makes sense just not sure if the children uh can affect parents I assume the children cannot affect parents I assume it's all one way it's all one way is this true Judo can you can you confirm can we get some confirmations that that what I've said is at least is what is in my head correct yes it's Atomic like that yes okay so it's good it's good old fashion encapsulation can you see what's in my head I can't but you can see what's in my head if the search succeeds the Handler results uh renders the results uh it's thread safe and tree walking it's beautiful that is good okay this is great it it feels pretty easy to understand I hope I hope everyone was able to understand this pretty straightforward because I didn't think this was crazy to understand right um this article makes it seem pretty straightforward when someone said it was a blue a linked list it all made sense then it's a tree right it's not I assume context is not a linked list it's a tree um which makes right because you could I assume you could spawn multiple contexts off of a single context and if you cancel the parent one you cancel all the ones spawned off of it so that would be a tree right it's it's it's like a spider leg tree it's a lot of long ones and few branches is my assumption uh it propagates down the tree but wait for cancellation of them uh from the leaf back to the canceled route interesting I'd have to I guess I don't know the exact execution order so that's something I'd have to play around with to really understand it but okay cool all right package let's see user IP provides uh functions for extracting user IP addresses from the request and associating with the context a context provides a key value mapping where the keys and values are both type interface key must support uh equality and a values must uh be safe for simultaneous use by multiple go routines gez I didn't realize that the godocs got political every now and then uh packages like user IP uh hide the details of this mapping and provide strongly typed access to a specific context value I say whatever pops up into the old brain okay I just want you to know that just whatever comes across my brain it just comes right in and right out you know what I mean our values people he reads whatever is on the telepromter it's such a fact it is such a fact hey by the way thank you for I know we're in the middle of reading and going through an article and there's a hype train it's at level five uh dude thank you everybody I really do appreciate that French sardo Viper Ranger Viper Ranger how you doing 14 months let's go uh b b b appreciate that uh Ricardo hey two time the two-tone Ricky Ricardo thank you appreciate that um darket again appreciate like the 20 Subs over time uh solinsky you guys are all making a YouTube video apparently uh stop post facing you wuss I'm not sure what that means uh but I'll I'll try thank you go g appreciate that and D Dance appreciate that down Sal preface postest preface preface postface oh oh yeah dude stop postf facing dude yeah I'm I'm on your team McGrill coder let's go let's go Jon o Deano let's go sepin yeah yeah Juke oh I already saw Juke juked Juke be appreciate that all right hey itchy hey itchy forever let's go oh my goodness if you guys don't know uh old school gamer right retro Gamers here if you like some good Retro Gaming boom I nice hair shut up okay I accidentally lost a bet and now I have now I've been blued I've blued myself okay I'm blue okay I said something I should have said and now look at me all right anyways to avoid collisions user IP defines a an unexported type key and uses the value as this type uh let's see type key int uh user IP key equals zero uh let's see from request let's see from request extracts the user IP value from the HB request from request gets this split host porting get all this stuff yeah yeah yeah yeah yeah yeah blah blah blah blah blah blah we get all that new context uh returns a new context and Carries provided user IP value with value user IP key user IP but how do you get the value back out because it's an unexported type called key oh interesting interesting okay from Context exra the user IP okay okay okay okay but how do how do I use it though contact context where where is it being used new request do this URL user IP equals okay user IP from Context oh oh that's so clever oh I see how they're doing it so okay so by having the type private only one person can provide type key right even though it's just an INT it's of type key therefore if you wish to access the user IP you have to pass in the context and only it can access and grab out that value oh oh oh oh oh oh oh right it never conflicts with any other zero correct yeah because you could potentially someone else could just provide zero right who says they can't have a zero but by having it as its own key no one else can have that specific type the cast at the end can blow up oh the cast at the end can blow up which cast at the end this is cool though it's still yeah it's still just a zero but it's like a special zero it's a zero okay okay this is cool uh uh search uh uses a helper function HP do to issue the HP uh request and cancel if the con context is done uh or the contact done is closed while the request or response is being processed okay little HPD uh defer body clothes here's the oh nice and inline struct ballsy ballsy uh new decoder get this stuff little range data results nil okay so this would be hbd so that must be a little okay so that just does like a little while done and runs this as a go routine and runs this other one okay Fantastico but it still looks like it's going to this thing still looks like it's going to keep on running I assume this thing keeps running all the way through the end every single time uh the cast can't blow up because uh net IP uh can be stored in there we need a dedicated video on your Jaz docu say yeah I want to do that uh I do actually want to do that I actually have some video I have multiple videos I want to record I guess we're going to have to do I I've been trying to figure out what I want to do for my main Channel and so I've been thinking about that yeah anyways okay so this makes sense so we do a little select we we either do when it's done or we get this error back out and we do that uh see make channel one uh request with context we create a request with the specific context we do this thing we grab out the value of this gof funk right here that passes it into the context um we select this thing out okay this make this all makes sense this all makes sense this is cool I like this I actually really like this this is really cool uh many server Frameworks provide packages and types for carrying request scoped values we can Define new implementations of context interface to bridge between code using existing Frameworks and code that expects context parameter for example gorillas gas uh package allows handlers to associate data with incoming requests providing a mapping from HTP requests to key value pairs in Gago we provide a context implementation whose value method Returns the value associated with the specific HP request in the GAA package nice what is his main channel it's not Theo get out of here Theo's a great guy but he ain't me bro all right I like this this was great okay I feel like I understand context more I'm happy with context I still need to use it a bunch I mean one of the one of the things that are obviously difficult right now is that I I I haven't used context and so therefore it will be difficult for me to actually have like that really concrete understanding right it's the difference between The Head and the Heart right now I'm I have head knowledge of of context I need to use it a few times I need to screw it up a few times you know what I mean I need to misuse context a few times then I'll kind of then I'll know how to use it you know what I mean that that's one of my hard Parts is that I always have to misuse something to really understand it in its entirety it's the only way to learn I know but for me it's just so important anyways I was very happy about this okay I like this hey the name is like I kind of get context now and go a genen
Info
Channel: TheVimeagen
Views: 32,171
Rating: undefined out of 5
Keywords: software engineering, software, vim, bash, rust, vtuber, programming, programming live, live coding, coding, developer, developing, web dev, web live coding, rustlang, golang, typescript, javascript
Id: VMonYfJlrc0
Channel Id: undefined
Length: 25min 2sec (1502 seconds)
Published: Fri Feb 02 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.