Reader small image

You're reading from  Echo Quick Start Guide

Product typeBook
Published inMay 2018
PublisherPackt
ISBN-139781789139433
Edition1st Edition
Tools
Right arrow
Author (1)
Ben Huson
Ben Huson
author image
Ben Huson

John Huson is an Echo developer
Read more about Ben Huson

Right arrow

Implementing Middleware

Middleware is an important concept in web application development, and when implemented properly, this can result in efficient code reuse. By implementing and employing middleware within your application, you will benefit from an overall reduction in the complexity of your handler code, as well as duplication. This is achieved by taking discrete units of work that are useful to multiple handlers and putting that functionality into middleware that wrap your handlers.

Within this chapter, we will explore common request and response processing pipelines within web applications utilizing Echo's middleware framework. You will be given examples of how Echo middleware chaining works, as well as how implementing middleware will make your application simpler and more maintainable. You will also learn more about available middleware implementations that come...

Technical requirements

Basics of middleware processing

Within a web application, a request message is ingested and a response is produced, as has been reinforced in prior chapters. Typically, within handlers, there are fairly common tasks associated with the ingest of a request. Common request tasks include request body parsing and data binding, logging of requests, validating request authentication and session management, and request metadata creation. Conversely, common response-related tasks include request body rendering, as well as graceful error and panic handling. When you start looking at the common overhead associated with handling a request and generating a response, you can start seeing potential reuse cases.

As a concrete example, we have two handlers, CreateReminder and GetReminder, which parse requests, validate that the user's session is authentic and valid, perform request pedigree...

Middleware chaining

The Echo framework provides three mechanisms for inserting middleware into your request-processing pipeline. The Echo instance's Use(MiddlewareFunc) helper method is the most common way to add normal post-routing middleware. As you may recall, for flexibility we showed you how to use the Group(string) Echo method to organize routes. The Use(MiddlewareFunc) helper method is also available on Group instances so that you can apply middleware functions only to particular groupings of routes as well. Use tells the Echo instance, or grouping instance, that we wish to insert the middleware specified as a parameter into our middleware chain. It should be made clear that the order of your Use calls is very important. The order of the middleware insertion stipulates the order in which the middleware chain will be performed. For example, you might want two middleware...

Creating custom middleware

Middleware functions are just functions that take in a next function and return a function. We are able to do this in Go because functions are first-class citizens, and they can be used as variables. By using this idea, we are able to use regular functions as parameters to middleware functions.

In order to create custom middleware for use within the Echo framework, all we need to do is create a function that conforms to the echo.MiddlewareFunc type, which is as follows:

type MiddlewareFunc func(HandlerFunc) HandlerFunc

The echo.MiddlewareFunc type which defines what a middleware should be is simply a function which takes a next parameter and returns a handler function. In the following example, we are creating a custom middleware which will assign a unique ID to every request that is made, and set our generated unique ID into the echo.Context for use...

In action

Within the Echo project, there is a directory called middleware, which contains many contributed middleware solutions seen here: https://github.com/labstack/echo/tree/master/middleware. These middleware functions have been vetted by the community, and follow the middleware best practices guidelines. In this section, we will dissect one very useful middleware, and show how to use these middleware in our example application.

We will start by looking at middleware.JWT, which is a very helpful middleware that takes a JSON Web Token (JWT) from the request header specified by the developer and validates that the token is legitimate. In our example, the handlers.Login handler will validate the user credentials with bcrypt, and after that verification, we will create a JWT for the caller to insert into their request headers. The following is the JWT creation code located in...

Summary

Throughout this chapter, we have learned about middleware and how to implement and use middleware within the Echo framework. Middleware serves as a means to minimize duplication within your handler code by abstracting common functionality out of the handlers. By using middleware, your code will become more streamlined and easier to maintain as changes can be made without touching every handler within your web application. This means that your web application can remain ignorant to the functionality that the middleware provides. This chapter also outlines a variety of middleware functions that come with the Echo framework that have been contributed to by the community.

The next chapter will dive into details mentioned within this chapter of request data binding. We will also cover the echo.Context primitive, which allows us to pass application context from the Echo framework...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Echo Quick Start Guide
Published in: May 2018Publisher: PacktISBN-13: 9781789139433
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Ben Huson

John Huson is an Echo developer
Read more about Ben Huson