-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.exs
89 lines (71 loc) · 1.62 KB
/
server.exs
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
get_pays_request = """
GET /pays HTTP/1.1
Host: server.com
User-Agent: Chrome/1.0
Accept: */*
"""
get_villes_request = """
GET /villes HTTP/1.1
Host: server.com
User-Agent: Chrome/1.0
Accept: */*
"""
non_existing_route_request = """
GET /non_existing_route HTTP/1.1
Host: server.com
User-Agent: Chrome/1.0
Accept: */*
"""
example_of_response = """
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 28
Lomé, Kpalimé, Dapaong, Kara
"""
defmodule Server do
def handle(request) do
request
|> parse()
|> route()
|> format_response()
end
defp parse(request) do
[method, path, _] =
request
|> String.split("\n")
|> List.first()
|> String.split(" ")
%{method: method, path: path, resp_body: "", status: nil}
end
defp route(conv) do
route(conv, conv.method, conv.path)
end
defp route(conv, "GET", "/villes") do
%{ conv | status: 200, resp_body: "Lomé, Kpalimé, Dapaong, Kara" }
end
defp route(conv, "GET", "/pays") do
%{ conv | status: 200, resp_body: "Togo, Benin, Ghana, Senegal" }
end
defp route(conv, _method, path) do
%{ conv | status: 404, resp_body: "La page #{path} n'existe pas!"}
end
defp 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
responses = %{
200 => "OK",
201 => "Created",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
500 => "Internal Server Error"
}
responses[code]
end
end