简体   繁体   English

Scala akka-http评估标头并在成功后继续路由?

[英]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. 我是scala的新手,我试图找出如何添加到现有路由中的方法,以便在命中某个路径时,通过检查某些值的存在以及它们是否存在来评估标头等于一些可接受的值。 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. 如果成功,我们将从标头中获取一些String并将其传递,否则我们不应继续路由并返回一些失败。

/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. 我在这里看到一些指令以从请求中获取内容以及标头( https://doc.akka.io/docs/akka-http/10.0.11/scala/http/routing-dsl/directives/header-directives/ headerValue.html ),但我不了解如何以这种方式链接指令。

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: 使用headerValueByName ,它查找特定的标头,如果找不到该标头,则拒绝该请求:

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: 上例中的isValid可能类似于:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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