Cowboy 2.9.0 reverse proxy websockets

188 Views Asked by At

I am a newer of elixir。I need to forward the websocket request from the cowboy sever http://127.0.0.1:4000/api to another server http://127.0.0.1:8080/abc. In short, how to implement reverse proxy websockets using Cowboy?

The following is the framework I used:

  • cowboy: 2.9.0
  • plug_cowboy: 2.6.0
  • plug: 1.14.0

The following is my simple code:

# application.ex
defmodule Example.Application do
  use Application
  require Logger

  def start(_type, _args) do
    children = [
      {Plug.Cowboy, scheme: :http, plug: Example.Router, options: [port: 4000]}
    ]
    opts = [strategy: :one_for_one, name: Example.Supervisor]

    Logger.info("Starting application...")

    Supervisor.start_link(children, opts)
  end
end
# router.ex
defmodule Example.Router do
  use Plug.Router

  plug :match
  plug :dispatch

  get "/" do
    send_resp(conn, 200, "Welcome")
  end

  get "/start" do
    send_resp(conn, 200, "here is start page!")
  end

  get "/hello" do
    send_resp(conn, 200, "hello world!")
  end

  get "/api" do
    send_resp(conn, 200, "need to upforward websocket request to http://127.0.0.1:8080")
  end

  match _ do
    send_resp(conn, 404, "Oops!")
  end
end

The resposity of the project is https://github.com/hrzyang/elixir_plug_cowboy_example

I have read the plug_cowboy document of WebSocket support, but I just don't understand the meaning. Read it or may bring some help with you !

0

There are 0 best solutions below