R/mw-text.R

Defines functions mw_text

Documented in mw_text

#' Middleware to parse a plain text body
#'
#' Adds the parsed object as the `text` element of the request object.
#'
#' @param default_charset Encoding to set on the text.
#' @param type Content type to match before parsing. If it does not
#'   match, then the request object is not modified.
#' @return Handler function.
#'
#' @family middleware
#' @export
#' @examples
#' app <- new_app()
#' app$use(mw_text())
#' app

mw_text <- function(default_charset = "utf-8",
                     type = "text/plain") {
  default_charset; type
  function(req, res) {
    ct <- req$get_header("Content-Type") %||% ""
    if (! ct %in% tolower(type)) return("next")
    req$text <- rawToChar(req$.body %||% raw())
    Encoding(req$text) <- default_charset
    "next"
  }
}

Try the presser package in your browser

Any scripts or data that you put into this service are public.

presser documentation built on July 1, 2020, 5:49 p.m.