As a newcomer to both Elixir and the web domain in general (no web framework experience) I would like to know, what is Plug? As I understand it Cowboy is a web server (albeit in Erlang, not Elixir) and Phoenix is a framework for building web apps, but where does Plug come in? Is it an abstraction layer between the two or perhaps a plug-in system in the same abstraction layer as Phoenix?
Elixir is a functional language, so it's no surprise that one of the main building blocks of the request-response cycle is the humble Plug. A Plug will take connection struct (see Plug. Conn) and return a new struct of the same type.
A function plug takes two arguments, the connection and a set of options. Since we don't won't use the options in our function, we can ignore them. Inside our function we'll use Plug's assign function to assign our movie count to the connection. Let's start with a default value of 3 to test it out.
Is it an abstraction layer between the two
Yes, exactly! Plug is meant to be a generic adapter for different web servers. Currently we support just Cowboy but there is work to support others.
Plug also defines how different components should be plugged together. Similar to Rack in Ruby, WSGI in Python, Ring in Clojure, and so on.
Think of plugs as a pipeline of instructions. The intention of plugs is to take in a conn, modify it and then return the modified conn. You can use plugs for tons of things from attaching headers to requests to verifying that a user is authenticated before rendering certain things. In my current project, I am using plugs to handle the construction of my requests as well as handling authentication.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With