| Title: | A Minimalist Web Framework for R |
|---|---|
| Description: | A minimalist web framework for developing application programming interfaces in R that provides a flexible framework for handling common HTTP-requests, errors, logging, and an ability to integrate any R code as server middle-ware. |
| Authors: | Hans Martin [aut], Jonathan Callahan [aut, cre] |
| Maintainer: | Jonathan Callahan <[email protected]> |
| License: | GPL-3 |
| Version: | 0.4.4 |
| Built: | 2026-05-28 06:12:44 UTC |
| Source: | https://github.com/mazamascience/beakr |
A 'Beakr' object defines a web server instance using the ['httpuv'] package. It provides the main entry point for creating and starting a Beakr application, wrapping a ['Router'] and exposing lifecycle methods.
An ['R6::R6Class'] generator for 'Beakr' objects.
nameApplication name. If 'NULL', a random name is set in '$initialize()'.
routerThe 'Router' instance used to handle requests.
serverThe underlying 'httpuv' server object (once started).
appDefinition()
Build the application definition passed to **httpuv** (request & WS handlers).
Beakr$appDefinition()
new()
Initialize the app: create a 'Router' and assign a random 'name' if missing.
Beakr$new()
start()
Start the HTTP server via **httpuv**.
Beakr$start(host, port, daemon)
hostHostname or IP to bind.
portInteger port to listen on.
daemonIf 'TRUE', run in background with 'httpuv::startServer()'; otherwise run foreground with 'httpuv::runServer()'.
print()
Print a one-line summary (name, state, host, port, #middlewares).
Beakr$print()
clone()
The objects of this class are cloneable with this method.
Beakr$clone(deep = FALSE)
deepWhether to make a deep clone.
[Router], [Middleware], [httpuv::startServer], [httpuv::runServer]
Allow Cross-Origin Resource Sharing headers as described in MDN Web Docs. Cross-origin resource sharing is a mechanism that allows restricted resources on a web page to be requested from another domain(origin) outside the domain from which the first resource was served.
cors( beakr, path = NULL, methods = c("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"), origin = "*", credentials = NULL, headers = NULL, maxAge = NULL, expose = NULL )cors( beakr, path = NULL, methods = c("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"), origin = "*", credentials = NULL, headers = NULL, maxAge = NULL, expose = NULL )
beakr |
|
path |
String representing a path for which to specify a CORS policy.
Default |
methods |
A vector of the request methods to allow. i.e
|
origin |
A vector of the request origin(s) for which resource sharing
is enabled. i.e |
credentials |
A boolean to enable/disable credentialed requests. i.e
|
headers |
A vector of the allowed headers. i.e
|
maxAge |
The max age, in seconds. i.e |
expose |
The headers to expose. i.e |
A Beakr instance with CORS enabled
You can verify that CORS is enabled by using the Chrome browser and
opening up the Developer Tools. The "Network" tab allows you to inspect
response headers and see where the Cross-Origin policy is specified.
If you run the example in the console, be sure to
stopServer(bekar) when you are done.
library(beakr) # Create an new beakr instance beakr <- newBeakr() # beakr pipeline beakr %>% # Enable CORS cors() %>% # Respond to GET requests at the "/hi" route httpGET(path = "/hi", function(req, res, err) { print("Hello, World!") }) %>% # Respond to GET requests at the "/bye" route httpGET(path = "/bye", function(req, res, err) { print("Farewell, my friends.") }) %>% # Start the server on port 25118 listen(host = "127.0.0.1", port = 25118, daemon = TRUE) # ------------------------------------------------------------ # POINT YOUR BROWSER AT: # * http://127.0.0.1:25118/hi # * http://127.0.0.1:25118/bye # # THEN, STOP THE SERVER WITH stopServer(beakr) # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr)library(beakr) # Create an new beakr instance beakr <- newBeakr() # beakr pipeline beakr %>% # Enable CORS cors() %>% # Respond to GET requests at the "/hi" route httpGET(path = "/hi", function(req, res, err) { print("Hello, World!") }) %>% # Respond to GET requests at the "/bye" route httpGET(path = "/bye", function(req, res, err) { print("Farewell, my friends.") }) %>% # Start the server on port 25118 listen(host = "127.0.0.1", port = 25118, daemon = TRUE) # ------------------------------------------------------------ # POINT YOUR BROWSER AT: # * http://127.0.0.1:25118/hi # * http://127.0.0.1:25118/bye # # THEN, STOP THE SERVER WITH stopServer(beakr) # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr)
The decorate() function can be used to prepare a function
for easy use in a beakr pipeline.
Decorating a function associates the specified function and its parameters
with req, res, and err objects and assigns a
content-type to the response object. This prepares a standard R function to
be used in Beakr instances and accept requests.
decorate(FUN, content_type = "text/html", strict = FALSE)decorate(FUN, content_type = "text/html", strict = FALSE)
FUN |
Function to decorate. |
content_type |
HTTP "content-type" of the function output. (e.g. "text/plain", "text/html" or other mime type) |
strict |
Boolean, requiring strict parameter matching. |
A decorated middleware function.
library(beakr) # Create an new Beakr instance beakr <- newBeakr() # Create simple hello and goodbye function hello <- function(name) { paste0("Hello, ", name, "!") } goodbye <- function(text = "Adios") { paste0(text, ", dear friend.") } # Create a web service from these functions beakr %>% httpGET(path = "/hello", decorate(hello)) %>% httpGET(path = "/goodbye", decorate(goodbye)) %>% handleErrors() %>% listen(host = '127.0.0.1', port = 25118, daemon = TRUE) # ------------------------------------------------------------ # POINT YOUR BROWSER AT: # * http://127.0.0.1:25118/hello?name=Honeydew # * http://127.0.0.1:25118/goodbye?text=Sionara # # THEN, STOP THE SERVER WITH stopServer(beakr) # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr)library(beakr) # Create an new Beakr instance beakr <- newBeakr() # Create simple hello and goodbye function hello <- function(name) { paste0("Hello, ", name, "!") } goodbye <- function(text = "Adios") { paste0(text, ", dear friend.") } # Create a web service from these functions beakr %>% httpGET(path = "/hello", decorate(hello)) %>% httpGET(path = "/goodbye", decorate(goodbye)) %>% handleErrors() %>% listen(host = '127.0.0.1', port = 25118, daemon = TRUE) # ------------------------------------------------------------ # POINT YOUR BROWSER AT: # * http://127.0.0.1:25118/hello?name=Honeydew # * http://127.0.0.1:25118/goodbye?text=Sionara # # THEN, STOP THE SERVER WITH stopServer(beakr) # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr)
An 'Error' object tracks and reports errors that occur during request handling or middleware execution in a ['Router']. Errors are collected in a list, and the 'occurred' active binding indicates whether any errors have been set.
An ['R6::R6Class'] generator for 'Error' objects.
errorsCharacter vector of recorded error messages.
occurredLogical; 'TRUE' if any errors have been recorded.
set()
Append an error message to 'errors'.
Error$set(err)
errError message (coerced to character).
clone()
The objects of this class are cloneable with this method.
Error$clone(deep = FALSE)
deepWhether to make a deep clone.
[Middleware], [Router], [handleErrors]
This default error handler should be added
at the end of the beakr pipeline, right before listen(). Errors
generated by any previous step will be returned within a JSON wrapper.
handleErrors(beakr = NULL, FUN = jsonError)handleErrors(beakr = NULL, FUN = jsonError)
beakr |
Beakr instance |
FUN |
a function to handle the error response |
A Beakr instance with added middleware.
If you run the example in the console, be sure to
stopServer(bekar) when you are done.
library(beakr) # Create an new beakr instance beakr <- newBeakr() # beakr pipeline beakr %>% # Respond to GET requests at the "/hi" route httpGET(path = "/hi", function(req, res, err) { print("Hello, World!") }) %>% # Respond to GET requests at the "/bye" route httpGET(path = "/bye", function(req, res, err) { print("Farewell, my friends.") }) %>% handleErrors() %>% # Start the server on port 25118 listen(host = "127.0.0.1", port = 25118, daemon = TRUE) # ------------------------------------------------------------ # POINT YOUR BROWSER AT: # * http://127.0.0.1:25118/NOT_A_ROUTE # # THEN, STOP THE SERVER WITH stopServer(beakr) # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr)library(beakr) # Create an new beakr instance beakr <- newBeakr() # beakr pipeline beakr %>% # Respond to GET requests at the "/hi" route httpGET(path = "/hi", function(req, res, err) { print("Hello, World!") }) %>% # Respond to GET requests at the "/bye" route httpGET(path = "/bye", function(req, res, err) { print("Farewell, my friends.") }) %>% handleErrors() %>% # Start the server on port 25118 listen(host = "127.0.0.1", port = 25118, daemon = TRUE) # ------------------------------------------------------------ # POINT YOUR BROWSER AT: # * http://127.0.0.1:25118/NOT_A_ROUTE # # THEN, STOP THE SERVER WITH stopServer(beakr) # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr)
Routes HTTP DELETE requests to the specified path with the specified callback functions or middleware.
httpDELETE(beakr, path = NULL, FUN = NULL)httpDELETE(beakr, path = NULL, FUN = NULL)
beakr |
|
path |
String representing a path for which the middleware function is invoked. |
FUN |
Middleware function to be invoked. |
A Beakr instance with added middleware.
## Not run: library(beakr) # Create an new Beakr instance beakr <- newBeakr() # Create a simple beakr pipeline beakr %>% httpDELETE("/", function(req, res, err) { return("Successful DELETE request!\n") }) %>% listen(host = '127.0.0.1', port = 25118, daemon = TRUE) # ------------------------------------------------------------ # IN A TERMINAL: # curl -X DELETE http://127.0.0.1:25118/ # > Successful DELETE request! # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr) ## End(Not run)## Not run: library(beakr) # Create an new Beakr instance beakr <- newBeakr() # Create a simple beakr pipeline beakr %>% httpDELETE("/", function(req, res, err) { return("Successful DELETE request!\n") }) %>% listen(host = '127.0.0.1', port = 25118, daemon = TRUE) # ------------------------------------------------------------ # IN A TERMINAL: # curl -X DELETE http://127.0.0.1:25118/ # > Successful DELETE request! # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr) ## End(Not run)
Routes HTTP GET requests to the specified path with the specified callback functions or middleware.
httpGET(beakr, path = NULL, FUN = NULL)httpGET(beakr, path = NULL, FUN = NULL)
beakr |
|
path |
String representing a path for which the middleware function is invoked. |
FUN |
Middleware function to be invoked. |
A Beakr instance with added middleware.
## Not run: library(beakr) # Create an new Beakr instance beakr <- newBeakr() # Create a simple beakr pipeline beakr %>% httpGET("/", function(req, res, err) { return("Successful GET request!\n") }) %>% listen(host = '127.0.0.1', port = 25118, daemon = TRUE) # ------------------------------------------------------------ # IN A TERMINAL: # curl -X GET http://127.0.0.1:25118/ # > Successful GET request! # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr) ## End(Not run)## Not run: library(beakr) # Create an new Beakr instance beakr <- newBeakr() # Create a simple beakr pipeline beakr %>% httpGET("/", function(req, res, err) { return("Successful GET request!\n") }) %>% listen(host = '127.0.0.1', port = 25118, daemon = TRUE) # ------------------------------------------------------------ # IN A TERMINAL: # curl -X GET http://127.0.0.1:25118/ # > Successful GET request! # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr) ## End(Not run)
Routes HTTP POST requests to the specified path with the specified callback functions or middleware.
httpPOST(beakr, path = NULL, FUN = NULL)httpPOST(beakr, path = NULL, FUN = NULL)
beakr |
|
path |
String representing a path for which the middleware function is invoked. |
FUN |
Middleware function to be invoked. |
A Beakr instance with added middleware.
## Not run: library(beakr) # Create an new Beakr instance beakr <- newBeakr() # Create a simple beakr pipeline beakr %>% httpPOST("/", function(req, res, err) { return("Successful POST request!\n") }) %>% listen(host = '127.0.0.1', port = 25118, daemon = TRUE) # ------------------------------------------------------------ # IN A TERMINAL: # curl -X POST http://127.0.0.1:25118/ # > Successful POST request! # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr) ## End(Not run)## Not run: library(beakr) # Create an new Beakr instance beakr <- newBeakr() # Create a simple beakr pipeline beakr %>% httpPOST("/", function(req, res, err) { return("Successful POST request!\n") }) %>% listen(host = '127.0.0.1', port = 25118, daemon = TRUE) # ------------------------------------------------------------ # IN A TERMINAL: # curl -X POST http://127.0.0.1:25118/ # > Successful POST request! # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr) ## End(Not run)
Routes HTTP PUT requests to the specified path with the specified callback functions or middleware.
httpPUT(beakr, path = NULL, FUN = NULL)httpPUT(beakr, path = NULL, FUN = NULL)
beakr |
|
path |
String representing a path for which the middleware function is invoked. |
FUN |
Middleware function to be invoked. |
A Beakr instance with added middleware.
## Not run: library(beakr) # Create an new Beakr instance beakr <- newBeakr() # Create a simple beakr pipeline beakr %>% httpPUT("/", function(req, res, err) { return("Successful PUT request!\n") }) %>% listen(host = '127.0.0.1', port = 25118, daemon = TRUE) # ------------------------------------------------------------ # IN A TERMINAL: # curl -X PUT http://127.0.0.1:25118/ # > Successful PUT request! # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr) ## End(Not run)## Not run: library(beakr) # Create an new Beakr instance beakr <- newBeakr() # Create a simple beakr pipeline beakr %>% httpPUT("/", function(req, res, err) { return("Successful PUT request!\n") }) %>% listen(host = '127.0.0.1', port = 25118, daemon = TRUE) # ------------------------------------------------------------ # IN A TERMINAL: # curl -X PUT http://127.0.0.1:25118/ # > Successful PUT request! # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr) ## End(Not run)
This function is used to add a JSON error response to the
res object. It is called by the handleErrors() utility
function.
jsonError(req, res, err)jsonError(req, res, err)
req |
|
res |
|
err |
|
The incoming res object is modified.
Binds and listens for connections at the specified host and port.
listen( beakr = NULL, host = "127.0.0.1", port = 25118, daemon = FALSE, verbose = FALSE )listen( beakr = NULL, host = "127.0.0.1", port = 25118, daemon = FALSE, verbose = FALSE )
beakr |
|
host |
String that is a valid IPv4 or IPv6 address to listen on. Defaults to the local host ("127.0.0.1"). |
port |
Number or integer that indicates the port to listen on. Default is a port opened on 25118. |
daemon |
Logical specifying whether the server should be run in the background. |
verbose |
Logical specifying whether to print out details of the
|
listen() binds the specified host and port and listens for connections
on a thread. The thread handles incoming requests. when it receives an HTTP
request, it will schedule a call to the user-defined middleware and handle the
request.
If daemon = TRUE, listen() binds the specified port and listens
for connections on a thread running in the background.
See the httpuv package for more details.
A Beakr instance with an active server.
The default port number 25118 was generated using:
> match(c("b","e","a","k","r"), letters) %% 10
[1] 2 5 1 1 8
library(beakr) # Create an new Beakr instance beakr <- newBeakr() # beakr pipeline beakr %>% httpGET("/", function(req, res, err) { return("Successful GET request!\n") }) %>% listen(daemon = TRUE) # run in the background # Stop the server stopServer(beakr)library(beakr) # Create an new Beakr instance beakr <- newBeakr() # beakr pipeline beakr %>% httpGET("/", function(req, res, err) { return("Successful GET request!\n") }) %>% listen(daemon = TRUE) # run in the background # Stop the server stopServer(beakr)
A 'Listener' object represents an event handler within a ['Router']. Each listener pairs an 'event' type (e.g., '"start"', '"error"', '"finish"') with a function 'FUN' to execute when that event is triggered.
An ['R6::R6Class'] generator for 'Listener' objects.
FUNHandler function to execute when 'event' is triggered.
eventEvent name (e.g., '"start"', '"error"', '"finish"').
new()
Construct a listener by setting its 'event' and handler 'FUN'.
Listener$new(event, FUN, ...)
eventEvent name string.
FUNFunction to call when the event occurs.
...Ignored; accepted for flexibility.
clone()
The objects of this class are cloneable with this method.
Listener$clone(deep = FALSE)
deepWhether to make a deep clone.
[Router], [Error]
Lists all Beakr servers currently running (and any other
servers created with the httpuv package). This function is included to
encourage experimentation so that users who create multiple Beakr
instances can quickly find and stop them all.
See httpuv::listServers for details.
listServers()listServers()
None
library(beakr) beakr1 <- newBeakr() beakr2 <- newBeakr() beakr1 %>% listen(daemon = TRUE, port = 1234, verbose = TRUE) beakr2 %>% listen(daemon = TRUE, port = 4321, verbose = TRUE) length(listServers()) stopAllServers() length(listServers())library(beakr) beakr1 <- newBeakr() beakr2 <- newBeakr() beakr1 %>% listen(daemon = TRUE, port = 1234, verbose = TRUE) beakr2 %>% listen(daemon = TRUE, port = 4321, verbose = TRUE) length(listServers()) stopAllServers() length(listServers())
A 'Middleware' object wraps a handler function with associated metadata ('path', 'method', 'protocol'). Middleware functions have access to the request ('req'), response ('res'), and error ('err') objects during the request–response cycle via the ['Router'].
An ['R6::R6Class'] generator for 'Middleware' objects.
pathPath this middleware matches, or 'NULL' for all paths.
FUNHandler function executed when matched.
methodHTTP method to match (e.g., '"GET"'), or 'NULL' for any.
protocolProtocol string: '"http"' or '"websocket"'.
new()
Initialize middleware with handler, path, method, and protocol selection.
Middleware$new(FUN, path, method, websocket)
FUNHandler function (e.g., '(req, res, err)' for HTTP).
pathRoute path to match, or 'NULL' for all.
methodHTTP method to match, or 'NULL' for any.
websocketIf 'TRUE', set 'protocol = "websocket"'; otherwise '"http"'.
clone()
The objects of this class are cloneable with this method.
Middleware$clone(deep = FALSE)
deepWhether to make a deep clone.
[Router], [Request], [Response], [Error]
Create a Beakr instance by calling the top-level
newBeakr() function. If name is not supplied, a random name
will be assigned.
This Beakr instance will then begin a pipeline of separate middleware
steps for routing, serving files and handling errors. The pipeline will
end with the listen() function.
newBeakr(name = NULL)newBeakr(name = NULL)
name |
Optional name assigned to the |
A new and empty Beakr instance.
library(beakr) # Create an new beakr instance beakr <- newBeakr() # beakr pipeline of hanldlers beakr %>% httpGET(path = "/route_A", function(res, req, err) { print("This is route 'A'.") }) %>% httpGET(path = "/route_B", function(res, req, err) { print("This is route 'B'.") }) %>% handleErrors() %>% listen(host = '127.0.0.1', port = 25118, daemon = TRUE) # ------------------------------------------------------------ # POINT YOUR BROWSER AT: # * http://127.0.0.1:25118/route_A # * http://127.0.0.1:25118/route_B # # THEN, STOP THE SERVER WITH stopServer(beakr) # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr)library(beakr) # Create an new beakr instance beakr <- newBeakr() # beakr pipeline of hanldlers beakr %>% httpGET(path = "/route_A", function(res, req, err) { print("This is route 'A'.") }) %>% httpGET(path = "/route_B", function(res, req, err) { print("This is route 'B'.") }) %>% handleErrors() %>% listen(host = '127.0.0.1', port = 25118, daemon = TRUE) # ------------------------------------------------------------ # POINT YOUR BROWSER AT: # * http://127.0.0.1:25118/route_A # * http://127.0.0.1:25118/route_B # # THEN, STOP THE SERVER WITH stopServer(beakr) # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr)
A 'Request' object represents an incoming HTTP request. It stores query string, parameters, body, headers, method, and protocol information. By convention, the request object is named 'req' (with the corresponding response named 'res').
An ['R6::R6Class'] generator for 'Request' objects.
parametersNamed list of route parameters.
headersNamed list of request headers.
pathThe request path.
methodHTTP method (e.g., '"GET"', '"POST"').
rawThe raw request object as received.
typeContent type (e.g., '"text/html"', '"application/json"').
bodyRaw request body as a single string.
protocolProtocol string ('"http"' or '"websocket"').
attach()
Attach a parameter key-value to 'parameters'.
Request$attach(key, value)
keyParameter name.
valueParameter value.
getHeader()
Get the value of a request header.
Request$getHeader(key)
keyHeader name (case-insensitive).
setHeader()
Set or overwrite a request header.
Request$setHeader(key, value)
keyHeader name.
valueHeader value.
addParameters()
Merge a named list of parameters into 'parameters'.
Request$addParameters(named_list)
named_listNamed list of key-value pairs.
new()
Parse fields from the raw request and populate the object.
Request$new(req)
reqRaw request object.
clone()
The objects of this class are cloneable with this method.
Request$clone(deep = FALSE)
deepWhether to make a deep clone.
[Response]
A 'Response' object represents the HTTP response that a 'Beakr' app sends when handling a request. By convention, the response object is named 'res' (with the corresponding request named 'req').
An ['R6::R6Class'] generator for 'Response' objects.
headersA named list of HTTP response headers. Defaults to 'list("Content-Type" = "text/html")'.
statusAn integer HTTP status code. Defaults to '200L'.
bodyThe response body. May be 'NULL', character, raw, JSON, or base64.
setHeader()
Set a header key-value pair (e.g., '"Content-Type" = "text/html"').
Response$setHeader(key, value)
keyHeader name.
valueHeader value.
setContentType()
Set the response 'Content-Type'.
Response$setContentType(type)
typeMIME type string.
setStatus()
Set the HTTP status code.
Response$setStatus(status)
statusInteger HTTP status code.
setBody()
Set the response body, respecting the current 'Content-Type'.
Response$setBody(body)
bodyBody content, type depends on 'Content-Type'.
redirect()
Redirect the client by setting status 302 and 'Location' header.
Response$redirect(url)
urlThe URL to redirect to.
json()
Convert 'txt' to JSON and set content type to '"application/json"'.
Response$json(txt, auto_unbox = TRUE)
txtContent to convert to JSON.
auto_unboxLogical; whether to simplify length-1 vectors.
text()
Set the response body as plain text and content type '"text/html"'.
Response$text(txt)
txtContent to include as plain text.
structured()
Return a structured response depending on 'protocol'.
Response$structured(protocol)
protocol'"http"' or '"websocket"'.
plot()
Render a plot to PNG (optionally base64-encode) and set as response body.
Response$plot(plot_object, base64 = TRUE, ...)
plot_objectA plot object to render.
base64Logical; if 'TRUE', encode image as base64.
...Passed to [graphics::png()].
clone()
The objects of this class are cloneable with this method.
Response$clone(deep = FALSE)
deepWhether to make a deep clone.
[Router], [Request], [Error]
'Router' coordinates HTTP/WebSocket routing and middleware execution. After instantiation, you can register middleware and event listeners; then call '$invoke()' to run the request/response cycle.
An ['R6::R6Class'] generator for 'Router' objects.
middlewareList of middleware entries.
listenersList of listeners (event handlers).
addMiddleware()
Append middleware entry/entries to 'middleware'.
Router$addMiddleware(middleware)
middlewareA middleware object/function or list of them.
addListener()
Append a listener to 'listeners'.
Router$addListener(listener)
listenerA listener object with fields like 'event' and 'FUN'.
processEvent()
Dispatch an event to all matching listeners.
Router$processEvent(event, ...)
eventEvent name (e.g., '"start"', '"error"', '"finish"').
...Additional arguments forwarded to each listener 'FUN'.
invoke()
Run the routing/middleware pipeline and return a structured response.
Router$invoke(req, websocket_msg = NULL, websocket_binary = NULL)
reqRaw request object or 'Request' instance.
websocket_msgOptional WebSocket text message.
websocket_binaryOptional WebSocket binary payload (raw).
clone()
The objects of this class are cloneable with this method.
Router$clone(deep = FALSE)
deepWhether to make a deep clone.
[Response], [Request], [Error]
Binds to GET requests that aren't handled by specified paths.
The result is to return files that are found on the host machine at the
requested path. Binary file types like .png, .gif or
.pdf are returned as raw bytes. All others are returned as characters.
Mime types are guessed using the mime package. The rawTypesPattern
parameter is used to match mime types that should be returned as raw bytes.
serveStaticFiles( beakr = NULL, urlPath = NULL, rootPath = getwd(), rawTypesPattern = "image|json|octet|pdf|video", verbose = FALSE )serveStaticFiles( beakr = NULL, urlPath = NULL, rootPath = getwd(), rawTypesPattern = "image|json|octet|pdf|video", verbose = FALSE )
beakr |
|
urlPath |
String representing the URL directory underneath which static file paths will appear. |
rootPath |
String representing the absolute path used as the root directory when searching for files on host machine. Defaults to the directory in which the script is running. |
rawTypesPattern |
String pattern identifying mime types to be returned as raw bytes. |
verbose |
Boolean to show a verbose static file information. |
All files to be served in this manner must exist underneath the
host machine directory specified with rootPath. The directory
structure underneath rootPath will be mapped onto URLs underneath
urlPath. This helps when deploying web services at preordained URLs.
The example below presents files underneath host machine directory
hostDir/ to be accessed at URLS under test/.
A Beakr instance with added middleware.
If you run the example in the console, be sure to
stopServer(bekar) when you are done.
library(beakr) # Create a .txt file in temp directory hostDir <- tempdir() file <- paste0(hostDir, "/my_file.txt") cat("I am a text file.", file = file) # Create an new beakr instance beakr <- newBeakr() # beakr pipeline beakr %>% # Respond to GET requests at the "/hi" route httpGET(path = "/hi", function(req, res, err) { print("Hello, World!") }) %>% # Respond to GET requests at the "/bye" route httpGET(path = "/bye", function(req, res, err) { print("Farewell, my friends.") }) %>% # Host the directory of static files serveStaticFiles("/test", hostDir, verbose = TRUE) %>% # Start the server on port 25118 listen(host = "127.0.0.1", port = 25118, daemon = TRUE) # ------------------------------------------------------------ # POINT YOUR BROWSER AT: # * http://127.0.0.1:25118/test/my_file.txt # # THEN, STOP THE SERVER WITH stopServer(beakr) # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr)library(beakr) # Create a .txt file in temp directory hostDir <- tempdir() file <- paste0(hostDir, "/my_file.txt") cat("I am a text file.", file = file) # Create an new beakr instance beakr <- newBeakr() # beakr pipeline beakr %>% # Respond to GET requests at the "/hi" route httpGET(path = "/hi", function(req, res, err) { print("Hello, World!") }) %>% # Respond to GET requests at the "/bye" route httpGET(path = "/bye", function(req, res, err) { print("Farewell, my friends.") }) %>% # Host the directory of static files serveStaticFiles("/test", hostDir, verbose = TRUE) %>% # Start the server on port 25118 listen(host = "127.0.0.1", port = 25118, daemon = TRUE) # ------------------------------------------------------------ # POINT YOUR BROWSER AT: # * http://127.0.0.1:25118/test/my_file.txt # # THEN, STOP THE SERVER WITH stopServer(beakr) # ------------------------------------------------------------ # Stop the beakr instance server stopServer(beakr)
Stops all Beakr servers currently running (and any other
servers created with the httpuv package). This function is included to
encourage experimentation so that users who create multiple Beakr
instances can quickly find and stop them all.
See httpuv::stopAllServers for details.
stopAllServers()stopAllServers()
None
library(beakr) beakr1 <- newBeakr() beakr2 <- newBeakr() beakr1 %>% listen(daemon = TRUE, port = 1234, verbose = TRUE) beakr2 %>% listen(daemon = TRUE, port = 4321, verbose = TRUE) length(listServers()) stopAllServers() length(listServers())library(beakr) beakr1 <- newBeakr() beakr2 <- newBeakr() beakr1 %>% listen(daemon = TRUE, port = 1234, verbose = TRUE) beakr2 %>% listen(daemon = TRUE, port = 4321, verbose = TRUE) length(listServers()) stopAllServers() length(listServers())
Stops the server associated with a Beakr instance,
closing all open connections and unbinding the port.
stopServer(beakr = NULL, verbose = FALSE)stopServer(beakr = NULL, verbose = FALSE)
beakr |
|
verbose |
Logical specifying whether to print out details of the
|
None
library(beakr) beakr <- newBeakr() # beakr pipeline beakr %>% handleErrors() %>% listen(daemon = TRUE, verbose = TRUE) stopServer(beakr, verbose = TRUE)library(beakr) beakr <- newBeakr() # beakr pipeline beakr %>% handleErrors() %>% listen(daemon = TRUE, verbose = TRUE) stopServer(beakr, verbose = TRUE)