Skip to content

Commit

Permalink
serve files
Browse files Browse the repository at this point in the history
  • Loading branch information
hexisdylan committed Jul 23, 2022
1 parent 39956fd commit 0f7f211
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
54 changes: 54 additions & 0 deletions lib/handler.ex
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,49 @@ defmodule Servy.Handler do
%{conv | status: 200, resp_body: "Bear #{id}"}
end

def route(%{method: "GET", path: "/about"} = conv) do
Path.expand(
"../pages",
__DIR__
)
|> Path.join("about.html")
|> File.read!()
|> handle_file(conv)
end

def handle_file({:ok, content}, conv) do
%{conv | status: 200, resp_body: content}
end

def handle_file({:error, :enoent}, conv) do
%{conv | status: 404, resp_body: "File Not Found!"}
end

def handle_file({:error, reason}, conv) do
%{conv | status: 500, resp_body: "File error: #{reason}"}
end

# def route(%{method: "GET", path: "/about"} = conv) do
# file =
# Path.expand(
# "../pages",
# __DIR__
# )
# |> Path.join("about.html")

# case File.read(file) do
# {:ok, content} ->
# %{conv | status: 200, resp_body: content}

# {:error, :enoent} ->
# %{conv | status: 404, resp_body: "File Not Found!"}

# {:error, reason} ->
# %{conv | status: 500, resp_body: "File error: #{reason}"}
# %{conv | status: 200, resp_body: "contents of file"}
# end
# end

def route(%{path: path} = conv) do
%{conv | status: 404, resp_body: "No #{path} here!"}
end
Expand Down Expand Up @@ -119,3 +162,14 @@ Accept: */*

response = Servy.Handler.handle(request)
IO.puts(response)

request = """
GET /about HTTP/1.1
Host: example.com
User-Agent: ExampleBrowser/1.0
Accept: */*
"""

response = Servy.Handler.handle(request)
IO.puts(response)
9 changes: 9 additions & 0 deletions pages/about.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<h1>Clark's Wildthings Refuge</h1>

<blockquote>
When we contemplate the whole globe as one great dewdrop, striped and dotted
with continents and islands, flying through space and dotted with continents
and islands, flying through space with other stars all singing and shining
together as one, the whole universe appears as an infinite storm of beauty. --
John Muir
</blockquote>

0 comments on commit 0f7f211

Please sign in to comment.