Integration of Echo web framework with existing Gorilla Mux API

1.3k views Asked by At

I am wanting to move to the echo framework for my API due to an openapi package we wish to use (opai-codegen) However our current API is built via gorilla mux. Due to the size of the current codebase we need to run them both side by side.

So I am trying to work out how do I get gorilla mux and the echo framework to work together via the same http.Server

The gorilla mux API is created via:

router := mux.NewRouter().StrictSlash(true)
router.Handle("/..",...)
//etc ...

And then my echo API is created via:

echo := echo.New()
echo.Get("/..", ...)
// etc ...

However I can't get them to run with the same http.ListenAndServe

Love to know if there is any to make these two work together?

Thanks

1

There are 1 answers

0
Shubham Srivastava On

This is what i can think of, Although you will need to move middle-wares to echo

package main

import (
    "fmt"
    "net/http"

    "github.com/gorilla/mux"
    "github.com/labstack/echo/v4"
    "github.com/labstack/echo/v4/middleware"
)

func main() {
    // Echo instance
    e := echo.New()

    // Middleware
    e.Use(middleware.Logger())
    e.Use(middleware.Recover())

    r := mux.NewRouter()
    r.HandleFunc("/mux/", Hello).Methods("GET", "PUT").Name("mux")
    r.HandleFunc("/muxp/", HelloP).Methods("POST").Name("muxp")

    gorillaRouteNames := map[string]string{
        "mux":  "/mux/",
        "muxp": "/muxp/",
    }

    // Routes
    e.GET("/", hello)
    // ro := e.Any("/mux", ehandler)

    for name, url := range gorillaRouteNames {
        route := r.GetRoute(name)
        methods, _ := route.GetMethods()
        e.Match(methods, url, echo.WrapHandler(route.GetHandler()))
        fmt.Println(route.GetName())
    }

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

// Handler
func hello(c echo.Context) error {
    return c.String(http.StatusOK, "Hello, World!")
}

func Hello(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintln(w, "Hello world!")
}

func HelloP(w http.ResponseWriter, req *http.Request) {
    fmt.Fprintln(w, "Hello world By Post!")
}