/__w/shurbej/shurbej/_build/test/cover/ct/shurbej_http_spa.html

1 -module(shurbej_http_spa).
2
3 -export([init/2]).
4
5 %% Catch-all handler: serves index.html for browser navigation,
6 %% returns JSON 404 for API-like requests.
7 init(Req0, State) ->
8 2 case is_browser_navigation(Req0) of
9 true ->
10 1 serve_spa(Req0, State);
11 false ->
12 1 Req = shurbej_http_common:error_response(404, <<"Not found">>, Req0),
13 1 {ok, Req, State}
14 end.
15
16 serve_spa(Req0, State) ->
17 1 case file:read_file(shurbej_http:web_dist_path("index.html")) of
18 {ok, Body} ->
19
:-(
Req = cowboy_req:reply(200,
20 #{<<"content-type">> => <<"text/html; charset=utf-8">>},
21 Body, Req0),
22
:-(
{ok, Req, State};
23 {error, _} ->
24 1 Req = cowboy_req:reply(404,
25 #{<<"content-type">> => <<"text/plain">>},
26 <<"UI not built — run: cd web && npm run build">>, Req0),
27 1 {ok, Req, State}
28 end.
29
30 %% Only serve the SPA for GET requests that accept HTML (browser navigation).
31 is_browser_navigation(Req) ->
32 2 case cowboy_req:method(Req) of
33 <<"GET">> ->
34 1 Accept = cowboy_req:header(<<"accept">>, Req, <<>>),
35 1 binary:match(Accept, <<"text/html">>) =/= nomatch;
36 _ ->
37 1 false
38 end.
Line Hits Source