0

I do have a scenario where I will want my websocket route and get route paths to be the same. Is it possible in Akka Http? Consider the below mentioned code:

def flow: Flow[Message, Message, Any] =
      Flow.fromSinkAndSource(Sink.ignore,     
         Source.single(TextMessage.Strict("Hello from websocket")))

val route =
  path("hello") {
    get {
      complete(HttpEntity(ContentTypes.`application/json`,"Simple hello"))
    }
  } ~ path("hello") {
    handleWebSocketMessages(flow)
  }

If, through a websocket client, I access ws://localhost:8080/hello, I get an websocket error. But a normal curl request gives the result of Simple hello. Is it possible to somehow achieve both actions on same route.

1 Answers1

1

Something along the lines of the below should do

val route = path("hello") {
  optionalHeaderValueByType[UpgradeToWebSocket](()) {
    case Some(upgrade) => complete(upgrade.handleMessages(flow))
    case None => get {
      complete("Simple hello")
    }
  }
}
Stefano Bonetti
  • 8,973
  • 1
  • 25
  • 44