Search code examples
restgoroutesmiddlewarego-echo

How to import sub-routes from other packages


Instead of writing every route under main(), like

func main() {
    e := echo.New()
    e.GET("/api", sayHello)
    e.GET("/api/music", getMusic)
    e.GET("/api/user/:id", getDetail)
    e.POST("/api/user", addUser)
    // ...
}

How can I import these all sub-routes from a file called api.go, and use those in the main function? Similar to

import "./API"
func main() {
    e := echo.New()
    e.UseSubroute(API.Routes) // <-- similar to this
    // ...
}

Solution

  • The Echo object does not have this method. I think you need the code?

    API.go:

    package main
    
    import "github.com/labstack/echo"
    
    func UseSubroute(echo *echo.Echo)  {
        echo.GET("/api", sayHello)
        echo.GET("/api/music", getMusic)
        echo.GET("/api/user/:id", getDetail)
        echo.POST("/api/user", addUser)
    }
    

    main.go:

    package main
    
    import "github.com/labstack/echo"
    
    func main() {
        e := echo.New()
        UseSubroute(e)
    }
    

    These two files need to be placed in the same directory.

    Do you need it?