Akka HTTP 响应 html 具有循环 css 或图像 link 的字符串
Akka HTTP response html string with recurrent css or image link
我正在使用 akka http routes dsl 等在 Scala 上实现一个简单的 web 服务器。我有(例如):
val route = get {
path("test") {
complete((new ViewTemplate).response)
}
}
其中 ViewTemplate 是一个 class,他读取一些 html 模板,向其中注入一些值可能会进行一些转换,并且 returns 作为 HttpResponse...
class ViewTemplate(val filename: String = "test.html") {
import scala.io.Source
private val template = Source.fromResource(filename)
override def toString: String = template.mkString
def entity: ResponseEntity = HttpEntity(ContentTypes.`text/html(UTF-8)`, toString)
def response: HttpResponse = HttpResponse(entity = entity)
}
所有这些工作正常,直到我添加
<link rel="stylesheet" href="style.css"/>
进入test.html的脑袋。浏览器根本忽略这个引用。图像和 a 的东西的情况相同。我想,像 spray of play 这样的东西可以很好地处理这种情况,我正在发明另一辆自行车,但我只是在寻找根源。那你有什么建议吗?
添加一个解释,你所拥有的只是提供生成的模板,它不提供任何其他路径,这意味着当你的浏览器请求“http://yourserver/style.css”时,服务器将回复 404未找到,因为没有为“/style.css”定义路由。
在 Akka HTTP(以及 Spray)中,您必须为您希望 Web 服务器执行的所有操作显式定义路由。但是,您可以定义从请求中提取路径并从文件系统提供相应文件的路由。
您可以在文档的这个页面上看到执行此操作的各种指令:http://doc.akka.io/docs/akka-http/10.0.7/scala/http/routing-dsl/directives/file-and-resource-directives/index.html
请注意,您自己发现的 getFromResourceDirectory
从类路径提供文件,而不是直接从文件系统提供文件,这可能适合也可能不适合您的用例。
我正在使用 akka http routes dsl 等在 Scala 上实现一个简单的 web 服务器。我有(例如):
val route = get {
path("test") {
complete((new ViewTemplate).response)
}
}
其中 ViewTemplate 是一个 class,他读取一些 html 模板,向其中注入一些值可能会进行一些转换,并且 returns 作为 HttpResponse...
class ViewTemplate(val filename: String = "test.html") {
import scala.io.Source
private val template = Source.fromResource(filename)
override def toString: String = template.mkString
def entity: ResponseEntity = HttpEntity(ContentTypes.`text/html(UTF-8)`, toString)
def response: HttpResponse = HttpResponse(entity = entity)
}
所有这些工作正常,直到我添加
<link rel="stylesheet" href="style.css"/>
进入test.html的脑袋。浏览器根本忽略这个引用。图像和 a 的东西的情况相同。我想,像 spray of play 这样的东西可以很好地处理这种情况,我正在发明另一辆自行车,但我只是在寻找根源。那你有什么建议吗?
添加一个解释,你所拥有的只是提供生成的模板,它不提供任何其他路径,这意味着当你的浏览器请求“http://yourserver/style.css”时,服务器将回复 404未找到,因为没有为“/style.css”定义路由。
在 Akka HTTP(以及 Spray)中,您必须为您希望 Web 服务器执行的所有操作显式定义路由。但是,您可以定义从请求中提取路径并从文件系统提供相应文件的路由。
您可以在文档的这个页面上看到执行此操作的各种指令:http://doc.akka.io/docs/akka-http/10.0.7/scala/http/routing-dsl/directives/file-and-resource-directives/index.html
请注意,您自己发现的 getFromResourceDirectory
从类路径提供文件,而不是直接从文件系统提供文件,这可能适合也可能不适合您的用例。