Debian Codegraph @

R/httpd.R

raw
1 #' Serve a static directory
2 #'
3 #' Serve a directory of files via [new_app()]. If `index.html` exists under the
4 #' directory, it is shown; otherwise a directory listing is shown. This is
5 #' similar to `servr::httd()` and Python's `http.server` module.
6 #' @param dir The directory to serve.
7 #' @param name The app name passed to [new_app()]. Use `''` to serve the
8 #' directory at the root URL via the proxy.
9 #' @param ... Other arguments passed to [new_app()].
10 #' @return The app URL, returned invisibly.
11 #' @export
12 #' @examplesIf interactive()
13 #' xfun::serve_dir(tempdir())
14 serve_dir = function(dir = '.', name = 'xfun-dir', ...) {
15 dir = normalizePath(dir, mustWork = TRUE)
16 handler = function(path, query = NULL, post = NULL, headers = NULL) {
17 in_dir(dir, .resolve_path_to_httpd(path))
18 }
19 new_app(name, handler, ...)
20 }
21
22 # Resolve a request path under the current working directory and return a
23 # neutral intermediate response. This is the shared core used by both
24 # `xfun::serve_dir()` (mapped to R's internal httpd shape) and
25 # `servr:::serve_dir()` (mapped to the httpuv shape). The `action` field is
26 # one of:
27 # 'file' — list(action, path = <abs>, mime)
28 # 'payload' — list(action, body = <text>, mime, status)
29 # 'add-slash' — caller redirects to its own request URL + '/'
30 # '404-redirect' — caller redirects to '/404.html' (if such a file exists)
31 resolve_path = function(path) {
32 if (path == '' || path == '/') path = '.'
33 if (file_test('-d', path)) {
34 # ensure a trailing slash so relative links inside the dir resolve correctly
35 if (path != '.' && !grepl('/$', path)) return(list(action = 'add-slash'))
36 idx = file.path(path, 'index.html')
37 if (file_exists(idx))
38 return(list(action = 'file', path = normalizePath(idx), mime = mime_type(idx)))
39 title = html_escape(path)
40 info = file.info(list.files(path, all.files = TRUE, full.names = TRUE))
41 body = one_string(html_doc(
42 c(sprintf('<h1>Index of %s</h1>', title), fileinfo_table(info)), title
43 ))
44 return(list(action = 'payload', body = body, mime = 'text/html', status = 200L))
45 }
46 if (!file_exists(path)) {
47 # callers may pass the request path with a leading './' (e.g. servr's
48 # serve_dir()), so match on the basename instead of the exact string
49 if (basename(path) == 'favicon.ico') return(list(
50 action = 'file', path = file.path(R.home('doc'), 'html', 'favicon.ico'),
51 mime = 'image/x-icon'
52 ))
53 # redirect to a custom 404.html if it exists and the request looks like a page
54 if (file_exists('404.html') && grepl('(/|[.]html)$', path, ignore.case = TRUE))
55 return(list(action = '404-redirect'))
56 return(list(
57 action = 'payload', body = paste('Not found:', path),
58 mime = 'text/plain', status = 404L
59 ))
60 }
61 list(action = 'file', path = normalizePath(path), mime = mime_type(path))
62 }
63
64 # Map the neutral response to R's internal httpd response shape.
65 .resolve_path_to_httpd = function(path) {
66 r = resolve_path(path)
67 redir = function(dest, status) list(
68 payload = sprintf('Redirect to <a href="%s">%s</a>', dest, dest),
69 `content-type` = 'text/html', header = paste0('Location: ', dest),
70 `status code` = as.integer(status)
71 )
72 switch(
73 r$action,
74 file = list(file = r$path, `content-type` = r$mime),
75 payload = list(payload = r$body, `content-type` = r$mime, `status code` = r$status),
76 `add-slash` = redir(sprintf('%s/', sub('^/?', '/', path)), 301L),
77 `404-redirect` = redir('/404.html', 302L)
78 )
79 }
80
81 # Render a file.info() data frame as an HTML directory listing.
82 fileinfo_table = function(info) {
83 info = info[order(info$isdir, decreasing = TRUE), ]
84 d = info$isdir; i = !is.na(d)
85 x1 = paste0(basename(rownames(info)), ifelse(d & i, '/', ''))
86 x1 = html_escape(x1)
87 x1[i] = sprintf('<a href="%s">%s</a>', x1[i], x1[i])
88 x2 = paste(format(info$size, scientific = FALSE, big.mark = ','), 'B')
89 x2[is.na(info$size) | d] = ''
90 x3 = as.character(info$mtime); x3[is.na(x3)] = ''
91 c('<table>', '<thead><tr>',
92 sprintf('<th>%s</th>', c('Name', 'Size', 'Date Modified')),
93 '</tr></thead>',
94 apply(cbind(
95 '<tr>', sprintf('<td>%s</td>', x1),
96 sprintf('<td align="right">%s</td>', x2),
97 sprintf('<td>%s</td>', x3), '</tr>'
98 ), 1, paste, collapse = ''),
99 '</table>')
100 }
101
102 # Wrap an HTML body in a minimal HTML document with the given title.
103 html_doc = function(body, title = NULL) {
104 c('<!DOCTYPE html>', '<html>',
105 '<head>', sprintf('<title>%s</title>', title), '</head>',
106 '<body>', body, '</body>', '</html>')
107 }