Last active
January 15, 2022 23:46
-
-
Save ktec/ed2303eb167bd54ed1e390cd9371cc41 to your computer and use it in GitHub Desktop.
Example MasterProxy for Elixir Umbrella applications supporting websockets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule MasterProxy.Application do | |
@moduledoc """ | |
Custom Cowboy specification to support hosting multiple Phoenix apps within the same umbrella, | |
all served via the same port. This is only really necessary if you're deploying your umbrella | |
to a restricted hosting environment like Heroku where they only expose 1 port per dyno. | |
Don't for get to configure your endpoints, something like this should work: | |
config :myapp_web, MyAppWeb.Endpoint, | |
url: [scheme: "https", host: "myapp.herokuapp.com", port: 443], | |
force_ssl: [rewrite_on: [:x_forwarded_proto]] | |
""" | |
use Application | |
def start(_type, _args) do | |
import Supervisor.Spec, warn: false | |
port = (System.get_env("PORT") || "4000") |> String.to_integer | |
cowboy = Plug.Adapters.Cowboy.child_spec(:http, MasterProxy.Plug, [], [ | |
port: port, | |
dispatch: [{:_, [phoenix_live_reload(), websocket(), master_proxy()]}] | |
]) | |
children = [ | |
cowboy | |
] | |
opts = [strategy: :one_for_one, name: MasterProxy.Supervisor] | |
Supervisor.start_link(children, opts) | |
end | |
def phoenix_live_reload do | |
{ | |
"/phoenix/live_reload/socket/websocket", | |
Phoenix.Endpoint.CowboyWebSocket, | |
{ | |
Phoenix.Transports.WebSocket, | |
{MyAppWeb.Endpoint, Phoenix.LiveReloader.Socket, :websocket} | |
} | |
} | |
end | |
def websocket do | |
{"/socket/websocket", | |
Phoenix.Endpoint.CowboyWebSocket, | |
{Phoenix.Transports.WebSocket, | |
{MyAppWeb.Endpoint, MyAppWeb.UserSocket, :websocket}} | |
} | |
end | |
def master_proxy do | |
{:_, Plug.Adapters.Cowboy.Handler, {MasterProxy.Plug, []}} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment