Elixir: Custom Plug Part 2 - [009]

In this episode we will implement the major part of the plug that will help us figure out which kind of audience is accessing our site.

Converting List of Tuples into Map

We need to convert the list of tuples we get from the connection into a map so we can access it as a key-value store.

headers = Enum.into(conn.req_headers, %{})

We can then use this code with the with statement.

Detecting Headless Chrome

We need to detect headless chrome, we can detect headless chrome by looking for the string HeadlessChrome inside ther user agent.

headers["user-agent"] =~ "HeadlessChrome"

That's all we need to check if the request is coming from headless chrome.

Pattern Matching and With Statement

We can use the with statement to call multiple functions and ensure that the output is something we're looking for.

# somewhere in the module@headless_chrome "HeadlessChrome"# in the call functionwith %{"user-agent" => ua} <- Enum.into(conn.req_headers, %{}),      true <- ua =~ @headless_chrome do  :headless_chromeelse  false ->    if Browser.bot?(conn),       do: :bot,      else: :userend

That's all we need in terms of he logic of the code. See the video to see how it all fits together.

In the next episode we will clean up a few things and wrap up our plug.