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.

033132c341296d7f5e5b41e871178418?s=128

Shane Logsdon

January 12, 2016
Tweet

Transcript

  1. Plug, Friend of Web Developers @shanelogsdon @slogsdon

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

    adapters • github.com/elixir-lang/plug | hexdocs.pm/plug
  3. Function Plug (Plug.Conn.t, Plug.opts) :: Plug.Conn.t plug :my_function_plug plug :my_function_plug,

    opt_a: true
  4. Function Plug def json_header_plug(conn, _opts) do conn |> put_resp_content_type("application/json") end

  5. Module Plug init(Plug.opts) :: Plug.opts call(Plug.Conn.t, Plug.opts) :: Plug.Conn.t plug

    MyModulePlug plug MyModulePlug, opt_a: true
  6. 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
  7. Plug’s plugs • Plug.Parsers • Parses request bodies • Plug.Static

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

    Plug.Debugger • Displays formatted runtime errors • Plug.Builder • Conveniences for working with pipelines • And more
  9. 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
  10. Plug composition plug Plug.Logger plug Plug.Head

  11. Plug composition Module.register_attribute(:plugs, accumulate: true) # [] @plugs {Plug.Logger, [],

    true} # [{Plug.Logger, [], true} | @plugs] @plugs {Plug.Head, [], true} # [{Plug.Head, [], true} | @plugs]
  12. 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
  13. 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
  14. Demo • $ mix new --sup our_app • Plug.Router (Plug.Builder)

    • Plug.Test
  15. Questions?