简体   繁体   中英

Scala akka-http evaluate headers and continue routing if successful?

I'm new to scala, and I'm trying to figure out how to add to the existing routes we have so that if a certain path is hit, we evaluate the headers by checking for the existence of some values and whether or not they equal some accepted values. If it succeeds, we get some String out of the headers and pass it on, otherwise we should not continue routing and return some failure.

/abc -> don't check headers
/abc/def -> check headers, return 

pathPrefix("abc") {
  path("def") { // want to ADD something here to check headers and send it into someMethod
     get {
       complete(HttpEntity(something.someMethod(someValue)))
     }
  } ~ path("gdi") {
     get { ... etc} 
  }
}

Any ideas or dummy examples would be really helpful. I see some directives here to get stuff from the request, and the header ( https://doc.akka.io/docs/akka-http/10.0.11/scala/http/routing-dsl/directives/header-directives/headerValue.html ), but I don't understand how to chain directives in this way.

If I'm misunderstanding something, please help clarify! Thanks

Use headerValueByName , which looks for a specific header and rejects the request if that header isn't found:

get {
  headerValueByName("MyHeader") { headerVal =>
    complete(HttpEntity(something.someMethod(headerVal)))
  }
}

To validate the header value if it exists:

get {
  headerValueByName("MyHeader") { headerVal =>
    if (isValid(headerVal)) // isValid is a custom method that you provide
      complete(HttpEntity(something.someMethod(headerVal)))
    else
      complete((BadRequest, "The MyHeader value is invalid."))
  }
}

isValid in the above example could look something like:

def isValid(headerValue: String): Boolean = {
  val acceptedValues = Set("burrito", "quesadilla", "taco")
  acceptedValues.contains(headerValue.toLowerCase)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM