Scoop API

scoop:scoop.http.server:0.1.0

src/files/static.scoop

Selected production source · src/files/static.scoop

1package scoop.http.server
3import scoop.platform.fs.Path
4import scoop.platform.system.OsString
6/** Maps a terminal wildcard's once-decoded segments onto an application-selected root. */
7public fun staticFiles(root: Path, options: StaticFileOptions = staticFileOptions()): HttpHandler =
8 suspend {
9 ctx ->
10 val parts = ctx.pathParams.tailSegments(options.pathParameter)
11 var path = root
12 var directory = false
13 var index = 0L
14 for (part in parts) {
15 index += 1L
16 if (part.decoded.size == 0L && index == parts.size)
17 directory = true
18 else {
19 if (!validStaticFileName(part.decoded))
20 reject(400U, "invalid static file path segment")
21 path = path.resolve(Path.fromOsString(OsString.fromByteArray(part.decoded)))
22 }
23 }
24 val fallback =
25 if (ctx.request.method == "GET" || ctx.request.method == "HEAD")
26 options.fallbackFile
27 else
28 None
29 val body =
30 HttpBody.File(
31 HttpFileBody(path, options.fileOptions, options.indexDocument, directory, fallback)
32 )
33 httpResult {
34 this.body = body
35 this.allowCompression = false
36 }
37 }
39internal fun validStaticFileName(bytes: Array<Byte>): Boolean {
40 if (bytes.size == 0L)
41 return false
42 if (bytes[0L] == 46 && (bytes.size == 1L || (bytes.size == 2L && bytes[1L] == 46)))
43 return false
44 if (
45 bytes.size >=
46 2L &&
47 bytes[1L] ==
48 58 &&
49 ((bytes[0L] >= 65 && bytes[0L] <= 90) || (bytes[0L] >= 97 && bytes[0L] <= 122))
50 )
51 return false
52 for (value in bytes)
53 if (value == 0 || value == 47 || value == 92)
54 return false
55 return true