rstudio / plumber

Turn your R code into a web API.
https://www.rplumber.io
Other
1.39k stars 256 forks source link

How to server a static bookdown gitbook? #294

Closed shizidushu closed 6 years ago

shizidushu commented 6 years ago

After render a bookdown to a gitbook, I want to server it as an api. Here is the code I try:

#' @get /static
function(res){
  plumber::include_html("/app/docs/bookdown/index.html", res)
}

#' @assets /app/docs/bookdown /static
list()

It doesn't work, nothing in the /app/docs/bookdown was loaded when visit /static

eduardszoecs commented 6 years ago

@shizidushu I use serve_book() from bookdown to serve the book. You might also want to check https://github.com/yihui/servr.

But plumber is for APIs, not to serve html files...

shizidushu commented 6 years ago

Thank you for you reply. I understand plumber was made to create web api. I used to serve bookdown gitbook with shiny server. Now I just want to add plumber's authentication filter to it.

As in the docs https://www.rplumber.io/docs/routing-and-input.html#static-file-handler, it says "Plumber includes a static file server which can be used to host directories of static assets". So I think the bookdown gitbook can be served with plumber. Did I misunderstand?

schloerke commented 6 years ago

With both the plumber route and the static route, they are competing and the plumber route won.

> plumb("~/tmp/petstore/static.R")
# # Plumber router with 1 endpoint, 4 filters, and 1 sub-router.
# # Call run() on this object to start the API.
# ├──[queryString]
# ├──[postBody]
# ├──[cookieParser]
# ├──[sharedSecret]
# └──/static (GET, NULL)

To get around this, I would save the book to disk and only use the static routing. It would handle all of the supporting js/css files that bookdown will require.

If you only have a single, self contained file, keep your #' @get /static and return the computed html result. You will probably need a #' @html tag to display the raw html being returned.

shizidushu commented 6 years ago

So I can't have both plumber route and the static route. Thanks for this information. And I finally get it work with the mount method, here is the sample code:

root <- plumber$new()

api <- plumber$new("~/git/test/plumber.R")
root$mount("/api", api)

root$filter("auth", function(req, res){
  token <- req$HTTP_TOKEN
  if (is.null(token)) {
    res$status <- 401 # 401 UNAUTHORIZED
    list(error = "Authentication Failed; Token is null")
  } else if (token != "abc") {
    res$status <- 401 # 401 UNAUTHORIZED
    list(error = "Token is not Valid")
  } else {
    forward()
  }
})

gitbook <- PlumberStatic$new("~/git/docs/gitbook")

root$mount("/static", gitbook)

root$run()