ambiorix icon indicating copy to clipboard operation
ambiorix copied to clipboard

auto-strip trailing slash in request endpoints?

Open kennedymwavu opened this issue 11 months ago • 4 comments

description

say you have a handler for /about. currently when a request is sent to /about/, you get a 404. should we automatically strip any trailing slashes in request endpoints which aren't /?

reprex

library(ambiorix)
library(htmltools)

home_get <- \(req, res) {
  html <- tags$h3("hello, world!")
  res$send(html)
}

about_get <- \(req, res) {
  html <- tags$h3("about page!")
  res$send(html)
}

Ambiorix$
  new()$
  get("/", home_get)$
  get("/about", about_get)$
  start()

hint

we can mutate req$PATH_INFO first thing in the .call() private method of the Routing class as follows:

req$PATH_INFO <- strip_trailing_slash(req$PATH_INFO)

where strip_trailing_slash() is defined as:

#' Strip trailing slash in a given path
#'
#' @param path String. Path.
#' @return String. 
#' @examples
#' strip_trailing_slash("/") # "/"
#' strip_trailing_slash("//") # "/"
#' strip_trailing_slash("/about") # "/about"
#' strip_trailing_slash("/about/") # "/about"
#' strip_trailing_slash("/about//") # "/about"
#' @keywords internal
#' @noRd
strip_trailing_slash <- function(path) {
  while (endsWith(x = path, suffix = "/")) {
    if (identical(path, "/")) {
      return(path)
    }
    path <- substring(text = path, first = 1L, last = nchar(path) - 1L)
  }

  path
}

kennedymwavu avatar Feb 10 '25 12:02 kennedymwavu