Plug.Parsers behaviour
A plug for parsing the request body.
Options
:parsers
- a set of modules to be invoked for parsing. These modules need to implement the behaviour outlined in this module.:accept
- an optional list of accepted mime type strings. Any mime not handled by a parser and not explicitly accepted willraise UnsupportedMediaTypeError
. For example:["*/*"]
- never raises["text/html", "application/*"]
- doesn’t raise for those values[]
- always raises (default)
All options supported by Plug.Conn.read_body/2
are also
supported here.
Examples
plug Plug.Parsers, parsers: [:urlencoded, :multipart]
plug Plug.Parsers, parsers: [:urlencoded, :json],
accept: ["application/json", "text/*"],
json_decoder: Poison
Built-in parsers
Plug ships with the following parsers:
Plug.Parsers.URLENCODED
- parses “application/x-www-form-urlencoded” requestsPlug.Parsers.MULTIPART
- parses “multipart/form-data” and “multipart/mixed” requestsPlug.Parsers.JSON
- parses “application/json” requests with the given :json_decoder
This plug will raise Plug.Parsers.UnsupportedMediaTypeError
by default if
the request cannot be parsed by any of the given types and the mime type has
not been explicity accepted in the :accept
option.
Plug.Parsers.RequestTooLargeError
will be raised if the request goes over
the given limit.
Parsers may raise Plug.Parsers.ParseError
if the request has a malformed
body.
File handling
If a file is uploaded via any of the parsers, Plug will
stream the uploaded contents to a file in a temporary directory,
avoiding loading the whole file into memory. For such, it is
required that the :plug
application is started.
In those cases, the parameter will return a Plug.Upload
struct with information about the file and its content type.
You can customize the temporary directory by setting the PLUG_TMPDIR
environment variable in your system.
Summary
call(conn, opts) | Callback implementation of |
init(opts) | Callback implementation of |
Callbacks
Specs:
- parse(Plug.Conn.t, type :: binary, subtype :: binary, headers :: Keyword.t, opts :: Keyword.t) :: {:ok, Plug.Conn.params, Plug.Conn.t} | {:error, :too_large, Plug.Conn.t} | {:skip, Plug.Conn.t}
Attempt to parse the connection request body given the type,
subtype and headers. Returns {:ok, conn}
if the parser can
handle the given content type, {:halt, conn}
otherwise.