As the person who asked that other question:
- gorilla/context allows you to store data in the request. If you have some middleware that does some pre-processing on a request before deciding to continue (i.e. anti-CSRF), you might want to store a token in the request so your handler can pass it to the template. The gorilla/context documentation explains it well:
... a router can set variables extracted from the URL and later application handlers can access those values, or it can be used to store sessions values to be saved at the end of a request. There are several others common uses.
- You may also want to store data in the session: error messages from form submissions, a user ID, or the 'canonical' version of the CSRF token for that visitor will likely be stored here. If you try to store an error message in the request context, and then re-direct the user, you'll lose it (that's a new request).
So why would you use context over sessions? It's lighter, and allows you to de-couple parts of your application (often, HTTP middleware!) from each other.
Example:
- Request comes in
- CSRF middleware checks the session for an existing CSRF token. Does not exist, so it sets one.
- It also passes this new token (via the request context!) to the handler that renders your form, so it can render it in the template (otherwise you would have to pull the token from the session again, which is wasted effort)
- Request is done.
- New request on form submission
- The token still persists in the session, so we can compare it to the submitted token from the form.
- If it checks out, we proceed to process the form
- If not, we can save an error in the session (a flash message; i.e. one that is erased after reading) and re-direct.
- This re-direction is a new request, and therefore we can't pass the error message via the request context here.