Status Reasons Code
Here’s the status_reason/1 function.
defp status_reason(code) do
%{
200 => "OK",
201 => "Created",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
500 => "Internal Server Error"
}[code]
endAdvanced Pattern Matching in Elixir
Notes
Exercise: Implement DELETE
How would you define a route that handles a DELETE request? Here’s an example:
request = """
DELETE /bears/1 HTTP/1.1
Host: example.com
User-Agent: ExampleBrowser/1.0
Accept: */*
"""Here’s one possible solution:
def route(conv, "DELETE", "/bears/" <> _id) do
%{ conv | status: 403, resp_body: "Deleting a bear is forbidden!" }
endAlternate Syntax
In the video, we pasted the following status_reason function:
defp status_reason(code) do
%{
200 => "OK",
201 => "Created",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
500 => "Internal Server Error"
}[code]
endThe keys are numbers, not atoms, so we need to use the square-bracket syntax to access the reason associated with the code.
Alternatively, you could use a temporary variable for the map, like so:
defp status_reason(code) do
codes = %{
200 => "OK",
201 => "Created",
401 => "Unauthorized",
403 => "Forbidden",
404 => "Not Found",
500 => "Internal Server Error"
}
codes[code]
endCode So Far
The code for this section is in the params-status directory found within the video-code directory of the code bundle
Why always me?