Fiery is a flexible and lightweight framework for building web servers in R. It is relatively unopinionated about how you chose to build your server logic and supports many use cases, from serving static files to being used as a base for a model-view-controller based setup.
Install the release from CRAN using
install.packages('fiery')
or get the development version
directly from GitHub using pak
:
# install.packages('pak')
::pak('thomasp85/fiery') pak
Fiery is designed around a clear server life-cycle with events being triggered at specific points during the life-cycle that will call the handlers attached to these events. In addition to the life-cycle events, it is possible to trigger custom events and attach handlers to these as well. Fiery is designed with modularity in mind so that plugins can be developed for different tasks and mixed and matched to suit the specific project.
While the intro might indicate that fiery is difficult to use, this
is not the case. Much of the hard work of handling http requests has
been encapsulated in the reqres
that
fiery uses to handle http requests and responses. Further, A plugin that
will often be used is routr
, which
provides powerful routing of HTTP requests, thus simplifying the server
logic even more.
Following is a very Hello World-ish example of a fiery app
(sans routr
), that showcases some of the different
life-cycle events:
library(fiery)
# Create a New App
<- Fire$new()
app
# Setup the data every time it starts
$on('start', function(server, ...) {
app$set_data('visits', 0)
server$set_data('cycles', 0)
server
})
# Count the number of cycles (internal loops)
$on('cycle-start', function(server, ...) {
app$set_data('cycles', server$get_data('cycles') + 1)
server
})
# Count the number of requests
$on('before-request', function(server, ...) {
app$set_data('visits', server$get_data('visits') + 1)
server
})
# Handle requests
$on('request', function(server, request, ...) {
app<- request$respond()
response $status <- 200L
response$body <- paste0('<h1>This is indeed a test. You are number ', server$get_data('visits'), '</h1>')
response$type <- 'html'
response
})
# Show number of requests in the console
$on('after-request', function(server, ...) {
appmessage(server$get_data('visits'))
flush.console()
})
# Terminate the server after 50 cycles
$on('cycle-end', function(server, ...) {
appif (server$get_data('cycles') > 50) {
message('Ending...')
flush.console()
$extinguish()
server
}
})
# Be polite
$on('end', function(server) {
appmessage('Goodbye')
flush.console()
})
$ignite(showcase = TRUE)
app#> Fire started at <127.0.0.1:8080>
#> Goodbye
In general much of the logic will happen in the request
and message
handlers and you are free to ignore the other
life-cycle events if they are not needed.
Please note that the ‘fiery’ project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.