duangou1551 2017-02-26 12:34
浏览 33
已采纳

如何使用Golang和LabStack回显处理到多个服务的代理

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.

  • 写回答

1条回答 默认 最新

  • doushuzd3033 2017-02-28 10:08
    关注

    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")
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?