| http_server | R Documentation |
Creates a server that can handle HTTP requests and WebSocket connections.
http_server(url, handlers = list(), tls = NULL)
url |
URL to listen on (e.g., "http://127.0.0.1:8080"). |
handlers |
A handler or list of handlers created with |
tls |
TLS configuration for HTTPS/WSS, created via |
This function leverages NNG's shared HTTP server architecture. When both HTTP handlers and WebSocket handlers are provided, they share the same underlying server and port. WebSocket handlers automatically handle the HTTP upgrade handshake and all WebSocket framing (RFC 6455).
WebSocket and streaming callbacks are executed on R's main thread via the
later package. To process callbacks, you must run the event loop
(e.g., using later::run_now() in a loop), or use $serve() which
handles this automatically.
Requires the later package.
A nanoServer object with methods:
$start() - Start accepting connections
$close() - Stop and release all resources
$serve() - Start and block, processing requests via the later
event loop until interrupted (e.g., Ctrl+C). The server is automatically
closed on exit
$url - The server URL
# Simple HTTP server
server <- http_server(
url = "http://127.0.0.1:8080",
handlers = list(
handler("/", function(req) {
list(status = 200L, body = "Hello, World!")
}),
handler("/api/data", function(req) {
list(
status = 200L,
headers = c("Content-Type" = "application/json"),
body = '{"value": 42}'
)
})
)
)
server$start()
# Run event loop: repeat later::run_now(Inf)
server$close()
# HTTP + WebSocket server
server <- http_server(
url = "http://127.0.0.1:8080",
handlers = list(
handler("/", function(req) {
list(status = 200L, body = "<html>...</html>")
}),
handler_ws("/ws", function(ws, data) {
ws$send(data) # Echo
}, textframes = TRUE)
)
)
# Multiple WebSocket endpoints
server <- http_server(
url = "http://127.0.0.1:8080",
handlers = list(
handler_ws("/echo", function(ws, data) ws$send(data)),
handler_ws("/upper", function(ws, data) ws$send(toupper(data)), textframes = TRUE)
)
)
# HTTPS server with self-signed certificate
cert <- write_cert(cn = "127.0.0.1")
cfg <- tls_config(server = cert$server)
server <- http_server(
url = "https://127.0.0.1:8443",
handlers = list(
handler("/", function(req) list(status = 200L, body = "Secure!"))
),
tls = cfg
)
server$start()
# Send async request and run event loop
aio <- ncurl_aio(
"https://127.0.0.1:8443/",
tls = tls_config(client = cert$client),
timeout = 2000
)
while (unresolved(aio)) later::run_now(0.1)
aio$status
aio$data
server$close()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.