Capstone: HTTP server
The second capstone in Elixir is the other end of the networking lesson: a server that listens, reads one HTTP request and writes one response. There is no framework here, which is the point: the request line is a string, the router is a function, and the response is a few lines of text on a socket.
The router
A router maps a path to a status and a body. Pattern matching on the path is the whole table, and the catch-all is the 404:
router.exs
defmodule Router do def response("/hello"), do: {200, "ok"} def response(_path), do: {404, "not found"} end IO.inspect(Router.response("/hello")) IO.inspect(Router.response("/nope"))
elixir router.exs
{200, "ok"}
{404, "not found"}
The tuple is small on purpose: a status and a body are the two things a client needs. A real router adds headers, methods and the query string, but it starts from this function, and a test of the table is a test of the server.
The server
The server asks for a free port, accepts one connection, reads the request, takes the path from the first line and writes the response. A client sends the request and reads the status line:
server.exs
defmodule Router do def response("/hello"), do: {200, "ok"} def response(_path), do: {404, "not found"} end {:ok, listen} = :gen_tcp.listen(0, [:binary, packet: :raw, active: false, reuseaddr: true]) {:ok, port} = :inet.port(listen) spawn(fn -> {:ok, socket} = :gen_tcp.accept(listen) {:ok, request} = :gen_tcp.recv(socket, 0) [request_line | _] = String.split(request, "\r\n") ["GET", path, _version] = String.split(request_line, " ") {status, body} = Router.response(path) IO.puts("request: " <> request_line) response = "HTTP/1.1 #{status} OK\r\ncontent-length: #{byte_size(body)}\r\n\r\n" <> body :gen_tcp.send(socket, response) :gen_tcp.close(socket) end) {:ok, client} = :gen_tcp.connect(~c"127.0.0.1", port, [:binary, active: false]) :gen_tcp.send(client, "GET /hello HTTP/1.1\r\nhost: localhost\r\n\r\n") {:ok, response} = :gen_tcp.recv(client, 0) [status_line | _] = String.split(response, "\r\n") IO.puts("response: " <> status_line) :gen_tcp.close(client) :gen_tcp.close(listen) Process.sleep(20)
elixir server.exs
request: GET /hello HTTP/1.1
response: HTTP/1.1 200 OK
The request arrives as one binary; the split on "\r\n" gives its lines, and the first line is the method, the path and the version separated by spaces. The response is the same shape: a status line, a header with the length and the body. The status text is OK in both branches of this example, which a real server maps from the code.
The request line
GET /hello HTTP/1.1 has three fields, and the pattern ["GET", path, _version] takes the middle one. A method other than GET does not match, and the spawned server would crash; the error tuple lesson shows the shape a router uses to answer 405 instead of crashing.
The response
The response is a binary in the HTTP format: the status line, the headers, an empty line and the body. The content-length is the byte size of the body, not the number of characters, which matters for a body outside ASCII. The binaries lesson shows the byte view, and building strings shows the interpolation used here.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container. The server uses the loopback interface only.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does the router answer for a path it does not know?
Answer
{404, "not found"}
The catch-all clause returns the 404 tuple.
-
Which function accepts one TCP connection?
Answer
:gen_tcp.accept/1
accept waits for a client and returns the connected socket.
-
What is the first line of an HTTP request?
Answer
The method, the path and the version
GET /hello HTTP/1.1 is the request line.
-
What does the
content-lengthheader carry?Answer
The byte size of the body
The client reads exactly that many bytes after the empty line.
-
What does this program print?
defmodule R do def response("/hello"), do: {200, "ok"} def response(_), do: {404, "not found"} end IO.inspect(R.response("/hello"))Answer
{200, "ok"}
The first clause matches the path and returns the ok tuple.
-
What does this program print?
defmodule R do def response("/hello"), do: {200, "ok"} def response(_), do: {404, "not found"} end IO.inspect(R.response("/nope"))Answer
{404, "not found"}
The catch-all clause answers the 404 tuple.
-
What does this program print?
request = "GET /hello HTTP/1.1\r\nhost: localhost\r\n\r\n" [line | _] = String.split(request, "\r\n") IO.puts(line)Answer
GET /hello HTTP/1.1
The split gives the request line first, then the headers and an empty line.
-
What does this program print?
["GET", path, _version] = String.split("GET /hello HTTP/1.1", " ") IO.puts(path)Answer
/hello
The path is the second field of the request line.
-
What does the server do when the request method is not GET?
Answer
The pattern does not match and the server process crashes
The pattern names GET; another method fails the match, which the prose notes a real router handles.
-
Why does the server not print the port?
Answer
The system assigns it, so it changes between runs
Listening on port 0 asks for a free port, which the run assigns.
Автор статьи: Arthur Isaev