2017-06-02 49 views
0

我在Scala上实现一个简单的Web服务器与AKK http路由DSL等。我有(例如):Akka HTTP响应HTML字符串与循环的CSS或图像链接

val route = get { 
    path("test") { 
     complete((new ViewTemplate).response) 
    } 
} 

凡ViewTemplateis类谁读一些HTML模板,一些价值注入它可能使一些转换和收益作为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"/> 

into test.html的头部。浏览器完全忽略了这个参考。与图像和a的东西相同的情况。我想,像游戏喷剂这样的事情处理这种情况很好,我正在发明另一辆自行车,但我只是在寻找根。那么你有什么建议?

+0

这个问题已经关闭。 getFromResourceDirectory(“”)发挥了魔力。 –

回答

1

要添加一个解释,你有什么只有服务生成的模板,它不提供任何其他路径,这意味着当您的浏览器要求“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,你已经找到自己,从classpath提供的文件和文件系统不直接,这可能是可能不适合你的用例。