I have an finch (0.11.1) application running on my local machine and if I do
curl -XPOST localhost:8081/lfdjalfjla // some non-existing url
I get a 404 response with an empty response body. Say I want to give a certain error message as a response, where would I configure that? I did not find an answer in the user guide (yet).
I think the reasonable way to implement that is to apply a Finagle filter on top a service returned from the .toServiceAs
call.
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
}
}
}
And then.
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)
Finally some testing with 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