Middleware Creation for REST API
Learn how to add middleware to the REST API application.
We'll cover the following...
Add middleware
Middleware is a component that acts as an interceptor for the request before another request has proceeded. For example, the middleware is added to create a new item request. In this example, the middleware acts as authentication to ensure the authenticated user can create a new item request.
Inside the auth.go
file in the utils
directory, we add some helpers for authentication purposes.
Before the GenerateNewAccessToken()
function, we add a struct for storing the JWT token’s metadata.
type TokenMetadata struct {
Expires int64
}
After the GenerateNewAccessToken()
function, we create a helper function called ExtractTokenMetadata
.
// ExtractTokenMetadata returns token metadatafunc ExtractTokenMetadata(c *fiber.Ctx) (*TokenMetadata, error) {// verify the tokentoken, err := verifyToken(c)// if verification is failed, return an errorif err != nil {return nil, err}// get the token claim dataclaims, ok := token.Claims.(jwt.MapClaims)// if token claim data exists and token is validif ok && token.Valid {// set the token expiration dateexpires := int64(claims["exp"].(float64))// return the token metadatareturn &TokenMetadata{Expires: expires,}, nil}// return an error if token is invalidreturn nil, err}
In the code above, the ExtractTokenMetadata()
function is used to extract the token metadata.
We then create a function called ...