Form

provides helpers for parsing application/x-www-form-urlencoded and multipart/form-data request bodies.

decode

defn

(Fn [(Ref String a)] (Map String String))

                        (decode body)
                    

decode-multipart

defn

(Fn [(Ref String a), (Ref String b)] (Result (Array FormPart) String))

                        (decode-multipart body boundary)
                    

decodes a multipart/form-data body given the boundary string, via http’s Multipart.parse. Returns (Result (Array FormPart) String); fails when the opening boundary delimiter is absent.

(match (Form.decode-multipart body "boundary123")
  (Result.Success parts) (Array.nth &parts 0)
  (Result.Error _) (Maybe.Nothing))

Each part’s name, optional filename, and optional content-type are extracted from its MIME headers. The body field is the raw content between the part headers and the next boundary delimiter.

decode-multipart-request

defn

(Fn [(Ref Request a)] (Result (Array FormPart) String))

                        (decode-multipart-request req)
                    

decodes the multipart form body of a request, taking the boundary from its Content-Type header, via http’s Request.multipart-data. Returns (Result (Array FormPart) String); fails when the request is not multipart/form-data or carries no boundary.

(defn upload [req params]
  (match (Form.decode-multipart-request req)
    (Result.Success parts)
      (Response.text (fmt "got %d parts" (Array.length &parts)))
    (Result.Error _) (Response.bad-request)))

decode-request

defn

(Fn [(Ref Request a)] (Map String String))

                        (decode-request req)
                    

encode

defn

(Fn [(Ref (Map String String) a)] String)

                        (encode m)
                    

encodes a (Map String String) as a URL-encoded form body. Spaces become + and other special characters are percent-encoded. This is the inverse of parse.

multipart?

defn

(Fn [(Ref Request a)] Bool)

                        (multipart? req)
                    

checks whether a request has a multipart/form-data content type.

parse

defn

(Fn [(Ref String a)] (Result (Map String String) b))

                        (parse s)
                    

parses a URL-encoded form body into a (Map String String).

(let [data (Form.decode (Request.body req))]
  (Map.get &data "username"))

Keys and values are URL-decoded. Duplicate keys keep the last value.

parse-pairs

defn

(Fn [(Ref String a)] (Result (Array (Pair String String)) b))

                        (parse-pairs s)
                    

parses a URL-encoded form body into an (Array (Pair String String)). Unlike parse, this preserves the order of pairs and allows duplicate keys. Keys and values are percent-decoded. The + character is decoded as space.

parse-request

meta-stub

a

parses the form body from a request. Returns an empty map if the content type is not application/x-www-form-urlencoded.