Reverse Proxy

This recipe demonstrates how you can use Echo as a reverse proxy server and load balancer in front of your favorite applications like WordPress, Node.js, Java, Python, Ruby or even Go. For simplicity, I will use Go upstream servers with WebSocket.

1) Identify upstream target URL(s)

  1. url1, err := url.Parse("http://localhost:8081")
  2. if err != nil {
  3. e.Logger.Fatal(err)
  4. }
  5. url2, err := url.Parse("http://localhost:8082")
  6. if err != nil {
  7. e.Logger.Fatal(err)
  8. }
  9. targets := []*middleware.ProxyTarget{
  10. {
  11. URL: url1,
  12. },
  13. {
  14. URL: url2,
  15. },
  16. }

2) Setup proxy middleware with upstream targets

In the following code snippet we are using round-robin load balancing technique. You may also use middleware.NewRandomBalancer().

  1. e.Use(middleware.Proxy(middleware.NewRoundRobinBalancer(targets)))

To setup proxy for a sub-route use Echo#Group().

  1. g := e.Group("/blog")
  2. g.Use(middleware.Proxy(...))

3) Start upstream servers

  • cd upstream
  • go run server.go server1 :8081
  • go run server.go server2 :8082

4) Start the proxy server

  1. go run server.go

Browse to http://localhost:1323, and you should see a webpage with an HTTP request being served from “server 1” and a WebSocket request being served from “server 2.”

  1. HTTP
  2. Hello from upstream server server1
  3. WebSocket
  4. Hello from upstream server server2!
  5. Hello from upstream server server2!
  6. Hello from upstream server server2!

Source Code

cookbook/reverse-proxy/upstream/server.go

  1. loading...

cookbook/reverse-proxy/server.go

  1. loading...