Advanced Pattern Matching

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: */*

"""

Show Answer

Hide Answer

def route(conv, "DELETE", "/bears/" <> _id) do
  %{ conv | status: 403, resp_body: "Deleting a bear is forbidden!"}
end

Alternate 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]
end

The 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]
end

Code So Far

The code for this video is in the params-status directory found within the video-code directory of the code bundle.