Replace upload image page with Kotlin version
[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.Page
4 import net.pterodactylus.util.web.Request
5 import net.pterodactylus.util.web.Response
6 import java.io.File
7
8 /**
9  * [Page] implementation that delivers static files from the filesystem.
10  */
11 class ReloadingPage<R: Request>(private val prefix: String, private val path: String, private val mimeType: String): Page<R> {
12
13         override fun isPrefixPage() = true
14
15         override fun getPath() = prefix
16
17         override fun handleRequest(request: R, response: Response): Response {
18                 val filename = request.uri.path.split("/").last()
19                 File(path, filename).also { file ->
20                         if (file.exists()) {
21                                 response.content.use { output ->
22                                         file.forEachBlock { buffer, bytesRead ->
23                                                 output.write(buffer, 0, bytesRead)
24                                         }
25                                 }
26                                 response.statusCode = 200
27                                 response.contentType = mimeType
28                         } else {
29                                 response.statusCode = 404
30                                 response.statusText = "Not found"
31                         }
32                 }
33                 return response
34         }
35
36 }