forked from SteffenDE/popcorn_live_view
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.exs
More file actions
75 lines (62 loc) · 1.95 KB
/
Copy pathserver.exs
File metadata and controls
75 lines (62 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
Mix.install([
{:bandit, "~> 1.1"},
{:file_system, "~> 1.0"}
])
defmodule FileWatcher do
def start(dirs) do
spawn(fn ->
{:ok, watcher} = FileSystem.start_link(dirs: dirs)
FileSystem.subscribe(watcher)
loop()
end)
end
defp loop(timer \\ nil) do
receive do
{:file_event, _watcher, {_path, _events}} ->
if timer, do: Process.cancel_timer(timer)
loop(Process.send_after(self(), :cook, 1000))
:cook ->
IO.puts("\n[watcher] change detected, running mix setup...")
System.cmd("mix", ["setup"], into: IO.stream(:stdio, :line), cd: File.cwd!())
loop(nil)
end
end
end
defmodule Router do
use Plug.Router
@static_dir "#{__DIR__}/static"
plug(Plug.Logger)
plug(:add_headers)
plug(Plug.Static, from: @static_dir, at: "/", gzip: true)
plug(:match)
plug(:dispatch)
get "/" do
send_file(conn, 200, "#{@static_dir}/index.html")
end
match _ do
send_file(conn, 200, "#{@static_dir}/index.html")
end
def add_headers(conn, _opts) do
# Match Popcorn's server: require-corp + CORP so the OTP/BEAM wasm worker
# can load under cross-origin isolation. credentialless alone is rejected
# by Safari/WebKit for dedicated module workers.
Plug.Conn.merge_resp_headers(
conn,
[
{"Access-Control-Allow-Origin", "*"},
{"Cache-Control", "public no-cache"},
{"Cross-Origin-Opener-Policy", "same-origin"},
{"Cross-Origin-Embedder-Policy", "require-corp"},
{"Cross-Origin-Resource-Policy", "cross-origin"}
]
)
end
end
{opts, _argv} = OptionParser.parse!(System.argv(), strict: [port: :integer])
FileWatcher.start(["lib"])
bandit = {Bandit, plug: Router, scheme: :http, port: Keyword.get(opts, :port, 4000)}
{:ok, _} = Supervisor.start_link([bandit], strategy: :one_for_one)
# unless running from IEx, sleep idenfinitely so we can serve requests
unless IEx.started?() do
IO.getn("Press enter to exit\n")
end