This class wraps all functionality related to extracting information from a
http request. 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 Request object is initialized from a Rook-compliant object. This will
often be the request object provided by the httpuv framework. While it
shouldn't be needed, the original Rook object is always accessible and can be
modified, though any modifications will not propagate to derived values in
the Request object (e.g. changing the HTTP_HOST element of the Rook
object will not change the host field of the Request object). Because of
this, direct manipulation of the Rook object is generally discouraged.
Value
A Request object (for as.Request()) or a logical indicating whether
the object is a Request (for is.Request())
Initialization
A new 'Request'-object is initialized using the new() method on the
generator:
Usage
req <- Request$new(rook, trust = FALSE) |
See also
Response for handling http responses
Active bindings
trustA logical indicating whether the request is trusted. Mutable
methodA string indicating the request method (in lower case, e.g. 'get', 'put', etc.). Immutable
bodyAn object holding the body of the request. This is an empty string by default and needs to be populated using the
set_body()method (this is often done using a body parser that accesses the Rook$input stream). Immutablebody_rawThe raw content of the request body as a raw vector. No unpacking or parsing has been performed on this, even if the request has been parsed.
sessionThe content of the session cookie. If session cookies has not been activated it will be an empty write-protected list. If session cookies are activated but the request did not contain one it will be an empty list. The content of this field will be send encrypted as part of the response according to the cookie settings in
$session_cookie_settings. This field is reflected in theResponse$sessionfield and using either produces the same resulthas_session_cookieQuery whether the request came with a session cookie Immutable
session_cookie_settingsGet the settings for the session cookie as they were provided during initialisation cookie Immutable
has_keyQuery whether the request was initialised with an encryption key Immutable
compression_limitQuery the compression limit the request was initialized with Immutable
cookiesAccess a named list of all cookies in the request. These have been URI decoded. Immutable
headersAccess a named list of all headers in the request. In order to follow R variable naming standards
-have been substituted with_. Use theget_header()method to lookup based on the correct header name. ImmutablehostReturn the domain of the server given by the "Host" header if
trust == FALSE. Iftrust == truereturns theX-Forwarded-Hostinstead. ImmutableipReturns the remote address of the request if
trust == FALSE. Iftrust == TRUEit will instead return the first value of theX-Forwarded-Forheader. ImmutableipsIf
trust == TRUEit will return the full list of ips in theX-Forwarded-Forheader. Iftrust == FALSEit will return an empty vector. ImmutableprotocolReturns the protocol (e.g. 'http') used for the request. If
trust == TRUEit will use the value of theX-Forwarded-Protoheader. ImmutablerootThe mount point of the application receiving this request. Can be empty if the application is mounted on the server root. Immutable
pathThe part of the url following the root. Defines the local target of the request (independent of where it is mounted). Immutable
urlThe full URL of the request. Immutable
queryThe query string of the request (anything following "?" in the URL) parsed into a named list. The query has been url decoded and "+" has been substituted with space. Multiple queries are expected to be separated by either "&" or "|". Immutable
query_delimThe delimiter used for specifying multiple values in a query. If
NULLthen queries are expected to contain multiple key-value pairs for the same key in order to provide an array, e.g.?arg1=3&arg1=7. If setting it to","","|", or" "then an array can be provided in a single key-value pair, e.g.?arg1=3|7querystringThe unparsed query string of the request, including "?". If no query string exists it will be
""rather than"?"xhrA logical indicating whether the
X-Requested-Withheader equalsXMLHttpRequestthus indicating that the request was performed using JavaScript library such as jQuery. ImmutablesecureA logical indicating whether the request was performed using a secure connection, i.e.
protocol == 'https'. ImmutableoriginThe original object used to create the
Requestobject. Asreqrescurrently only works with rook this will always return the original rook object. Changing this will force the request to reparse itself.responseIf a
Responseobject has been created for this request it is accessible through this field. ImmutablelockedSet the
lockedstatus on the request. This flag does not result in any different behaviour in the request but can be used by frameworks to signal that the request should not be altered in some wayresponse_headersThe list of headers the response is prepopulated with Immutable
otel_spanAn OpenTelemetry span to use as parent for any instrumentation happening during the handling of the request. If otel is not enabled then this will be NULL. The span is populated according to the HTTP Server semantics https://opentelemetry.io/docs/specs/semconv/http/http-spans/#http-server, except for the
http.routeattribute, which must be set by the server implementation, along with a proper name for the span ({method}_{route}). The span is automatically closed when the response is converted to a list, unless asked not to. Immutablestart_timeThe time point the Request was created
durationThe time passed since the request was created
Methods
Method new()
Create a new request from a rook object
Arguments
rookThe rook object to base the request on
trustIs this request trusted blindly. If
TRUEX-Forwarded-*headers will be returned when querying host, ip, and protocolkeyA 32-bit secret key as a hex encoded string or a raw vector to use for
$encode_string()and$decode_string()and by extension to encrypt a session cookie. It must be given to turn on session cookie support. A valid key can be generated usingrandom_key(). NEVER STORE THE KEY IN PLAIN TEXT. Optimalle use the keyring package to store it or set it as an environment variablesession_cookieSettings for the session cookie created using
session_cookie(). Will be ignored ifkeyis not provided to ensure session cookies are properly encryptedcompression_limitThe size threshold in bytes for trying to compress the response body (it is still dependant on content negotiation)
query_delimThe delimiter to split array-type query arguments by
response_headersA list of headers the response should be prepopulated with. All names must be in lower case and all elements must be character vectors. This is not checked but assumed
with_otelA boolean to indicate if otel instrumentation should be initiated with the creation of this request. Set to
FALSEto avoid a span being started as well as metrics being recorded for this request. IfTRUEyou should callrequest$clear()as the last act of your request handling to ensure that the span is closed and that the duration metric is correctly reported.
Method set_body()
Sets the content of the request body. This method should
mainly be used in concert with a body parser that reads the rook$input
stream
Method set_cookies()
Sets the cookies of the request. The cookies are automatically parsed and populated, so this method is mainly available to facilitate cookie signing and encryption
Method accepts()
Given a vector of response content types it returns the
preferred one based on the Accept header.
Method accepts_charsets()
Given a vector of possible character encodings it returns
the preferred one based on the Accept-Charset header.
Method accepts_encoding()
Given a vector of possible content encodings (usually
compression algorithms) it selects the preferred one based on the
Accept-Encoding header. If there is no match it will return "identity"
signaling no compression.
Method accepts_language()
Given a vector of possible content languages it selects the
best one based on the Accept-Language header.
Method is()
Queries whether the body of the request is in a given format
by looking at the Content-Type header. Used for selecting the best
parsing method.
Method parse()
Based on provided parsers it selects the appropriate one by
looking at the Content-Type header and assigns the result to the
request body. A parser is a function accepting a raw vector, and a named
list of additional directives, and returns an R object of any kind (if
the parser knows the input to be plain text, simply wrap it in
rawToChar()). If the body is compressed, it will be decompressed based
on the Content-Encoding header prior to passing it on to the parser.
See parsers for a list of pre-supplied parsers. Parsers are either
supplied in a named list or as named arguments to the parse method. The
names should correspond to mime types or known file extensions. If
autofail = TRUE the response will throw an appropriate abort code if
failing to parse the body. parse() returns TRUE if parsing was
successful and FALSE if not
Method parse_raw()
This is a simpler version of the parse() method. It will
attempt to decompress the body and set the body field to the resulting
raw vector. It is then up to the server to decide how to handle the
payload. It returns TRUE if successful and FALSE otherwise.
Method encode_string()
base64-encode a string. If a key has been provided during
initialisation the string is first encrypted and the final result is a
combination of the encrypted text and the nonce, both base64 encoded and
combined with a "_".
Method decode_string()
base64-decodes a string. If a key has been provided during
initialisation the input is first split by "_" and then the two parts
are base64 decoded and decrypted. Otherwise the input is base64-decoded
as-is. It will always hold that
val == decode_string(encode_string(val)).
Method clear()
Clears the content of the request and, if created, the related response. This method exists only to allow reuse of the request and response object to save a few milliseconds in latency. Use with caution and see e.g. how fiery maintains a poll of request objects
Method forward()
Forward a request to a new url, optionally setting different headers, queries, etc. Uses curl and mirai under the hood and returns a promise
Usage
Request$forward(
url,
query = NULL,
method = NULL,
headers = NULL,
body = NULL,
return = NULL,
...
)Arguments
urlThe url to forward to
queryOptional querystring to append to
url. IfNULLthe query string of the current request will be usedmethodThe HTTP method to use. If
NULLthe method of the current request will be usedheadersA list of headers to add to the headers of the current request. You can remove a header from the current request by setting it to
NULLherebodyThe body to send with the forward. If
NULLthe body of the current request will be usedreturnA function that takes in the fulfilled response object and whose return value is returned by the promise
...ignored
Examples
fake_rook <- fiery::fake_request(
'http://example.com/test?id=34632&question=who+is+hadley',
content = 'This is an elaborate ruse',
headers = list(
Accept = 'application/json; text/*',
Content_Type = 'text/plain'
)
)
req <- Request$new(fake_rook)
# Get full URL
req$url
#> [1] "http://example.com:80/test?id=34632&question=who+is+hadley"
# Get list of query parameters
req$query
#> $id
#> [1] "34632"
#>
#> $question
#> [1] "who is hadley"
#>
# Test if content is text
req$is('txt')
#> [1] TRUE
#> attr(,"pick")
#> [1] 1
# Perform content negotiation for the response
req$accepts(c('html', 'json', 'txt'))
#> [1] "json"
# Cleaning up connections
rm(fake_rook, req)
gc()
#> used (Mb) gc trigger (Mb) max used (Mb)
#> Ncells 1163550 62.2 2284858 122.1 2284858 122.1
#> Vcells 2160099 16.5 8388608 64.0 8387939 64.0
