Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Plug, Friend of Web Developers

Plug, Friend of Web Developers

The Elixir programming language developers have focused efforts on de-facto web application library. This presentation covers the Plug specification, using the web server adapters, and composing Plug modules/functions into larger web applications.

Shane Logsdon

January 12, 2016
Tweet

More Decks by Shane Logsdon

Other Decks in Programming

Transcript

  1. What is Plug? • Specification for composable modules • Connection

    adapters • github.com/elixir-lang/plug | hexdocs.pm/plug
  2. Module Plug defmodule JSONHeaderPlug do def init(opts) do opts end

    def call(conn, _opts) do conn |> put_resp_content_type("application/json") end end
  3. Plug’s plugs • Plug.Parsers • Parses request bodies • Plug.Static

    • Serves static files • Plug.Logger • Logs requests via Logger • And more
  4. Plug’s other modules • Plug.Router • Simple HTTP router •

    Plug.Debugger • Displays formatted runtime errors • Plug.Builder • Conveniences for working with pipelines • And more
  5. Plug composition • Plug.Builder.plug/2 • Accumulates plugs + options to

    module attribute • Attribute values seen as pipeline • Plug.Builder.compile/3 • Expands pipeline into quoted terms
  6. Plug composition Module.register_attribute(:plugs, accumulate: true) # [] @plugs {Plug.Logger, [],

    true} # [{Plug.Logger, [], true} | @plugs] @plugs {Plug.Head, [], true} # [{Plug.Head, [], true} | @plugs]
  7. Plug composition case Plug.Logger.call(conn, Plug.Logger.init(opts)) do %Plug.Conn{} = c1 ->

    case Plug.Head.call(c, Plug.Head.init(opts)) do %Plug.Conn{} = c2 -> c2 _ -> :error end _ -> :error end
  8. Connection adapters • Plug.Conn.Adapter • Defines API for Plug to

    receive/send requests/responses via webservers • Adapters: • Cowboy (Plug.Adapters.Cowboy) • Conveniences can be added to adapters, e.g. Plug.Adapters.Cowboy.http/3