How can I rewrite the url before it is handled?


#1

Hi,

I want to rewrite the url before requests are handle. how can I achieve this?

my incoming request: http://foo.com/service-name/bar => should become /bar.

Thanks in advance,
Ron


#2

@rhvdwijngaard You can create a middleware and hook it up before the router is hit using https://godoc.org/github.com/labstack/echo#Echo.Pre API. Something like below:

package main

import (
	"net/http"

	"github.com/labstack/echo"
)

func main() {
	e := echo.New()
	e.Pre(func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			if c.Request().URL.Path == "/service-name/bar" {
				c.Request().URL.Path = "/bar"
			}
			return next(c)
		}
	})
	e.GET("/bar", func(c echo.Context) error {
		return c.String(http.StatusOK, "/bar")
	})
	e.Logger.Fatal(e.Start(":1323"))
}

PS: You can use some efficient code for matching the path.