Created
March 2, 2017 21:03
-
-
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...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 !