yihui / servr

A simple HTTP server in R
https://cran.rstudio.com/package=servr
278 stars 35 forks source link

Make httd and httw return the deamon id #34

Closed ColinFay closed 6 years ago

ColinFay commented 6 years ago

Here's the context: I want to be able to programmatically launch and stop a servr.daemon from a shiny app, and for now I'm doing this weird thing to catch the daemon id and close it with a button: (reprex here, of course)

library(shiny)

ui <- fluidPage(
  actionButton("go", "Launch daemon"),
  actionButton("stop", "Stop daemon"), 
  textOutput("srv")
)

server <- function(input, output, session) {
  r <- reactiveValues()
  r$srv <- servr::daemon_list()

  output$srv <- renderText({
    r$srv
    })

  observeEvent(input$go, {
    res <- capture.output(
      servr::httw(tempdir(), daemon = TRUE),
      type = 'message'
    )
    r$last_daemon <-  gsub('.* servr::daemon_stop\\("(.*)"\\) .*', "\\1", res[1])
    r$srv <- servr::daemon_list()
  })

  observeEvent(input$stop, {
    servr::daemon_stop(r$last_daemon)
    r$srv <- servr::daemon_list()
  })
}

shinyApp(ui, server)

So my PR consists of just returning the id of the daemon, so that I can programmatically do :

# remotes::install_github("ColinFay/servr")
res <- servr::httw(tempdir(), daemon = TRUE)
servr::daemon_stop(res)

Which would be cleaner I guess:

library(shiny)

ui <- fluidPage(
  actionButton("go", "Launch daemon"),
  actionButton("stop", "Stop daemon"), 
  textOutput("srv")
)

server <- function(input, output, session) {
  r <- reactiveValues()
  r$srv <- servr::daemon_list()

  output$srv <- renderText({ r$srv })

  observeEvent(input$go, {

    res <- servr::httw(tempdir(), daemon = TRUE)

    r$last_daemon <-  res
    r$srv <- servr::daemon_list()
  })

  observeEvent(input$stop, {
    servr::daemon_stop(r$last_daemon)
    r$srv <- servr::daemon_list()
  })
}

shinyApp(ui, server)
ColinFay commented 6 years ago

Indeed it does. I was convinced (for a reason I can't find back) that id = servr::httd(daemon = TRUE) returned a NULL, hence the weird parsing of the capture.output.

Sorry for the PR, then.

Thanks.

yihui commented 6 years ago

The function = returns the RHS value invisibly: https://yihui.name/en/2017/06/top-level-r-expressions/