0

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 !

James Z
  • 12,209
  • 10
  • 24
  • 44
  • Your code has no notion of websockets. The topic is too broad to pretend to have it answered here, you might start with examining how it’s done in [`Phoenix`](https://hexdocs.pm/phoenix/Phoenix.Socket.html). – Aleksei Matiushkin Jan 18 '23 at 05:42
  • There is a reverse proxy for `plug` here: https://github.com/tallarium/reverse_proxy_plug you can use it as starting point – ema Jan 19 '23 at 19:23

0 Answers0