Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

akka http custom nested directives

I'm trying to nest existing akka http (version 10) directives to create my own custom directives. I'm having issues with things like this:

def echoHeaderDirective: Directive0 = optionalHeaderValueByName("X-Echo-Header") {
    case Some(value) => respondWithHeader(RawHeader("X-Echo-Header", value))
    case _ => pass
}

The type being returned from the match is Directive0, but I get this error from IDEA

Expression of type Directive0 doesn't conform to expected type Route

and this error from the compiler

type mismatch;
[error]  found   : akka.http.scaladsl.server.Directive0
[error]     (which expands to)  akka.http.scaladsl.server.Directive[Unit]
[error]  required: akka.http.scaladsl.server.RequestContext => scala.concurrent.Future[akka.http.scaladsl.server.RouteResult]
[error]     case Some(value) => respondWithHeader(RawHeader("X-Echo-Header", value))

is it possible to create custom directives in this style (nesting), and if so, what am I doing wrong?

like image 611
kag0 Avatar asked Apr 07 '26 06:04

kag0


1 Answers

What you are doing is essentially applying the Directives by nesting them, as you would do to form your Route. And indeed, the final nesting level is expecting a Route (which is an alias for RequestContext ⇒ Future[RouteResult], as per SBT's complaint).

What you want to do is to transform Directives into other Directives, and to do so you should use map/flatMap functions. Example below:

  def echoHeaderDirective: Directive0 = optionalHeaderValueByName("X-Echo-Header") flatMap {
    case Some(value) => respondWithHeader(RawHeader("X-Echo-Header", value))
    case _ => pass
  }

More info here.

like image 108
Stefano Bonetti Avatar answered Apr 08 '26 21:04

Stefano Bonetti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!