The new handler function type

Prior to Go 1., the request data structure in the standard library did not include any form of modifiable context structure. Due to this limitation in the standard library, it makes sense that many frameworks decided that the standard library definition of what a handler did not offer needed flexibility. That being the case, these frameworks developed their own concepts of context, and changed their handler function type to pass in a context instead. In the following snippet, you can see the differences between these handler types, where the Echo handler function type has a context parameter, while the standard library does not:

type HandlerFunc func(ResponseWriter, *Request) // http handler function type
type HandlerFunc func(Context) error // Echo handler function type

Web frameworks that created a context type and a new HandlerFunc definition that took the context type as a parameter had a few small concerns to address. Firstly, the portability of the handler code to switch from one web framework to another dramatically drops. Effectively, you have vendor lock-in because in order to switch to a new web framework, you would have to refactor all of your handlers. Secondly, the context type used as the parameter would need to include both the request and the response structures, as well as provide an interface to add contextual data. Looking at the current Echo context interface definition, you can see that the context implementation needs to implement 53 methods. The context literally has everything including the kitchen sink.

You might be wondering, if Echo needs to create a new context for every single request, how can Echo be a low-cost abstraction? Echo achieves this by implementing a sync.Pool context, which is a set of temporary instances that may be saved and retrieved. With this capability, every time Echo needs a request context to be created, it actually goes to the pool and draws an existing context instance and re-uses it. Other frameworks do not do this, and suffer from new context instance allocations for every request that comes into their web application:

The context is central to application development within Echo, as you can see based on the handler function signature. From the context structure, you have access to the original request structure, response writer, as well as a shared request, processing state from upstream middleware functions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.71.106