public final class HttpServerConf extends Object
Each config property can be set by the setter method, for example
httpServer.conf().port( 8080 );
The setters return `this` for method chaining, for example
httpServer.conf() .port( 8080 ) .trafficDump( System.out::print ) ;
The config properties must be set before server start.
ip
,
port
,
maxConnections
,
maxConnectionsPerIp
sslPort
,
sslContext
,
sslEngineConf
supportedMethods
,
xForwardLevel
,
autoGzip
,
autoConditional
,
autoRange
,
autoCacheControl
accessLogger
,
trafficDump
readMinThroughput
,
writeMinThroughput
keepAliveTimeout
, etc.
Constructor and Description |
---|
HttpServerConf()
Create an HttpServerConf with default values.
|
Instance Methods | |
---|---|
HttpServerConf |
ip(InetAddress ip)
IP address the server socket binds to.
|
HttpServerConf |
ip(String ip)
IP address the server socket binds to.
|
HttpServerConf |
port(int... ports)
Ports for plain connections.
|
HttpServerConf |
serverSocketBacklog(int serverSocketBacklog)
Server socket backlog.
|
HttpServerConf |
serverSocketConf(ConsumerX<ServerSocketChannel> action)
Action to configure the server socket.
|
HttpServerConf |
socketConf(ConsumerX<SocketChannel> action)
Action to configure each newly accepted socket.
|
HttpServerConf |
maxConnections(int maxConnections)
Max number of connections.
|
HttpServerConf |
maxConnectionsPerIp(int maxConnectionsPerIp)
Max number of connections per IP.
|
HttpServerConf |
selectorIds(int... selectorIds)
Ids of selectors for this server.
|
HttpServerConf |
sslPort(int... ports)
SSL port numbers.
|
HttpServerConf |
sslContext(SSLContext sslContext)
SSLContext for SSL connections.
|
HttpServerConf |
sslKeyStore(String filePath,
String password)
Set
sslContext using a key store file. |
HttpServerConf |
sslEngineConf(ConsumerX<SSLEngine> action)
Action to configure each SSLEngine.
|
HttpServerConf |
sslHandshakeTimeout(Duration sslHandshakeTimeout)
Timeout for completing the SSL handshake on an SSL connection.
|
HttpServerConf |
supportedMethods(String... methods)
HTTP methods supported by the server.
|
HttpServerConf |
readTimeout(Duration readTimeout)
Timeout for read() when reading a request body.
|
HttpServerConf |
readMinThroughput(long readMinThroughput)
Min throughput (bytes/second) when reading a request body.
|
HttpServerConf |
writeTimeout(Duration writeTimeout)
Timeout for write() when writing a response.
|
HttpServerConf |
writeMinThroughput(long writeMinThroughput)
Min throughput (bytes/second) when writing a response.
|
HttpServerConf |
outboundBufferSize(long outboundBufferSize)
Outbound buffer size.
|
HttpServerConf |
keepAliveTimeout(Duration keepAliveTimeout)
Timeout for keep-alive connections.
|
HttpServerConf |
requestHeadTimeout(Duration requestHeadTimeout)
Timeout for reading a request head.
|
HttpServerConf |
requestHeadFieldMaxLength(int requestHeadFieldMaxLength)
Max length for request uri and any header value in a request.
|
HttpServerConf |
requestHeadTotalMaxLength(int requestHeadTotalMaxLength)
Max length of a request head.
|
HttpServerConf |
requestBodyMaxLength(long requestBodyMaxLength)
Max length of a request body.
|
HttpServerConf |
drainRequestTimeout(Duration drainRequestTimeout)
Timeout for draining the request body before writing a response.
|
HttpServerConf |
closeTimeout(Duration closeTimeout)
Timeout for closing a connection.
|
HttpServerConf |
requestEncodingPolicy(String requestEncodingPolicy)
How to handle request entity Content-Encoding.
|
HttpServerConf |
xForwardLevel(int xForwardLevel)
Expected level of
"X-Forwarded-For" . |
HttpServerConf |
autoGzip(boolean autoGzip)
Whether to compress responses with "gzip" automatically.
|
HttpServerConf |
autoGzipContentTypes(String... contentTypes)
Content types of responses to allow auto gzip.
|
HttpServerConf |
autoGzipMinContentLength(long autoGzipMinContentLength)
Min content length of responses to allow auto gzip.
|
HttpServerConf |
autoConditional(boolean autoConditional)
Whether to handle conditional requests automatically.
|
HttpServerConf |
autoRange(boolean autoRange)
Whether to handle Range requests automatically.
|
HttpServerConf |
autoCacheControl(boolean autoCacheControl)
Whether to set response header "Cache-Control" automatically.
|
HttpServerConf |
accessLogger(Consumer<HttpAccess> accessLogger)
Http Access Logger.
|
HttpServerConf |
accessLogTo(Consumer<CharSequence> out)
Set the
accessLogger as one that writes entries to `out`. |
HttpServerConf |
trafficDump(Consumer<CharSequence> trafficDump)
Where to dump http traffic, for debugging purpose.
|
HttpServerConf |
setProxyDefaults()
Set default values suitable for a proxy.
|
InetAddress |
get_ip() |
List<Integer> |
get_ports() |
ConsumerX<ServerSocketChannel> |
get_serverSocketConf() |
ConsumerX<SocketChannel> |
get_socketConf() |
int |
get_serverSocketBacklog() |
int |
get_maxConnections() |
int |
get_maxConnectionsPerIp() |
int[] |
get_selectorIds() |
List<Integer> |
get_sslPorts() |
SSLContext |
get_sslContext() |
ConsumerX<SSLEngine> |
get_sslEngineConf() |
Duration |
get_sslHandshakeTimeout() |
Set<String> |
get_supportedMethods() |
Duration |
get_readTimeout() |
long |
get_readMinThroughput() |
Duration |
get_writeTimeout() |
long |
get_writeMinThroughput() |
long |
get_outboundBufferSize() |
Duration |
get_keepAliveTimeout() |
Duration |
get_requestHeadTimeout() |
int |
get_requestHeadFieldMaxLength() |
int |
get_requestHeadTotalMaxLength() |
long |
get_requestBodyMaxLength() |
Duration |
get_drainRequestTimeout() |
Duration |
get_closeTimeout() |
String |
get_requestEncodingPolicy() |
int |
get_xForwardLevel() |
boolean |
get_autoGzip() |
Set<String> |
get_autoGzipContentTypes() |
long |
get_autoGzipMinContentLength() |
boolean |
get_autoConditional() |
boolean |
get_autoRange() |
boolean |
get_autoCacheControl() |
Consumer<HttpAccess> |
get_accessLogger() |
Consumer<CharSequence> |
get_trafficDump() |
public HttpServerConf()
public HttpServerConf ip(InetAddress ip)
default: the wildcard address
See also ip(String)
.
public HttpServerConf ip(String ip)
This method is equivalent to ip(InetAddress.getByName(ip))
,
see ip(InetAddress)
.
public HttpServerConf port(int... ports)
default: {8080}
Port 0
means an automatically allocated port.
See sslPort(int...)
for SSL ports.
public HttpServerConf serverSocketBacklog(int serverSocketBacklog)
default: 50
public HttpServerConf serverSocketConf(ConsumerX<ServerSocketChannel> action)
default action:
enable
SO_REUSEADDR
if the OS is not Windows.
This action will be invoked before
ServerSocket.bind()
.
App may want to configure more options on the server socket, e.g.
ConsumerX<ServerSocketChannel> defaultAction = server.conf().get_serverSocketConf(); server.conf().serverSocketConf( defaultAction.then(serverSocketChannel -> { serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 16*1024); }) );
The ServerSocketChannel is in non-blocking model; it must not be changed to blocking mode.
public HttpServerConf socketConf(ConsumerX<SocketChannel> action)
default action:
enable
TCP_NODELAY
App may want to configure more options on each socket, for example
server.conf().socketConf( socketChannel -> { socketChannel.setOption(StandardSocketOptions.TCP_NODELAY, true); ... });
The SocketChannel is in non-blocking model; it must not be changed to blocking mode.
public HttpServerConf maxConnections(int maxConnections)
default:
Integer.MAX_VALUE
If this limit is reached, no new incoming connections are accepted, until some existing connections are closed.
public HttpServerConf maxConnectionsPerIp(int maxConnectionsPerIp)
default:
Integer.MAX_VALUE
For any remote IP, if this limit is reached, no new incoming connections are accepted, until some existing connections are closed.
Note: this limit is only useful if the server is directly connected to clients. If there is a reverse proxy in front of the server, do not set this limit, because it limits the number of connections between the reverse proxy and the server. Instead, configure the reverse proxy to limit connections from clients.
public HttpServerConf selectorIds(int... selectorIds)
default: [0, 1, ... N-1] where N is the number of processors
Conceptually there are infinite number of selectors, each associated with a dedicated thread. A server may choose to use any one or several selectors. Different servers/clients can share selectors or use different selectors.
public HttpServerConf sslPort(int... ports)
default: {} (none)
Plain ports
and SSL ports can overlap;
if a port is specified for both plain and SSL, the same port will server both plain and SSL connections.
server.conf() .port (8080) // for http .sslPort(8080) // for https
Port 0
means an automatically allocated port.
If port 0
is specified for both plain and SSL,
a port is automatically allocated to server both plain and SSL connections.
To forbid plain connections and only accept SSL connections, call
server.conf() .port() // no plain ports .sslPort( SSL_PORT )
public HttpServerConf sslContext(SSLContext sslContext)
default: null
If null
, SSLContext.getDefault()
is used. Typically it requires
system properties javax.net.ssl.keyStore/keyStorePassword
etc,
see JSSE Guide.
See sslKeyStore(String, String)
for a typical way of setting the SSLContext.
See also SslConf
for creating SSLContext.
public HttpServerConf sslKeyStore(String filePath, String password) throws Exception
sslContext
using a key store file.
This is a convenience method, equivalent to
sslContext( new SslConf() .keyStoreFile(filePath) .keyStorePass(password) .createContext() )
See SslConf
for more options.
Exception
public HttpServerConf sslEngineConf(ConsumerX<SSLEngine> action)
default action:
do nothing
Example:
server.conf().sslEngineConf( engine-> { engine.setWantClientAuth(true); });
public HttpServerConf sslHandshakeTimeout(Duration sslHandshakeTimeout)
default: 15 seconds
public HttpServerConf supportedMethods(String... methods)
default: { "GET", "HEAD", "POST", "PUT", "DELETE" }
The server will send a 501 response if the method of an HTTP request is not among the supported.
Note that "CONNECT", "OPTIONS", "TRACE" are standard methods listed in RFC7231, but they are excluded by default since most applications don't expect them.
public HttpServerConf readTimeout(Duration readTimeout)
default: 15 seconds
The request.entity().body().read()
action will fail if
the server does not receive any client data within this timeout.
Note that this timeout is for each read() action, not for reading the entire request body.
See also readMinThroughput
.
public HttpServerConf readMinThroughput(long readMinThroughput)
default: 4*1024 (4KB/s)
The request.entity().body().read()
action will fail if
the throughput is below this limit.
public HttpServerConf writeTimeout(Duration writeTimeout)
default: 15 seconds
If the client refuses to accept server data within this timeout, the response is abandoned, and the connection is closed.
Note that this timeout is for each write() action when writing the response, not for writing the entire response.
See also writeMinThroughput
.
public HttpServerConf writeMinThroughput(long writeMinThroughput)
default: 4*1024 (4KB/s)
If the throughput is below this limit when writing a response, the response is abandoned, and the connection is closed.
public HttpServerConf outboundBufferSize(long outboundBufferSize)
default: 16*1024 (16KB)
The server will attempt to buffer this amount of bytes before write().
public HttpServerConf keepAliveTimeout(Duration keepAliveTimeout)
default: 15 seconds
On a keep-alive connection, after a response is sent, if a new request does not arrive within this timeout, the connection will be closed.
public HttpServerConf requestHeadTimeout(Duration requestHeadTimeout)
default: 15 seconds
If the server cannot read an entire request head within this timeout, the request is abandoned, and the connection is closed.
public HttpServerConf requestHeadFieldMaxLength(int requestHeadFieldMaxLength)
default: 8*1024 (8KB)
See also requestHeadTotalMaxLength
.
public HttpServerConf requestHeadTotalMaxLength(int requestHeadTotalMaxLength)
default: 32*1024 (32KB)
public HttpServerConf requestBodyMaxLength(long requestBodyMaxLength)
default: 1024*1024*1024 (1GB)
0 is a legal value for this limit - the server does not allow request bodies (except empties ones).
public HttpServerConf drainRequestTimeout(Duration drainRequestTimeout)
default: 15 seconds
App may generate a response without reading the entire request body. Unfortunately, most HTTP/1 clients will not read the response before it finishes writing the entire request. Therefore the server must drain the request before writing the response to avoid deadlock. This timeout is for the draining step.
public HttpServerConf closeTimeout(Duration closeTimeout)
default: 5 seconds
Before the server closes a connection,
it sends a TCP FIN to the client, then waits for a FIN from the client,
to make sure the client receives all data of the last response.
This timeout is for that waiting period.
The last response is usually marked with a Connection: close
header,
so a decent client should send a FIN as soon as it finishes reading the response.
public HttpServerConf requestEncodingPolicy(String requestEncodingPolicy)
default: "reject"
Available options are:
entity contentEncoding
.
entity contentEncoding
.entity body
accordingly, e.g. with
GunzipByteSource
.
public HttpServerConf xForwardLevel(int xForwardLevel)
"X-Forwarded-For"
.
default: 0
If the server is directly connected to clients, set this value to 0
.
If there is one reverse proxy (e.g. a load balancer) in between, set this value to 1
.
Higher values are also possible.
The "X-Forwarded-For"
header is added by a proxy to reflect
the IP address of the client. The server is usually more interested in that IP,
instead of the IP of the proxy. If there are multiple proxies, the header may
contain a list of IPs.
However, the "X-Forwarded-For"
header can be easily spoofed by clients,
therefore the server must be careful with it.
If there is one reverse proxy in front of the server that is under our control and trustworthy,
xForwardLevel=1
, the server can trust the last IP in "X-Forwarded-For"
,
and HttpRequest.ip()
returns that IP.
Note that clients must not be able to bypass the reverse proxy, or spoofing still works.
If there is no trusted reverse proxy in front of the server, xForwardLevel=0
"X-Forwarded-For"
will be ignored,
HttpRequest.ip()
returns the remote IP of the HTTP connection.
The "X-Forwarded-Proto"
header is treated the same way,
influencing the value of HttpRequest.isHttps()
.
public HttpServerConf autoGzip(boolean autoGzip)
default: false
When autoGzip
is enabled, if request/response satisfies the following conditions
"TE"
or "Accept-Encoding"
header allows "gzip"
Content-Type
matches
autoGzipContentTypes
Content-Length
>= autoGzipMinContentLength
, or is null(unknown)
Content-Encoding
is null
(i.e. the body is not already encoded)
the response body will be automatically compressed with
"Transfer-Encoding: gzip,chunked"
or
"Content-Encoding: gzip"
.
"TE/Transfer-Encoding"
is preferred over "Accept-Encoding/Content-Encoding"
.
If "Content-Encoding: gzip"
is applied, ".gzip"
will be appended to
"ETag"
of the original response.
For manual gzip by app, see
public HttpServerConf autoGzipContentTypes(String... contentTypes)
default: { "text/*", "image/svg+xml", "application/javascript", "application/json" }
Each argument can be a specific content type, e.g. "text/plain", or a main type with wildcard subtype, e.g. "text/*".
See autoGzip
.
public HttpServerConf autoGzipMinContentLength(long autoGzipMinContentLength)
default: 1024 (1KB)
See autoGzip
.
public HttpServerConf autoConditional(boolean autoConditional)
default: true
When enabled, if the request is GET/HEAD and the response is 200,
the server will handle If-Modified-Since/If-None-Match/If-Unmodified-Since/If-Match
conditional requests, and may respond with 304/412 instead.
Response entity's ETag
and Last-Modified
headers are consulted for this feature.
For If-Range
requests see autoRange
.
public HttpServerConf autoRange(boolean autoRange)
default: true
When enabled, if the request is GET/HEAD with the "Range" header, and the response is 200 without the "Accept_Ranges" header, the server may transform the response to 206 with partial body. The "If-Range" request header is also handled.
App can bypass the default behavior by generating a 206 response by itself, or by setting the "Accept_Ranges" header in a 200 response (e.g. Accept-Ranges: none).
See also RangedByteSource
.
public HttpServerConf autoCacheControl(boolean autoCacheControl)
default: true
When enabled, if the request is GET/HEAD, and the response does not already contain the "Cache-Control" header,
Expires
!=null
,
set response header "Cache-Control: private"
Expires
==null
,
set response header "Cache-Control: private, no-cache"
We add "private"
by default to avoid accidentally leaking private responses.
App can bypass the default behavior by setting the "Cache-Control" header in a response.
public HttpServerConf accessLogger(Consumer<HttpAccess> accessLogger)
default: null
If non-null, HttpAccess
entries will be passed to the logger to be logged.
Example Usage:
server.conf().accessLogger( entry -> System.out.println(entry.toCombinedLogFormat()) );
The server allocates a dedicated thread for the logger; entries will be passed to it in a serialized order. The logger can invoke blocking IO actions. If the logger throws, it is abandoned, and future accesses will not be logged.
See also accessLogTo(Consumer<CharSequence>)
public HttpServerConf accessLogTo(Consumer<CharSequence> out)
accessLogger
as one that writes entries to `out`.
Each HttpAccess entry is converted to
Combined Log Format
and written to `out`.
Example Usage:
server.conf().accessLogTo( System.out::print ); // to a file. also, consider 'logrotate' utility on linux. PrintStream accessLog = new PrintStream(new FileOutputStream("access.log", true), true); server.conf().accessLogTo( accessLog::print );
public HttpServerConf trafficDump(Consumer<CharSequence> trafficDump)
default: null
If non-null, request/response heads will be dumped to it. This feature is mostly enabled during development time.
Example Usage:
server.conf().trafficDump( System.out::print );
public HttpServerConf setProxyDefaults()
HttpServer can be used as an intermediary, e.g. proxy, load balancer,
which mainly forwards requests and responses as-is.
Some HttpServerConf default values may not be appropriate for that purpose.
Use setProxyDefaults()
to set values appropriate for an intermediary.
Calling this method is equivalent to calling
supportedMethods
("GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE");requestEncodingPolicy
("keep");autoGzip
(false);autoConditional
(false);autoRange
(false);autoCacheControl
(false);
public InetAddress get_ip()
public ConsumerX<ServerSocketChannel> get_serverSocketConf()
public ConsumerX<SocketChannel> get_socketConf()
public int get_serverSocketBacklog()
public int get_maxConnections()
public int get_maxConnectionsPerIp()
public int[] get_selectorIds()
public SSLContext get_sslContext()
public Duration get_sslHandshakeTimeout()
public Duration get_readTimeout()
public long get_readMinThroughput()
public Duration get_writeTimeout()
public long get_writeMinThroughput()
public long get_outboundBufferSize()
public Duration get_keepAliveTimeout()
public Duration get_requestHeadTimeout()
public int get_requestHeadFieldMaxLength()
public int get_requestHeadTotalMaxLength()
public long get_requestBodyMaxLength()
public Duration get_drainRequestTimeout()
public Duration get_closeTimeout()
public String get_requestEncodingPolicy()
public int get_xForwardLevel()
public boolean get_autoGzip()
public long get_autoGzipMinContentLength()
public boolean get_autoConditional()
public boolean get_autoRange()
public boolean get_autoCacheControl()
public Consumer<HttpAccess> get_accessLogger()
public Consumer<CharSequence> get_trafficDump()