Skip to content

Instantly share code, notes, and snippets.

@dragonfax
Last active August 31, 2018 18:14
Show Gist options
  • Save dragonfax/906165cde5296b777ba1ecc025497703 to your computer and use it in GitHub Desktop.
Save dragonfax/906165cde5296b777ba1ecc025497703 to your computer and use it in GitHub Desktop.
Blog post on contexts in go.

Whats a Context?

You can find this in a lot of frameworks for web dev nowdays and even a few UI frameworks. I feel its replacing something that some old languages had but modern ones don't. Dynamic scoping.

Think of it as a scope of data. Data that's scoped to the request. Every request might need a timeout, but it might not be a global hard-coded timeout. Different requests might require different timeouts. The headers are also request scoped data.

Dynamic Scope

We had this as a language feature back in perl. It was called "dynamic scoping" vs the "lexical scoping" we're all used to. Where you had global variables. But you could scope the value of a variable to a particular function call and its nested call tree.

$request_data = $old_blah

sub handle_request($blah) {
    local $request_data = $blah;
    execute();
}

Regardless of what value $request_data had before handle_request() was called, for this execution of execute() and all functions it calls, $request_data will have the value of $blah. After handle_request is done the value of $request_data would return to $old_blah.

https://perldoc.perl.org/perlsub.html#Temporary-Values-via-local()

Go's Context

But of course, using globals for everything is bad, so instead in go you have to pass the context around manually though function parameters.

Nested Contexts

Then you take it further and you make this work as nested scopes too. So your whole request might have one timeout, but a subprocess with it, say pulling some data from the database, might need a shorter timeout. So you can nest that smaller bit of data (context) within the larger context. After the db work is done, that nested context disappears, as its scope has been left.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment