-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.ex
121 lines (94 loc) · 2.27 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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
defmodule Servy.Handler do
def handle(request) do
request
|> parse
|> rewrite_path
|> log
|> route
|> track
|> format_response
end
def track(%{status: 404, path: path} = conv) do
IO.puts("Warning: #{path} is on the loose!")
conv
end
def track(conv), do: conv
def rewrite_path(%{path: "/wildlife"} = conv) do
%{conv | path: "/wildthings"}
end
def rewrite_path(conv), do: conv
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(%{method: "GET", path: "/wildthings"} = conv) do
%{conv | status: 200, resp_body: "Bears, Lions, Tigers"}
end
def route(%{method: "GET", path: "/bears"} = conv) do
%{conv | status: 200, resp_body: "Teddy, Smokey, Paddington"}
end
def route(%{method: "GET", path: "/bears" <> id} = conv) do
%{conv | status: 200, resp_body: "Bear #{id}"}
end
def route(%{path: path} = conv) 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 /bigfoot HTTP/1.1
Host: example.com
User-Agent: ExampleBrowser/1.0
Accept: */*
"""
response = Servy.Handler.handle(request)
IO.puts(response)
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)