gpt4 book ai didi

kotlin - 将路由拆分为多个文件

转载 作者:行者123 更新时间:2023-12-02 09:03:43 24 4
gpt4 key购买 nike

我是 KotlinKtor 的新手,下面的内容在启动时工作正常,现在我需要添加更多 Routes 如何我可以将路由拆分为多个文件吗?

package blog

import org.jetbrains.ktor.netty.*
import org.jetbrains.ktor.routing.*
import org.jetbrains.ktor.application.*
import org.jetbrains.ktor.features.*
import org.jetbrains.ktor.host.*
import org.jetbrains.ktor.http.*
import org.jetbrains.ktor.response.*
import org.jetbrains.ktor.request.* // for recieve
import org.jetbrains.ktor.util.* // for ValuesMap

import org.apache.commons.mail.*

fun Application.module() {
install(DefaultHeaders)
install(CallLogging)
install(Routing) {
get("/") {
call.respondText("""
My Example Blog2
<form action="/contact-us" method="post">
<input name="subject" placeholder="Subject">
<br>
<textarea name="message" placeholder="Your message ..."></textarea>
<br>
<button>Submit</button>
</form>
""", ContentType.Text.Html)
}
post("/contact-us") {
val post = call.receive<ValuesMap>()
SimpleEmail().apply {
setHostName("smtp.gmail.com")
setSmtpPort(465)
setAuthenticator(DefaultAuthenticator("my_alias@gmail.com", "my_gmil_passoword"))
setSSLOnConnect(true)
setFrom("my_alias@gmail.com")
setSubject(post["subject"])
setMsg(post["message"])
addTo("my_alias@gmail.com")
}.send() // will throw email-exception if something is wrong
call.respondRedirect("/contact-us/success")
}
get("/contact-us/success") {
call.respondText("Your message was sent", ContentType.Text.Html)
}
}
}

fun main(args: Array<String>) {
embeddedServer(Netty, 8080, watchPaths = listOf("BlogAppKt"), module = Application::module).start()
}

最佳答案

终于我明白了:

为您需要的函数名称安装路由,例如:

install(Routing) {
contact()
}

创建一个类似 fun Route.contact(){ ..} 的函数来处理必要条件,因此对于我的示例,我创建了以下内容:

fun Route.contact(){
get("/") {
call.respondText("""
My Example Blog 12
<form action="/contact-us" method="post">
<input name="subject" placeholder="Subject">
<br>
<textarea name="message" placeholder="Your message ..."></textarea>
<br>
<button>Submit</button>
</form>
""", ContentType.Text.Html)
}
post("/contact-us") {
val post = call.receive<ValuesMap>() // val userId = registration["userId"]
SimpleEmail().apply {
setHostName("smtp.gmail.com")
setSmtpPort(465)
setAuthenticator(DefaultAuthenticator("my_alias@gmail.com", "my_gmil_passoword"))
setSSLOnConnect(true)
setFrom("my_alias@gmail.com")
setSubject(post["subject"])
setMsg(post["message"])
addTo("my_alias@gmail.com")
}.send() // will throw email-exception if something is wrong
call.respondRedirect("/contact-us/success")
}
get"/contact-us/success") {
call.respondText("Your message was sent", ContentType.Text.Html)
}
}

关于kotlin - 将路由拆分为多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46390023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com