♻️ Add freenet client interface
[Sone.git] / src / main / kotlin / net / pterodactylus / sone / web / pages / ReloadingPage.kt
1 package net.pterodactylus.sone.web.pages
2
3 import net.pterodactylus.util.web.*
4 import java.io.*
5 import javax.inject.*
6
7 /**
8  * [Page] implementation that delivers static files from the filesystem.
9  */
10 class ReloadingPage<R : Request> @Inject constructor(private val prefix: String, private val path: String, private val mimeType: String) : Page<R> {
11
12         override fun isPrefixPage() = true
13
14         override fun getPath() = prefix
15
16         override fun handleRequest(request: R, response: Response): Response {
17                 val filename = request.uri.path.split("/").last()
18                 File(path, filename).also { file ->
19                         if (file.exists()) {
20                                 response.content.use { output ->
21                                         file.forEachBlock { buffer, bytesRead ->
22                                                 output.write(buffer, 0, bytesRead)
23                                         }
24                                 }
25                                 response.statusCode = 200
26                                 response.contentType = mimeType
27                         } else {
28                                 response.statusCode = 404
29                                 response.statusText = "Not found"
30                         }
31                 }
32                 return response
33         }
34
35 }