将Echo Web框架与现有的Gorilla Mux API集成

问题描述

由于我们希望使用一个openapi软件包,我想转向我的API的echo框架(opai-codegen)。但是,我们当前的API是通过大猩猩mux构建的。由于当前代码库的大小,我们需要同时运行它们。

所以我试图弄清楚如何通过相同的http.Server

使大猩猩多路复用器和echo框架一起工作

大猩猩mux API通过以下方式创建:

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

然后通过以下方式创建我的echo API:

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

但是我无法让它们使用相同的http.ListenAndServe

想知道是否有任何两者可以使它们一起工作?

谢谢

解决方法

这是我能想到的,尽管您将需要移动中间件来回荡

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,"Hello world By Post!")
}