Follow

Follow

CORS handling in the Echo go language!

Maheshwar Ligade's photo
Maheshwar Ligade
·Apr 27, 2023·

3 min read

Play this article

Table of contents

  • Introduction
  • Prerequisites
  • Setup
  • Implementing CORS Middleware
  • Custom Function:
  • Conclusion

Introduction

Cross-Origin Resource Sharing (CORS) is a security feature implemented in modern web browsers that allows web applications to make requests to a different domain than the one that served the application. This is necessary when a web application wants to access resources from a different domain, such as an API endpoint, and is commonly used in building modern web applications.

Echo Go web framework provides a middleware for handling CORS requests. In this article, we'll go through how to implement CORS middleware in Echo Go web framework to allow cross-domain requests to your REST API.

Prerequisites

Before getting started, ensure that you have installed the latest version of Echo Go web framework and have a basic understanding of building REST APIs with Echo Go.

Setup

To implement CORS middleware in Echo Go web framework, you'll need to use the "github.com/labstack/echo-contrib" package which provides additional middleware, including CORS middleware.

To get started, install the "github.com/labstack/echo-contrib" package by running the following command:

go get github.com/labstack/echo-contrib

After installing the package, import it in your Echo Go web application:

import (
    "github.com/labstack/echo-contrib/cors"
    "github.com/labstack/echo/v4"
)

Implementing CORS Middleware

To implement CORS middleware in your Echo Go web application, use the cors.New() function provided by the "github.com/labstack/echo-contrib" package:

func main() {
    e := echo.New()

    // CORS middleware
    e.Use(cors.New(cors.Config{
        AllowOrigins: []string{"*"},
        AllowMethods: []string{echo.GET, echo.PUT, echo.POST, echo.DELETE},
    }))

    // Start server
    e.Logger.Fatal(e.Start(":8080"))
}

In the above code, we use the cors.New() function to create a new instance of the CORS middleware with the specified configuration options. The cors.Config struct allows us to set the allowed origins and methods for the CORS requests.

In this example, we have allowed all origins by setting the AllowOrigins option to []string{"*"} and allowed only four methods (GET, PUT, POST, and DELETE) by setting the AllowMethods option to []string{echo.GET, echo.PUT, echo.POST, echo.DELETE}.

Once the middleware is implemented, it will automatically handle the CORS requests for all endpoints in your Echo Go web application.

Custom Function:

In addition to the built-in middleware functions, Echo also allows you to define custom middleware functions using regular expressions. This can be useful if you need to apply middleware to a subset of routes that share a common pattern.

To define a custom middleware function using regex, you can use the Match function of the echo package. The Match the function takes a regular expression string and a handler function as arguments. The handler function will be called for any route whose path matches the regular expression.

Here's an example of defining a custom middleware function using regex:

func customMiddleware() echo.MiddlewareFunc {
    return func(next echo.HandlerFunc) echo.HandlerFunc {
        return func(c echo.Context) error {
            // Your middleware logic goes here
            return next(c)
        }
    }
}

func main() {
    e := echo.New()

    // Apply the custom middleware function to any route
    // whose path matches the regex pattern "/api/*"
    e.Match([]string{"GET", "POST"}, "/api/*", customMiddleware())

    e.Logger.Fatal(e.Start(":8080"))
}

In this example, we define a custom middleware function called customMiddleware that simply logs a message. We then use the Match function to apply this middleware function to any route whose path matches the regex pattern "/api/*".

Note that the Match the function takes an array of HTTP methods as its first argument. This allows you to specify which HTTP methods the middleware should be applied to.

By using custom middleware functions with regular expressions, you can easily apply middleware to subsets of routes that share a common pattern.

Conclusion

In this article, we've seen how to implement CORS middleware in Echo Go web framework to allow cross-domain requests to your REST API. By using the cors.New() function provided by the "github.com/labstack/echo-contrib" package, you can easily configure the allowed origins and methods for your Echo Go web application.

I hope this helps, you!!

More such articles:

https://medium.com/techwasti

https://www.youtube.com/channel/UCiTaHm1AYqMS4F4L9zyO7qA

https://www.techwasti.com/

\==========================**=========================

If this article adds any value to you then please clap and comment.

Let’s connect on Stackoverflow, LinkedIn, & Twitter.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!

See recent sponsors Learn more about Hashnode Sponsors
 
Share this