HttpChannelInitializer.kt

  1. package com.hexagonkt.http.server.netty

  2. import com.hexagonkt.http.handlers.HttpHandler
  3. import com.hexagonkt.http.server.HttpServerSettings
  4. import io.netty.channel.ChannelInitializer
  5. import io.netty.channel.socket.SocketChannel
  6. import io.netty.handler.codec.http.*
  7. import io.netty.handler.stream.ChunkedWriteHandler
  8. import io.netty.util.concurrent.EventExecutorGroup

  9. internal class HttpChannelInitializer(
  10.     private val handlers: Map<HttpMethod, HttpHandler>,
  11.     private val executorGroup: EventExecutorGroup?,
  12.     private val settings: HttpServerSettings,
  13.     private val keepAliveHandler: Boolean = true,
  14.     private val httpAggregatorHandler: Boolean = true,
  15.     private val chunkedHandler: Boolean = true,
  16.     private val enableWebsockets: Boolean = true,
  17. ) : ChannelInitializer<SocketChannel>() {

  18.     override fun initChannel(channel: SocketChannel) {
  19.         val pipeline = channel.pipeline()

  20.         pipeline.addLast(HttpServerCodec())

  21.         if (keepAliveHandler)
  22.             pipeline.addLast(HttpServerKeepAliveHandler())
  23.         if (httpAggregatorHandler)
  24.             pipeline.addLast(HttpObjectAggregator(Int.MAX_VALUE))
  25.         if (chunkedHandler)
  26.             pipeline.addLast(ChunkedWriteHandler())
  27.         if (settings.zip)
  28.             pipeline.addLast(HttpContentCompressor())

  29.         val nettyServerHandler = NettyServerHandler(handlers, null, enableWebsockets)

  30.         if (executorGroup == null)
  31.             pipeline.addLast(nettyServerHandler)
  32.         else
  33.             pipeline.addLast(executorGroup, nettyServerHandler)
  34.     }
  35. }