Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle proxying to multiple services with golang and labstack echo

Tags:

go

I'm new to Go and Micro-services development, but I hope my question will make sense:

Let's say I have a micro-service handling users actions such as creating, showing & updating an user, available at localhost:8081/users.

Beside that, I have a micro-service handlings events' creation, show & update as well, available at localhost:8082/events.

And, above that, there is a gateway, available at localhost:8080 which is suppose to act as a proxy to dispatch the incoming request to the right service.

I found this piece of code which is working well to redirect from my gateway to my user's service:

proxy := httputil.NewSingleHostReverseProxy(&url.URL{
    Scheme: "http",
    Host:   "localhost:8081",
})
http.ListenAndServe(":8080", proxy)

But two things are bothering me:

  • How am I suppose to handle dispatching on multiple micro-services? I'd like to have a condition such as: "If the client requests localhost:8080/users it should go to the user's service. If he requests localhost:8080/events it should go to the event's service. (Please feel free to tell me if this approach is just wrong)

  • As I mentioned in the title, I'm using the labstack/echo Router, so I don't want to start my server with http.ListenAndServe(":8080", proxy), but with something like

    e := echo.New() e.Start(":8080")

    But I can't find how to pass a proxy as parameter with this tool.

like image 820
Charrette Avatar asked Feb 26 '17 12:02

Charrette


1 Answers

Thanks to an answer on an issue I posted on labstack/echo github, here is the solution:

httputil.ReverseProxy implements http.Handler, so you can do something like:

e := echo.New()
proxy := httputil.NewSingleHostReverseProxy(&url.URL{
    Scheme: "http",
    Host:   "localhost:8081",
})
e.Any("/users", echo.WrapHandler(proxy))
e.Start(":8080")
like image 150
Charrette Avatar answered Oct 10 '22 20:10

Charrette