问题描述
我正在尝试Akka-http,希望有人可以阐明以下问题:
I'm trying out Akka-http and hopefully someone can shed light on a the following questions:
-
如何一个基于请求中的accept:标头创建不同的路由?例如,我想要一个代码路径来处理 json,一个代码路径来处理 xml请求(如果缺少标头,则默认为 json)
How does one create different routes based on the accept: header in the request? For example, i want one code path to handle "json" and one to handle "xml" requests (with default to "json" if header is missing)
在不希望推断contentType的情况下,如何指定它?例如,在下面的代码中,我尝试通过compactPrint()运行json,但这会将其更改为字符串,因此为 text / plain。我想覆盖它并告诉客户端它仍然是json。
In cases where I don't want the contentType to be inferred, how do i specify it? For example, in the code below I try to run the json through compactPrint() but this changes it to a string, hence "text/plain". I want to override that and tell the client it's still json.
我的代码是这样的;
...
path("api") {
get {
complete {
getStuff.map[ToResponseMarshallable] {
case Right(r) if r.isEmpty => List[String]().toJson.compactPrint
case Right(r) => r.toJson.compactPrint
case Left(e) => BadRequest -> e
}
}
}
}
...
在这种情况下,响应是文本/纯文本,因为compactPrint创建了一个字符串。
的批评非常欢迎。 ;)
The response in this case is text/plain, since compactPrint creates a string.criticism very welcome. ;)
推荐答案
您可以按以下方式定义内容类型,
You can define Content Type as follows,
complete {
HttpResponse(entity = HttpEntity(ContentType(MediaTypes.`application/json`), """{"id":"1"}"""))
}
您可以创建自定义指令,
You can create your custom directive as,
def handleReq(json: String) = {
(get & extract(_.request.acceptedMediaRanges)) {
r =>
val encoding: MediaRange =
r.intersect(myEncodings).headOption
.getOrElse(MediaTypes.`application/json`)
complete {
// check conditions here
// HttpResponse(entity = HttpEntity(encoding.specimen, json)) //
}
}
}
并在路由中使用指令
val route = path("api"){ handleReq(json) }
这篇关于Akka-http:接受和内容类型处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!