net.http Package

Function Description

The HTTP package provides the server and client implementation of the HTTP/1.1, HTTP/2, and WebSocket protocols.

For details about the protocols, see RFC 9110, 9112, 9113, 9218, and 7541.

This package depends on the SSL and crypto dynamic library files of OpenSSL 3. Therefore, related tools must be installed in advance.

  • For Linux, perform the following operations:
    • Install the OpenSSL 3 development tool package using the package management tool of the system if the tool supports the installation, and ensure that the system installation directory contains the libssl.so, libssl.so.3, libcrypto.so, and libcrypto.so.3 dynamic library files. For example, on Ubuntu 22.04, run the sudo apt install libssl-dev command to install the libssl-dev tool package.
    • Download and install the OpenSSL 3.*x*.*x* source code compilation software package if the preceding method fails, and ensure that the installation directory contains the libssl.so, libssl.so.3, libcrypto.so, and libcrypto.so.3 dynamic library files. Then, use either of the following methods to ensure that the system linker can find these files:
      • Install OpenSSL in the system path if it has not been installed in the system.
      • Set the directory where the OpenSSL development tool package files are located to the environment variables LD_LIBRARY_PATH and LIBRARY_PATH if OpenSSL is installed in a user-defined directory.
  • For Windows, perform the following operations:
    • Download and install the OpenSSL 3.*x*.*x* source code compilation software package for the x64 architecture, or download and install the OpenSSL 3.*x*.*x* software package precompiled by a third party for developers.
    • Ensure that the installation directory contains the libssl.dll.a (or libssl.lib), libssl-3-x64.dll, libcrypto.dll.a (or libcrypto.lib), and libcrypto-3-x64.dll library files.
    • Set the directory containing libssl.dll.a (or libssl.lib) and libcrypto.dll.a (or libcrypto.lib) to the environment variable LIBRARY_PATH, and the directory containing libssl-3-x64.dll and libcrypto-3-x64.dll to the environment variable PATH.
  • For macOS, perform the following operations:
    • Run the brew install openssl@3 command to install OpenSSL, and ensure that the system installation directory contains the libcrypto.dylib and libcrypto.3.dylib dynamic library files.
    • Download and install the OpenSSL 3.*x*.*x* source code compilation software package if the preceding method fails, and ensure that the installation directory contains the libcrypto.dylib and libcrypto.3.dylib dynamic library files. Then, use either of the following methods to ensure that the system linker can find these files:
      • Install OpenSSL in the system path if it has not been installed in the system.
      • Set the directory where the OpenSSL development tool package files are located to the environment variables DYLD_LIBRARY_PATH and LIBRARY_PATH if OpenSSL is installed in a user-defined directory.

If OpenSSL 3 is not installed or an earlier version is installed, the program may fail to work with a TLS-related exception thrown.

http

The user can select the HTTP version, for example, HTTP/1.1 or HTTP/2. Most APIs of HTTP packets support both protocol versions. The two protocol versions need to be distinguished only when a user uses a specific function of a version, for example, chunked transfer-encoding in HTTP/1.1 and server push in HTTP/2.

The HTTP library uses HTTP/1.1 by default. To use HTTP/2, the developer needs to configure TLS for the client and server and set ALPN to h2. HTTP/1.1 cannot be upgraded to HTTP/2 through Upgrade: h2c.

If the handshake for creating an HTTP/2 connection fails, the client and server automatically fall back to HTTP/1.1.

  • The user uses ClientBuilder to create a Client instance with multiple parameters available, such as httpProxy, logger, cookieJar, redirect, and connection pool size.

  • The user uses ServerBuilder to create a Server instance with multiple parameters available, such as addr, port, logger, and distributor.

A user-defined logger must be thread-safe.

Most parameters of the client and server cannot be modified after construction. To modify these parameters, a new Client or Server instance must be constructed. This implementation provides explicit functions for parameters that can be dynamically modified, such as cert and CA hot update on the server.

  • A user can use a Client instance to send HTTP requests and receive HTTP responses.

  • A user can use a Server instance to configure the request forwarding processor and start the HTTP server. In the server handler, the user can obtain the detailed information about the request sent by the client through HttpContext and construct the response to be sent to the client. The server creates a ProtocolService instance based on the client's request. A Server instance supports both HTTP/1.1 and HTTP/2.

  • On the client, the user uses HttpRequestBuilder to construct a request with multiple parameters available, such as method, URL, version, headers, body, and trailers. A request cannot be modified after construction.

  • On the server, the user uses HttpResponseBuilder to construct a response with multiple parameters available, such as status, headers, body, and trailers. A response cannot be modified after construction.

In addition, this implementation provides some tool classes for users to construct common responses. For example, a user can use RedirectHandler to construct a redirect response, and use NotFoundHandler to construct a 404 response.

WebSocket

This implementation provides sub-protocol negotiation for WebSocket, including basic frame decoding, reading, message sending, frame encoding, ping, pong, and closing.

The user uses WebSocket.upgradeFromClient to upgrade HTTP/1.1 or HTTP/2 used by a Client instance to WebSocket, and then uses the returned WebSocket instance for WebSocket communication.

In a handler on the server, the user uses WebSocket.upgradeFromServer to upgrade HTTP/1.1 or HTTP/2 to WebSocket, and then uses the returned WebSocket instance for WebSocket communication.

According to the protocol, in HTTP/1.1, the upgraded WebSocket connection is established on the TCP/TLS connection. In HTTP/2, the upgraded WebSocket connection is established on a stream of the HTTP/2 connection. In HTTP/1.1, the close operation directly closes the TCP/TLS connection. In HTTP/2, the close operation closes only a stream on the connection.

API List

Function

NameDescription
handleError(HttpContext, UInt16)Specifies a shortcut HTTP request processing function used to return error requests.
notFound(HttpContext)Specifies a shortcut HTTP request processing function used to return the 404 response.
upgrade(HttpContext)Obtains StreamingSocket from the handler to support protocol upgrade and process CONNECT requests.

Interface

NameDescription
CookieJarSpecifies a tool used by the client to manage cookies.
HttpRequestDistributorSpecifies an HTTP request distributor interface used to distribute a request to the corresponding HttpRequestHandler based on the path in the URL.
HttpRequestHandlerSpecifies an HTTP request handler.
ProtocolServiceFactorySets the HTTP service instance factory used to generate ProtocolService instances.

Class

NameDescription
ClientSpecifies the Client class. A user can use a Client instance to send HTTP/1.1 or HTTP/2 requests.
ClientBuilderConstructs Client instances. Since there is no public constructor for Client instance construction, the user can obtain Client instances only by using ClientBuilder. If the ClientBuilder document does not specify the supported version, the configuration is valid in both HTTP/1.1 and HTTP/2.
CookieHTTP is stateless. To obtain the client status and provide personalized services, the server can use Cookie to maintain a stateful session.
FileHandlerHandles file download or upload.
FuncHandlerSpecifies the HttpRequestHandler interface wrapper class, which wraps a single function into an HttpRequestHandler.
HttpContextSpecifies the HTTP request context used as a parameter of the HttpRequestHandler.handle function on the server.
HttpHeadersIndicates the header and trailer in an HTTP packet with the add, delete, modify, and query operations defined.
HttpRequestSpecifies the HTTP request class.
HttpRequestBuilderSpecifies the HttpRequestBuilder class used to construct HttpRequest instances.
HttpResponseSpecifies the HTTP response class.
HttpResponseBuilderConstructs an HttpResponse instance.
HttpResponsePusherSets the HTTP/2 server push.
HttpResponseWriterSpecifies the HTTP response message body writer, which allows a user to control the sending process of the message body.
NotFoundHandlerSpecifies a convenient HTTP request handler and 404 Not Found handler.
OptionsHandlerSpecifies a convenient HTTP handler used to process OPTIONS requests. The "Allow: OPTIONS, GET, HEAD, POST, PUT, or DELETE" response header is always returned.
ProtocolServiceSpecifies an HTTP service instance, which provides HTTP services for a single client connection, including parsing client request packets, distributing requests, and sending responses.
RedirectHandlerSpecifies a convenient HTTP handler used to return redirection responses.
ServerSpecifies the server class providing the HTTP service.
ServerBuilderProvides a server instance builder.
WebSocketProvides classes related to the WebSocket service and read, write, and close functions for the WebSocket connection. The user can use the upgradeFrom function to obtain a WebSocket connection.
WebSocketFrameSpecifies the basic unit used by WebSocket for reading.

Enumeration

NameDescription
FileHandlerTypeSets the FileHandler mode to upload or download.
ProtocolDefines the HTTP protocol type enumeration.
WebSocketFrameTypeDefines the enumeration types of WebSocketFrame.

Struct

NameDescription
HttpStatusCodeSpecifies a 3-digit code indicating the response status of Hypertext Transfer Protocol (HTTP) of the web server.
ServicePoolConfigConfigures the HTTP server coroutine pool.
TransportConfigSpecifies a transport layer configuration class used by the server to establish a connection.

Exception Class

NameDescription
ConnectionExceptionSpecifies the TCP connection exception class of HTTP.
CoroutinePoolRejectExceptionSpecifies the exception class of HTTP coroutine pool rejecting processing requests.
HttpExceptionSpecifies the common exception class of HTTP.
HttpStatusExceptionSpecifies the response status exception class of HTTP.
HttpTimeoutExceptionSpecifies the timeout exception class of HTTP.
WebSocketExceptionSpecifies the common exception class of WebSocket.