labstack / echo

High performance, minimalist Go web framework
https://echo.labstack.com
MIT License
29.86k stars 2.23k forks source link

Is there a way to emulate fiber.Mount in echo? #2298

Closed 4strodev closed 2 years ago

4strodev commented 2 years ago

Issue Description

I used to work with fiber. And a feature that I love is that you can mount a router under a path. This allows you to create a router separate from app instance and then mount that under your application. Even you can create a group and then under this group mount the routers that you need for example.

main.go

func main() {
    // Example with fiber go to https://docs.gofiber.io/api/app#mount
    micro := fiber.New()
    micro.Get("/doe", func(c *fiber.Ctx) error {
        return c.SendStatus(fiber.StatusOK)
    })

    app := fiber.New()
    app.Mount("/john", micro) // GET /john/doe -> 200 OK

    log.Fatal(app.Listen(":3000"))
}

This allows me to create a group for API routes and in this group mount the routers of this API.

Is there a way to do something similar with echo?

aldas commented 2 years ago

Echo has way of creating collection of routes (called Group) that share same path prefix and have same middlewares. Note:

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

    // signature for creating Group is `Group(prefix string, middleware ...MiddlewareFunc)` so
    // you can add any number of middlewares to the group   
        g := e.Group("/users", middleware.CORS(), middleware.RequestID())
    g.GET("/:id", func(c echo.Context) error {
        return c.JSON(http.StatusOK, map[string]string{"username": "test"})
    })

    if err := e.Start(":8080"); err != http.ErrServerClosed {
        log.Fatal(err)
    }
}

A little bit more evolved example

package main

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

    api := e.Group("/api", middleware.Logger(), middleware.Recover())
    users.registerUserRoutes(api)

    if err := e.Start(":8080"); err != http.ErrServerClosed {
        log.Fatal(err)
    }
}

package users

// this function you can add under `users` package for example to split your application logic
// into separate domain packages
func registerUserRoutes(parent *echo.Group) {
    // signature for creating Group is `Group(prefix string, middleware ...MiddlewareFunc)` so
    // you can add any number of middlewares to the group
    g := parent.Group("/users", middleware.CORS(), middleware.RequestID())

    g.GET("/:id", func(c echo.Context) error {
        return c.JSON(http.StatusOK, map[string]string{"username": "test"})
    })
}