Last active
June 2, 2016 03:47
-
-
Save Jire/d342f7e7e741058abad5427f4fb6303d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| @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