if (FALSE) { # interactive() && requireNamespace("later", quietly = TRUE)
# 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 = "...")
}),
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()
}
Run the code above in your browser using DataLab