TitleCrawlerHandler : Stream output.

This commit is contained in:
Dmitry Voronin 2024-09-23 20:27:15 +03:00
parent f2d9fdae9b
commit 194c8b2eed
Signed by: voronind
SSH key fingerprint: SHA256:3kBb4iV2ahufEBNq+vFbUe4QYfHt98DHQjN7QaptY9k

View file

@ -27,20 +27,22 @@ class TitleCrawlerHandler extends HttpHandler, Handler {
// I don't know if this one is ugly, but I wanted to show off a bit. // I don't know if this one is ugly, but I wanted to show off a bit.
extension (exchange: HttpExchange) private def sendResponse(request: Array[Byte]): Unit = { extension (exchange: HttpExchange) private def sendResponse(request: Array[Byte]): Unit = {
exchange.sendResponseHeaders(200, 0)
val reader = new BufferedReader(new InputStreamReader(ByteArrayInputStream(request))) val reader = new BufferedReader(new InputStreamReader(ByteArrayInputStream(request)))
val response = Iterator val output = exchange.getResponseBody
Iterator
.continually(reader.readLine) .continually(reader.readLine)
.takeWhile(null !=) .takeWhile(null !=)
.filter(HttpUtil.isUrl) .filter(HttpUtil.isUrl)
.map({ url => s"$url => ${runCrawler(url)}" }) .map({ url => s"$url => ${runCrawler(url)}\n" })
.mkString("\n") .foreach({ result => {
.getBytes() val bytes = result.getBytes
StreamUtil.copyStream(new ByteArrayInputStream(bytes), System.out)
StreamUtil.copyStream(new ByteArrayInputStream(bytes), output)
output.flush()
}})
exchange.sendResponseHeaders(200, response.length)
val output = exchange.getResponseBody
StreamUtil.copyStream(new ByteArrayInputStream(response), output)
output.close() output.close()
} }