0
我有一個雀我的本地機器上運行(0.11.1)應用程序,如果我做芬奇配置應對非現有的端點
curl -XPOST localhost:8081/lfdjalfjla // some non-existing url
我得到一個空的響應主體404響應。 假設我想給出一個特定的錯誤信息作爲迴應,我會在哪裏配置? 我在user guide(還沒有)找到答案。
我有一個雀我的本地機器上運行(0.11.1)應用程序,如果我做芬奇配置應對非現有的端點
curl -XPOST localhost:8081/lfdjalfjla // some non-existing url
我得到一個空的響應主體404響應。 假設我想給出一個特定的錯誤信息作爲迴應,我會在哪裏配置? 我在user guide(還沒有)找到答案。
我認爲實施該方法的合理方法是在.toServiceAs
調用返回的服務上應用Finagle過濾器。
import com.twitter.finagle.http.{Request, Response, Status}
import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.util.Future
class OnNotFound(rep: Response) extends SimpleFilter[Request, Response] {
def apply(req: Request, s: Service[Request, Response]): Future[Response] = {
s(req).map {
case r if r.status == Status.NotFound => rep
case r => r
}
}
}
然後。
scala> import io.finch._, com.twitter.finagle.http.Status
scala> val e = get("foo") { Ok("bar") }
e: io.finch.Endpoint[String] = GET /foo
scala> val s = new OnNotFound(Response(Status.InternalServerError)).andThen(e.toServiceAs[Text.Plain])
s: com.twitter.finagle.Service[com.twitter.finagle.http.Request,com.twitter.finagle.http.Response] = <function1>
scala> Http.server.serve(":8080", s)
res0: com.twitter.finagle.ListeningServer = Group(/0:0:0:0:0:0:0:0:8080)
最後用HTTPie進行一些測試。
$ http :8080/foo
HTTP/1.1 200 OK
Content-Encoding: gzip
Content-Length: 29
Content-Type: text/plain
Date: Fri, 03 Mar 2017 23:59:34 GMT
bar
$ http :8080/bar
HTTP/1.1 500 Internal Server Error
Content-Length: 0
這看起來很有說服力。謝謝! – Phil