65 lines
2.0 KiB
Kotlin
65 lines
2.0 KiB
Kotlin
package moe.kageru.kodeshare
|
|
|
|
import io.ktor.application.ApplicationCall
|
|
import io.ktor.application.call
|
|
import io.ktor.http.ContentType
|
|
import io.ktor.http.HttpStatusCode
|
|
import io.ktor.http.content.PartData
|
|
import io.ktor.http.content.forEachPart
|
|
import io.ktor.http.content.streamProvider
|
|
import io.ktor.locations.Location
|
|
import io.ktor.locations.get
|
|
import io.ktor.request.receiveMultipart
|
|
import io.ktor.response.respond
|
|
import io.ktor.response.respondText
|
|
import io.ktor.routing.Routing
|
|
import io.ktor.routing.get
|
|
import io.ktor.routing.post
|
|
import moe.kageru.kodeshare.persistence.PasteDao
|
|
|
|
@ExperimentalStdlibApi
|
|
object Routes {
|
|
fun Routing.createRoutes() {
|
|
get("/") {
|
|
call.respondText("Hello, world!", ContentType.Text.Html)
|
|
}
|
|
post("/") {
|
|
save(call)
|
|
}
|
|
get<PasteRequest> { req ->
|
|
respondGet(call, req)
|
|
}
|
|
}
|
|
}
|
|
|
|
@ExperimentalStdlibApi
|
|
suspend fun save(call: ApplicationCall) {
|
|
call.receiveMultipart().forEachPart { part ->
|
|
when(part) {
|
|
is PartData.FileItem -> {
|
|
Log.info("new file")
|
|
val content = part.streamProvider().use { it.readAllBytes().decodeToString() }
|
|
val id = PasteDao.insert(Paste(content = content, html = null)).id
|
|
call.respond(HttpStatusCode.Created, "$id")
|
|
Log.info("Saving new paste with ID $id")
|
|
}
|
|
is PartData.FormItem -> {
|
|
Log.info("form item")
|
|
}
|
|
is PartData.BinaryItem -> {
|
|
Log.info("binary item")
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
suspend fun respondGet(call: ApplicationCall, req: PasteRequest) {
|
|
val id = req.id
|
|
Log.info("Retrieving paste $id")
|
|
PasteDao.select(id)?.data?.let { paste ->
|
|
call.respondText(paste.html ?: paste.content, ContentType.Text.Html)
|
|
} ?: call.respond(HttpStatusCode.NotFound, "nothing found for id $id")
|
|
}
|
|
|
|
@Location("/{id}")
|
|
data class PasteRequest(val id: Long) |