-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.ex
95 lines (75 loc) · 1.75 KB
/
handler.ex
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
defmodule Servy.Handler do
def handle(request) do
request
|> parse
|> log
|> route
|> format_response
end
def parse(request) do
[method, path, _] =
request
|> String.split("\n")
|> List.first()
|> String.split(" ")
%{method: method, path: path, resp_body: "", status: nil}
end
def log(conv), do: IO.inspect(conv)
def route(conv) do
route(conv, conv.method, conv.path)
end
def route(conv, "GET", "/wildthings") do
%{conv | status: 200, resp_body: "Bears, Lions, Tigers"}
end
def route(conv, "GET", "/bears") do
%{conv | status: 200, resp_body: "Teddy, Smokey, Paddington"}
end
def route(conv, "GET", "/bears/" <> id) do
%{conv | status: 200, resp_body: "Bear #{id}"}
end
def route(conv, method, path) do
%{conv | status: 404, resp_body: "No #{path} here!"}
end
def format_response(conv) do
"""
HTTP/1.1 #{conv.status} #{status_reason(conv.status)}
Content-Type: text/html
Content-Length: #{String.length(conv.resp_body)}
#{conv.resp_body}
"""
end
defp status_reason(code) do
%{
200 => "OK",
201 => "Created",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
500 => "Internal Server Error"
}[code]
end
end
request = """
GET /wildthings HTTP/1.1
Host: example.com
User-Agent: ExampleBrowser/1.0
Accept: */*
"""
response = Servy.Handler.handle(request)
IO.puts(response)
request = """
GET /bears HTTP/1.1
Host: example.com
User-Agent: ExampleBrowser/1.0
Accept: */*
"""
response = Servy.Handler.handle(request)
IO.puts(response)
request = """
GET /bears/1 HTTP/1.1
Host: example.com
User-Agent: ExampleBrowser/1.0
Accept: */*
"""
response = Servy.Handler.handle(request)
IO.puts(response)