Adding default header for all requests in Unfiltered

302 views Asked by At

We have Unfiltered with underlying Jetty server (not sure but I believe Unfiltered uses Jetty 8). And now we would need to add header entry for all responses we return.

I can get underlying Jetty Server and tried adding Handler directly to it. Not sure if I did some silly mistake or does Unfiltered do something because I managed to add that header, but at same time I removed all other functionality. Not good :)

I also found way to do that in jetty.xml, but didn't get that working.

Now trying to get it working with Cycle.Intent but having some trouble with types when add two of them to Plan.

object AllowOrigin {
  case class AllowOriginResponseFunctionWrapper[A](req: HttpRequest[A], f: ResponseFunction[Any]) extends ResponseFunction[Any] {
    def apply[T](res: HttpResponse[T]) = req match {
      case _ =>
        val resp = f(res)
        resp.header("Access-Control-Allow-Origin", "*")
        resp
    }
  }

  def apply[A](inner: Cycle.Intent[A,Any]): Cycle.Intent[A,Any] = {
    case req @ _ => {
      inner.orElse({ case _ => Pass }: Cycle.Intent[A,Any])(req) match {
        case Pass => Pass
        case responseFunction => AllowOriginResponseFunctionWrapper(req, responseFunction)
      }
    }
  }
}
1

There are 1 answers

0
Jari Kujansuu On

I figured out how to do it without breaking existing functionality. Unfortunately I have to add code to every Plan I have but it is quite small change any way.

First define intent.

object AllowAllOrigin extends unfiltered.kit.Prepend {
  def intent = Cycle.Intent {
    case _ ⇒ ResponseHeader("Access-Control-Allow-Origin", Set("*"))
  }
}

Then add it to intent in plans, if got two things you want to do before Plan specific stuff just add more.

def intent = AllowAllOrigin { Authentication(config) {
  case _ => Ok // or perhaps something more clever here :)
}}