-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRestRserve.R
52 lines (43 loc) · 1.23 KB
/
RestRserve.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
## An example RestRserve API from https://restrserve.org/
library(RestRserve)
app = Application$new()
app$logger$set_log_level("off") # using tryr's logger
foo <- function(x) {
x <- as.numeric(x)
if (x < 0)
stop("'x' is too low.")
"Success!"
}
bar <- function(x) {
x <- suppressWarnings(as.numeric(x))
if (is.na(x))
tryr::http_error(400L, "Unexpected input.")
foo(x)
}
app$add_post(
path = "/test",
FUN = function(req, res) {
x <- req$parameters_query[["x"]]
out <- foo(x = x)
res$set_content_type("application/json")
res$set_body(out)
})
app$add_post(
path = "/try",
FUN = function(req, res) {
out <- tryr::http_try(req, res, {
x <- req$parameters_query[["x"]]
if (is.null(x))
stop("'x' is missing", call. = FALSE)
bar(x = x)
})
res$set_content_type("application/json")
res$set_body(out)
})
backend = BackendRserve$new()
backend$start(app, http_port = 8000)
# Rscript inst/examples/RestRserve.R
# curl -i -X POST "http://localhost:8000/try?x=0"
# curl -i -X POST "http://localhost:8000/try?x=-1"
# curl -i -X POST "http://localhost:8000/try?x=a"
# curl -i -X POST "http://localhost:8000/try?x="