Skip to content

Instantly share code, notes, and snippets.

@Jire
Last active June 2, 2016 03:47
Show Gist options
  • Save Jire/d342f7e7e741058abad5427f4fb6303d to your computer and use it in GitHub Desktop.
Save Jire/d342f7e7e741058abad5427f4fb6303d to your computer and use it in GitHub Desktop.
@Sharable object HTTPHandler : SimpleChannelInboundHandler<HttpRequest>() {
private val files = Object2ObjectArrayMap<String, ByteBuf>(8)
override fun channelRead0(ctx: ChannelHandlerContext, msg: HttpRequest) {
val uri = msg.uri()
var buffer = files[uri]
if (buffer == null) {
val bytes = Files.readAllBytes(Paths.get(uri))
buffer = ctx.alloc().directBuffer(bytes.size)
buffer.writeBytes(bytes)
files[uri] = buffer
}
ctx.writeAndFlush(buffer!!.retain())
}
}
@Sharable object HTTPInitializer : ChannelInitializer<SocketChannel>() {
override fun initChannel(ch: SocketChannel) {
ch.pipeline().addLast(HttpRequestDecoder()).addLast(HttpResponseEncoder()).addLast(HTTPHandler)
}
}
fun http(port: Int = 80) = ServerBootstrap().group(group).channel(channel).childHandler(HTTPInitializer).bind(port)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment