How to serve static files in route "/" together with other routes

Viewed 23

I need to serve both static files and endpoints on the same Plumber API server. My idea is:

  • route / will serve static HTML files (like index.html)
  • route /test will execute a R command (like list("TEST API")

My folder contains as follows:

  • a init.R file that starts the Plumber server
  • a api folder that contains endpoints definitions
  • a api/assets folder that contains the static file (in this case index.html)

init.R

library(plumber)

options(plumber.trailingSlash = TRUE)

pr <- Plumber$new()

pr <- pr %>%
  pr_mount("/", plumb("api/assets.R")) %>%
  pr_mount("/test", plumb("api/test.R"))

pr_run(pr, host = "0.0.0.0", port = 8080)

api/assets.R

#* Assets for front end
#* @assets api/assets /
list()

api/test.R

#* Test API
#* @get /
function() {
  list("TEST API")
}

Now, if I query the URL http://localhost:8080 I got the content of the index.html file stored in api/assets folder:

# > curl http://localhost:8080
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  Hello World!
</body>

Instead, if I query locahost:8080/test I got Resource Not Found:

# > curl http://localhost:8080/test
{"error":"404 - Resource Not Found"}

If I remove static mounting, /test works correctly. Is there a way to mounting both static files in / and endpoints in sub-routes?

Thank you, Domi

0 Answers
Related