【问题标题】:Akka Http return different type of response based on Accept headerAkka Http 根据 Accept 头返回不同类型的响应
【发布时间】:2015-12-16 01:08:41
【问题描述】:

我是 scala 和 Akka-Http 的新手。试验 Akka-Http 来编写休息服务。我必须根据 Accept 标头返回 json 或 protobuf。

 optionalHeaderValueByName("Accept"){ contentType =>
  if(contentType == Some(protoEncode)) {
    complete {
      NewsService.getNewsList().map {
        case stories: List[Story] =>    HttpResponse(entity = HttpEntity(ContentType(protoEncoding),  StoryList(stories).toProto().build().toByteArray))
      }
    }
  } else {
      complete {
        NewsService.getNewsList().map {
          case stories: List[Story] => StoryList(stories)
          }
        }
  }

正如您所见,代码重复正在发生,任何人都可以建议优化和概括设计以避免这种情况的最佳方法。

【问题讨论】:

    标签: scala akka spray akka-http


    【解决方案1】:

    最简单的方法是将支票移动到正文中。

    optionalHeaderValueByName("Accept"){ contentType =>
          complete {
            NewsService.getNewsList().map {
              case stories: List[Story] =>
                if(contentType == Some(protoEncode)) {
                  HttpResponse(entity = HttpEntity(ContentType(protoEncoding),  StoryList(stories).toProto().build().toByteArray))
                } else
                  StoryList(stories)
            }  
          }
      }
    

    【讨论】:

    • 感谢您的回答。您建议的方式通常会起作用。但是,akka-http 完整方法不接受两种不同的返回类型。我已经更新了代码,请检查一下。
    • @user3487990 您应该将其发布为答案,而不是将其编辑到问题中
    【解决方案2】:

    想通了。

    optionalHeaderValueByName("Accept") { contentType =>
       onSuccess(NewsService.getNewsList()) {
           case stories: List[Story] => contentType match {
               case Some(protoEncodingString) => complete(HttpResponse(entity = HttpEntity(ContentType(protoEncoding),  StoryList(stories).toProto().build().toByteArray)))
               case  _=> complete(StoryList(stories))
    
             }
         }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-10
      • 2013-02-07
      • 2010-12-22
      • 1970-01-01
      • 2017-06-28
      相关资源
      最近更新 更多