Difference between standard Golang context pack and Gorilla context pack

What are the differences? Which one is more powerful? Is it possible to do the same using just the standard one context

without using any third party libraries?

+3


source to share


1 answer


Gorilla context pack

stores values ​​shared during the lifetime of the request.

Official context

package

contains deadlines, cancellations, and other request-specific values ​​across API boundaries and between processes.

So, it's obvious from the start that the official package does a lot more. But before going into details, here are some stories:

The Gorilla context package predates the official Go context package. It was created to address a fundamental problem in responding to HTTP requests: different intermediaries and handlers must be able to share the state of the request scope. Things like authenticated username and user id, and the results of the information retrieved from the database before sending it to the template to be parsed, etc.

The Gorilla context package does this with a pretty ugly hack: it creates a map with the HTTP request pointer as the key. To make it concurrency -safe, it transfers all access to that card in mutexes, which makes access slower (although this is real, probably only important for very busy websites).

The Go context package, as said, came later with a different need. The Go context package exists primarily to solve the problem of canceling operations after they are no longer needed.



Before that, if you were making an HTTP request and the user closed their web browser or hit the Stop button or their Wi-Fi connection dropped, you wouldn't know. Your server will happily continue to iterate over, fetch values ​​from the database, create templates, and more, just send the result back ... nobody.

Or maybe your program needs to fetch data from a group of remote APIs, but you're willing to wait 10 seconds. After 10 seconds, you want to cancel the pending requests.

With the Go context package, these things are possible - and easy. By providing the canceled context, the http library can now tell your HTTP server that the HTTP request has been canceled by the client. Or you can set a context with a timeout for the last script.

So, you can see that the two packages are designed to solve completely different problems.

However, the official Go package also has an additional feature. The WithValue method allows you to pass arbitrary data in context. This relates to the same purpose as the gorilla context package, but kind of after a thought.

The best practice these days is to use the official context pack. But this should be done primarily for cancellation purposes. As a secondary benefit, you can also use it to pass values ​​- the same values ​​you pass in the Gorilla context.

But if you only use it to pass values, you will lose about 90% of your gain.

+8


source







All Articles