Last active
January 17, 2018 20:24
-
-
Save wch/461ac3ab9233c48445d886035b5b8bdc to your computer and use it in GitHub Desktop.
httpuv application that listens for R commands in background
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This application will listen for local connections on port 7000 and run | |
# commands it receives via HTTP POST. It will run commands using the later | |
# packages -- that is, whenever the R call stack is empty (it is idle at the R | |
# prompt), or whenever later::run_now() is called. Shiny keeps calling run_now() | |
# when running an application, so this can run commands when a Shiny application | |
# is running. | |
# | |
# This can be useful for enabling options while a Shiny application is running. | |
# For example, you can use it to run `options(shiny.trace=TRUE)` without | |
# restarting the application. | |
# | |
# curl -X POST http://localhost:7000/ --data "options(shiny.trace=TRUE)" | |
# wget --quiet -O - http://localhost:7000/ --post-data="options(shiny.trace=TRUE)" | |
# Note that it requires the background-thread branch of httpuv: | |
# devtools::install_github('rstudio/httpuv@background-thread') | |
# Examples of sending R commands via POST with curl or wget: | |
# curl -X POST http://localhost:7000/ --data "a<-1; a+100" | |
# wget --quiet -O - http://localhost:7000/ --post-data="a<-1; a+100" | |
httpuv::startServer("127.0.0.1", 7000, | |
list(call = function(req) { | |
txt <- req$rook.input$read_lines() | |
expr <- parse(text = txt) | |
result_txt <- capture.output({ | |
result <- withVisible(eval(expr, envir = .GlobalEnv)) | |
if (result$visible == TRUE) { | |
print(result$value) | |
} | |
}) | |
result_txt <- paste(result_txt, collapse = "\n") | |
# Print result to R console | |
cat(result_txt, "\n", sep = "") | |
# Return result to client | |
list( | |
status = 200L, | |
headers = list( | |
'Content-Type' = 'text/plain' | |
), | |
body = result_txt | |
) | |
}) | |
) | |
# To stop: | |
httpuv::stopAllServers() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment