Created
August 5, 2019 22:50
-
-
Save johndrummond/7722272994efa5b939eda5fbfbd50b3e to your computer and use it in GitHub Desktop.
sample shiny router app returning json but wrapped in websocket and html
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 was an attempt to return json on /health/ with shiny.router | |
# https://appsilon.com/shiny-router-package/ | |
# trying https://stackoverflow.com/users/7268834/slavakx 's suggestion | |
# https://stackoverflow.com/questions/19991654/shiny-server-print-json-as-a-result-output | |
# but the json is already wrapped | |
library(shiny) | |
library(shiny.router) | |
library(data.table) | |
library(jsonlite) | |
# This creates UI for each page. | |
page <- function(title, content) { | |
div( | |
shiny::sliderInput("int", "Choose integer:", -10, 10, 1, 1), | |
titlePanel(title), | |
p(content), | |
uiOutput("power_of_input") | |
) | |
} | |
# Part of both sample pages. | |
home_page <- page("Home page", "This is the home page!") | |
side_page <- verbatimTextOutput(outputId="jsonoutput") | |
# Callbacks on the server side for the sample pages | |
home_server <- function(input, output, session) { | |
output$power_of_input <- renderUI({ | |
HTML(paste( | |
"I display <strong>square</strong> of input and pass result to <code>output$power_of_input</code>: ", | |
as.numeric(input$int) ^ 2)) | |
}) | |
} | |
side_server <- function(input, output, session) { | |
output$jsonoutput <- renderText({ | |
#data <- getMainData() | |
data <- data.table(a=1:3, b=sample(letters,3)) | |
result <- jsonlite::prettify(jsonlite::toJSON(data, auto_unbox = TRUE), 4) | |
return(result) | |
}) | |
} | |
# Create routing. We provide routing path, a UI as well as a server-side callback for each page. | |
router <- make_router( | |
route("home", home_page, home_server), | |
route("side", side_page, side_server) | |
) | |
# Create output for our router in main UI of Shiny app. | |
ui <- shinyUI(fluidPage( | |
router_ui() | |
)) | |
# Plug router into Shiny server. | |
server <- shinyServer(function(input, output, session) { | |
router(input, output, session) | |
}) | |
# Run server in a standard way. | |
shinyApp(ui, server) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment