Skip to content

Instantly share code, notes, and snippets.

@programaths
Created March 2, 2017 21:03
Show Gist options
  • Save programaths/d5a6c8b884ac78104d2b5c7d36d81642 to your computer and use it in GitHub Desktop.
Save programaths/d5a6c8b884ac78104d2b5c7d36d81642 to your computer and use it in GitHub Desktop.
This code show a complex stuff done in few lines and 60ms max out of which 20ms come from the origin having hard time serving an HTML file...
import io.netty.buffer.ByteBufInputStream
import io.vertx.core.Vertx
import io.vertx.ext.web.client.WebClient
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
fun main(args: Array<String>) {
val vertx = Vertx.vertx()
val server = vertx.createHttpServer()
val client = WebClient.create(vertx)
server.requestHandler { req ->
client.get(80,"www.programaths.be",req.uri()).send{ get ->
if(get.succeeded()){
with(req.response()){
putHeader("content-type",get.result().getHeader("content-type"))
try {
if(get.result().getHeader("content-type")=="text/html") {
val parsed = Jsoup.parse(ByteBufInputStream(get.result().body().byteBuf), "utf8", "/")
parsed.getElementsByTag("div").append("ho ho ho")
parsed.getElementsByTag("img").forEach(::adjustSrc)
parsed.getElementsByTag("img").forEach(::adjustSrc)
end(parsed.toString())
}else{
end(get.result().body())
}
}catch(e:Exception) {
end("processing error")
}
}
}else{
with(req.response()){
putHeader("content-type","text/plain")
end("sorry")
}
}
}
}
server.listen(8080)
}
fun adjustSrc(el:Element){
if (!el.attr("src").startsWith("http")) {
el.attr("src", "http://www.programaths.be/" + el.attr("src"))
}
}
@programaths
Copy link
Author

It take an HTML document, locate each "div" and append the text "ho ho ho".
It also look at attributes of "script" and "img" tags to prefix them with "http://www.programaths.be/" if they do not start with "http".

So, that's quite heavy processing here, done in 40ms !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment