| Response {reqres} | R Documentation |
HTTP Response handling
Description
This class handles all functionality involved in crafting a http response.
Much of the functionality is inspired by the Request class in Express.js, so
the documentation for this will
complement this document. As reqres is build on top of the
Rook specifications
the Response object can be converted to a compliant list object to be
passed on to e.g. the httpuv handler.
Usage
## S3 method for class 'Response'
as.list(x, ...)
is.Response(x)
Arguments
x |
A |
... |
Ignored |
Details
A Response object is always created
as a response to a Request object and contains a reference to the
originating Request object. A Response is always initialized with a
404 Not Found code, an empty string as body and the Content-Type header set
to text/plain. As the Content-Type header is required for httpuv to
function, it will be inferred if missing when converting to a list. If the
body is a raw vector it will be set to application/octet-stream and
otherwise it will be set to text/plain. It is always advised to consciously
set the Content-Type header though. The only exception is when attaching a
standard file where the type is inferred from the file extension
automatically. Unless the body is a raw vector it will automatically be
converted to a character vector and collapsed to a single string with "\n"
separating the individual elements before the Response object is converted
to a list (that is, the body can exist as any type of object up until the
moment where the Response object is converted to a list). To facilitate
communication between different middleware the Response object contains
a data store where information can be stored during the lifetime of the
response.
Value
A rook-compliant list-response (in case of as.list()) or a logical
indicating whether the object is a Response (in case of is.Response())
Initialization
A new 'Response'-object is initialized using the new() method on the
generator:
Usage
res <- Response$new(request)
|
But often it will be provided by the request using the respond() method,
which will provide the response, creating one if it doesn't exist
Usage
res <- request$respond()
|
Arguments
request | The Request object that the Response is responding to |
|
Fields
The following fields are accessible in a Response object:
statusGets or sets the status code of the response. Is initialised with
404LbodySet or get he body of the response. If it is a character vector with a single element named
'file'it will be interpreted as the location of a file. It is better to use thefilefield for creating a response referencing a file as it will automatically set the correct headers.fileSet or get the location of a file that should be used as the body of the response. If the body is not referencing a file (but contains something else) it will return
NULL. TheContent-Typeheader will automatically be inferred from the file extension, if known. If unknown it will defaults toapplication/octet-stream. If the file has no extension it will betext/plain. Existence of the file will be checked.typeGet or sets the
Content-Typeheader of the response based on a file extension or mime-type.requestGet the original
Requestobject that the object is responding to.
Methods
The following methods are available in a Response object:
set_header(name, value)Sets the header given by
name.valuewill be converted to character. A header will be added for each element invalue. Useappend_header()for setting headers without overwriting existing ones.get_header(name)Returns the header(s) given by
nameremove_header(name)Removes all headers given by
namehas_header(name)Test for the existence of any header given by
nameappend_header(name, value)Adds an additional header given by
namewith the value given byvalue. If the header does not exist yet it will be created.set_data(key, value)Adds
valueto the internal data store and stores it withkeyget_data(key)Retrieves the data stored under
keyin the internal data store.remove_data(key)Removes the data stored under
keyin the internal data store.has_data(key)Queries whether the data store has an entry given by
keyattach(file, filename=basename(file), type=NULL)Sets the body to the file given by
fileand marks the response as a download by setting theContent-Dispositiontoattachment; filename=<filename>. Use thetypeargument to overwrite the automatic type inference from the file extension.status_with_text(code)Sets the status to
codeand sets the body to the associated status code description (e.g.Bad Gatewayfor502L)set_cookie(name, value, encode = TRUE, expires = NULL, http_only = NULL, max_age = NULL, path = NULL, secure = NULL, same_site = NULL)Adds the cookie given by
nameto the givenvalue, optionally url encoding it, along with any additional directives. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie for a description of the different directives. If the cookie already exists it will be overwritten. The validity of the directives will automatically be checked.expiresexpects a POSIXct object,http_onlyandsecureexpect a logical,max_ageexpects an integer,patha string, andsame_siteeither"Lax"or"Strict"remove_cookie(name)Removes the cookie named
namefrom the response.has_cookie(name)Queries whether the response contains a cookie named
nameset_links(...)Sets the
Linkheader based on the named arguments passed to.... The names will be used for thereldirective.format(..., autofail = TRUE, compress = TRUE)Based on the formatters passed in through
...content negotiation is performed with request and the preferred formatter is chosen. TheContent-Typeheader is set automatically. Ifcompress = TRUEthecompress()method will be called after formatting. If an error is encountered andautofail = TRUEthe response will be set to500. If a formatter is not found andautofail = TRUEthe response will be set to406. If formatting is successful it will returnTRUE, if not it will returnFALSEcompress(priority = c('gzip', 'deflate', 'br', 'identity'))Based on the provided priority, an encoding is negotiated with the request and applied. The
Content-Encodingheader is set to the chosen compression algorithm.content_length()Calculates the length (in bytes) of the body. This is the number that goes into the
Content-Lengthheader. Note that theContent-Lengthheader is set automatically byhttpuvso this method should only be called if the response size is needed for other reasons.as_list()Converts the object to a list for further processing by a Rook compliant server such as
httpuv. Will setContent-Typeheader if missing and convert a non-raw body to a single character string.
Methods
Public methods
Method new()
Usage
Response$new(request)
Method print()
Usage
Response$print(...)
Method set_header()
Usage
Response$set_header(name, value)
Method get_header()
Usage
Response$get_header(name)
Method remove_header()
Usage
Response$remove_header(name)
Method has_header()
Usage
Response$has_header(name)
Method append_header()
Usage
Response$append_header(name, value)
Method set_data()
Usage
Response$set_data(key, value)
Method get_data()
Usage
Response$get_data(key)
Method remove_data()
Usage
Response$remove_data(key)
Method has_data()
Usage
Response$has_data(key)
Method timestamp()
Usage
Response$timestamp()
Method attach()
Usage
Response$attach(file, filename = basename(file), type = NULL)
Method status_with_text()
Usage
Response$status_with_text(code)
Method set_cookie()
Usage
Response$set_cookie( name, value, encode = TRUE, expires = NULL, http_only = NULL, max_age = NULL, path = NULL, secure = NULL, same_site = NULL )
Method remove_cookie()
Usage
Response$remove_cookie(name)
Method has_cookie()
Usage
Response$has_cookie(name)
Method set_links()
Usage
Response$set_links(...)
Method format()
Usage
Response$format(..., autofail = TRUE, compress = TRUE)
Method compress()
Usage
Response$compress(priority = c("gzip", "deflate", "br", "identity"))Method content_length()
Usage
Response$content_length()
Method as_list()
Usage
Response$as_list()
Method as_message()
Usage
Response$as_message()
Method clone()
The objects of this class are cloneable with this method.
Usage
Response$clone(deep = FALSE)
Arguments
deepWhether to make a deep clone.
See Also
Request for handling http requests
Examples
fake_rook <- fiery::fake_request(
'http://example.com/test?id=34632&question=who+is+hadley',
content = 'This is elaborate ruse',
headers = list(
Accept = 'application/json; text/*',
Content_Type = 'text/plain'
)
)
req <- Request$new(fake_rook)
res <- Response$new(req)
res
# Set the body to the associated status text
res$status_with_text(200L)
res$body
# Infer Content-Type from file extension
res$type <- 'json'
res$type
# Prepare a file for download
res$attach(system.file('DESCRIPTION', package = 'reqres'))
res$type
res$body
res$get_header('Content-Disposition')
# Cleaning up connections
rm(fake_rook, req, res)
gc()