NaviServer Built-in Commands – 5.0.0a
ns_conn - Query or modify state information about the current HTTP connection
This command provides various subcommands that allow you to query and modify properties of the current HTTP connection.
The subcommands of ns_conn (listed here in alphabetical order) include:
Returns the compression formats accepted by the client, as indicated by the Accept-Encoding header.
Returns the content of the Authorization header as an ns_set. For Basic authentication, the ns_set includes reserved keys such as "Username" and "Password" (the values returned by ns_conn authuser and ns_conn authpassword). For Digest authentication, all header fields are included in the ns_set. For Bearer authentication, the ns_set contains the base64-encoded token. The returned ns_set can also be updated.
For other authorization schemes, the Authorization header is treated like any other request header. For example:
set auth_header [ns_set get -nocase [ns_conn header] Authorization ""]
Returns the decoded user password extracted from the authorization data.
Returns the decoded username extracted from the authorization data.
Returns the Tcl channel name for the current connection.
Queries or sets the client data associated with the current connection. This application-defined data may be shared across threads to help maintain context of running requests (e.g. to determine which user initiated a request).
Closes the connection so that the script or ADP can perform time-consuming processing without delaying the client. When using ns_conn close in an ADP, ensure that streaming is enabled (e.g., via <SCRIPT RUNAT=SERVER STREAM=ON>) so that output is sent before the connection is terminated in this case.
Queries or sets the compression level for the current connection. Specifying a level of 0 disables compression.
Returns the body of the HTTP request. Optionally, you can specify an offset and length to extract a substring. If the -binary option is used, raw binary content is returned; otherwise, the content is converted to the connection’s encoding. Note that the response content may be delivered either as a string (via ns_conn content) or as a file (see ns_conn contentfile), depending on configration options.
Returns the name of the temporary file that holds the request content. Whether the received contemt is spooled to a file depends on the configuration settings.
Returns the length (in bytes) of the HTTP request body.
Queries or sets the number of bytes of content that have been sent.
Copies a specified number of bytes from the connection’s buffered data to a Tcl channel. The offset and length parameters define the starting position and the number of bytes to copy.
This command is intended for specialized use cases where the raw, unsent content is needed (available only if the data is not spooled to a file). For most applications, consider using ns_getcontent instead.
Returns the local IP address (IPv4 or IPv6) of the current connection (i.e. the destination address of the socket).
Returns the local port (i.e. the destination port of the socket) for the current connection.
Returns a dict containing driver-specific details for the current connection. This dict typically includes the local IP address, its type (IPv4/IPv6), whether it is public or trusted, and whether the connection is proxied. For HTTPS connections, additional fields such as sslversion, cipher, and servername (as provided via SNI) are included.
Returns the name of the module (e.g., nssock or nsssl) acting as the communications driver for this connection.
Queries or sets the encoding for the current connection. If an encoding is provided, it sets the encoding; otherwise, it returns the current encoding.
Returns an ns_set containing header information for the uploaded file specified by file (as returned by ns_conn files). If the file was uploaded using the HTML5 multiple attribute, a list of ns_sets is returned.
Returns the length (in bytes) of the uploaded file specified by file. For files uploaded using the HTML5 multiple attribute, a list of file lengths is returned.
Returns the byte offset of the uploaded file specified by file. For files uploaded using the HTML5 multiple attribute, a list of offsets is returned.
Returns a list of files uploaded with the current form.
Returns the internal connection flags. Use with caution as these flags may change in future releases.
Returns any submitted form data as an ns_set. The form data may be submitted via POST or included in the URL of a GET request.
The option `-fallbackcharset` specifies an alternative character set for decoding the form data if the default decoding results in invalid UTF-8. (This fallback charset can also be set globally via the formfallbackcharset configuration parameter.) For multipart form data file uploads, use ns_getform instead.
Returns the fragment identifier of the request URL (the portion following the # character).
Returns the length of the HTTP request header. Combined with ns_conn contentlength, this can be used to determine the total uncompressed size of the request (excluding any chunked encoding overhead).
Returns all HTTP request header fields as an ns_set, where each key is a header field name. The case of the header names depends on the HeaderCase configuration parameter (default is Preserve).
Returns the host part of the URL in the HTTP request line. This field is set only when NaviServer is used as a (forward) proxy server.
Returns a unique identifier for the current connection.
Returns 1 if the current code is executing in a connection thread and the connection is open (allowing ns_conn calls), or 0 otherwise (e.g., when running in a schedule procedure).
Queries or sets the keepalive value for the current connection.
Returns the location string for the virtual server handling the request in the format (":port" ist optional): protocol://hostname:port
The location is determined by:
If ns_locationproc is configured, its result is returned.
If virtual hosting is enabled and a valid "Host:" header is provided, its value is used.
Otherwise, the virtual hosts mapping table (as defined in the ns/module/nssock/servers or ns/module/nsssl/servers section) is consulted.
If no match is found and a connection is open, the current socket address is used.
If all else fails, the location is derived from the driver's configuration.
Returns the HTTP method (e.g., GET, POST).
Returns an ns_set containing the HTTP response header fields that will be sent to the client. This ns_set can be modified to extend, update, or clear the response headers. For example:
ns_set put [ns_conn outputheaders ] "Content-Disposition" "attachment;filename=export.xotcl"
Returns the client's IP address (the remote endpoint of the connection). For IPv4, the address is returned in dotted decimal notation; for IPv6, in colon-separated format. In reverse proxy mode, the IP is derived from the x-forwarded-for header. The optional -source parameter can force the return of the configured, direct, or forwarded IP address.
Returns the connection pool associated with the current server.
Returns the currently associated connection pool of this request.
Returns the port specified in the host header or the protocol's default port. In proxy mode, it returns the port specified in the HTTP request URL, or 0 for backwards compatibility.
Returns the protocol used by the current connection. In (forward) proxy mode, this reflects the URL present in the request line.
Returns the query parameters of the HTTP request (the portion after the ? and before the # in the URL).
Returns detailed timing information for the current request as a dict. Keys include:
accepttime: Time between socket acceptance and queueing.
queuetime: Time spent in the queue.
filtertime: Time spent executing filters.
runtime: Total time elapsed during request processing.
Queries or sets the rate limit for the current connection in kilobytes per second (KB/s). A value of 0 indicates no limit. Default limits can be set at the connection pool level (parameter ratelimit) or at the driver level (writerratelimit). Rate limiting is enforced only on connections using writer threads.
Returns the HTTP request line as received from the client (e.g., "GET / HTTP/1.1").
Returns the name of the server handling the request.
Returns the socket identifier (integer file descriptor) for the current connection.
Returns the time when the connection request started in "sec:usec" (ns_time) format.
Queries or sets the HTTP status code for the current connection.
Returns the URI target from the start line of the HTTP request (this may include query variables).
Returns an absolute time value beyond which the connection will not wait for resources (e.g., condition variables).
Returns the URL of the HTTP request. This is the portion of the URL following the hostname (e.g., "/index.adp").
if { [string match /page/* [ns_conn url]] } { ns_returnnotfound }
Returns the number of elements in the URL, as determined by splitting on the / character.
Returns the current request URL as a Tcl dictionary. The dictionary separates the URL into its constituent components (such as protocol, host, port, path, query, fragment, etc.).
This structured representation allows you to modify specific parts of the URL programmatically (for example, removing the query or adding a fragment) and then rebuild the complete URL using ns_joinurl. This is especially useful for dynamic web applications that require URL manipulation based on request context or custom routing logic.
# Original URL: /foo/bar?x=1 set urldict [ns_conn urldict] # Example result: {path foo tail bar query x=1} dict unset urldict query dict set urldict fragment sect2 set url [ns_joinurl $urldict] # Resulting URL: /foo/bar#sect2
Queries or sets the URL encoding for the current connection. If an encoding value is provided, it sets the URL encoding; otherwise, it returns the current encoding.
Returns a list of the URL components (delimited by `/'). If idx is provided, returns the nth element of the URL vector.
Returns the HTTP version of the current request (typically 1.0 or 1.1).
Returns 0 or 1 depending on whether the client accepts a zip-encoded response.