NaviServer Programmable Web Server

ns_return(n)

NaviServer Built-in Commands – 5.1.0


[ Main Table Of Contents | Table Of Contents | Keyword Index ]

Name

ns_return - Return a complete HTTP response

Table Of Contents

Synopsis

Description

These are the lower elevel commands are used to construct a complete HTTP response and return it to the requesting client. The response may be transcoded into a different encoding, compressed and/or sent in chunks as automatically negotiated by the client and server settings.

Unless otherwise noted, these commands return true if the command failed and false otherwise. All of them can raise an error if their arguments are incorrect.

The behavior of the file delivery commands ns_returnfile and ns_repond is influenced by the fastpath settings, that define, how static files are served. The fastpath settings are described in the CONFIGURATION section at the end of this page.

Note that there are additional higher level commands are designed to ease consistent behavior in common success, redirect or error situations (see returnstatus-cmds).

COMMANDS

ns_return ?-binary? status mimetype data

Sends a complete response to the client consisting of the given data as response body and a set of HTTP headers. status is an integer HTTP status code such as 200 (OK) or 404 (Not Found). When the optional flag -binary is used, the content of the Tcl byte-array is transmitted.

mimetype is the MIME type of the body. If a charset attribute is included in the MIME type it will be used to set the encoding of the connection. Otherwise, the connection encoding will be used to construct a charset attribute for the MIME type.

If body is Tcl byte-array object then no transcoding will take place. Otherwise, the encoding in effect for the current connection will be used to encode the body.

After the command completes the connection is returned to the driver thread to be closed or monitored for keep-alive and the calling connection thread continues to execute code.

ns_returnfile status mimetype filename

Sends the given file as the complete response body. Headers are constructed using status, mimetype and any pending headers set using ns_conn outputheaders. The bytes of the file are not transformed in any way.

After the command completes the connection is returned to the driver thread to be closed or monitored for keep-alive and the calling connection thread continues to execute code.

ns_returnfp status mimetype channel length

Sends length bytes from channel as the response body. The current offset of the channel is the beginning of the body -- the offset will be left at length bytes. The bytes of the file are not transformed in any way.

After the command completes the connection is returned to the driver thread to be closed or monitored for keep-alive and the calling connection thread continues to execute code.

ns_respond ?-status integer? ?-type value? ?-length integer? ?-headers setId? ?-string value? ?-file value? ?-fileid value? ?-data data?

Sends a complete response to the client using exactly one of -string, -binary, -file or -fileid as the body.

After the command completes the connection is returned to the driver thread to be closed or monitored for keep-alive and the calling connection thread continues to execute code.

-status

The HTTP status code. Default 200.

-type

The MIME type of the response body. Default */*.

-length

The number of bytes to send from the channel (in connection with -fileid).

-headers

The setid of an ns_set containing the headers which will replace any pending headers for the response. If the parameter is not specified, ns_conn outputheaders will be used.

-string

The Tcl string to send as the response body. The body may be encoded into an appropriate character set if required by the client and server settings.

-file

The file identified by the given filepath (fully qualified filename) will be sent as the response body. The bytes of the file will not be transformed in any way.

-fileid

The file identified by the given Tcl channel will be sent as the response body. The bytes of the file will not be transformed in any way.

-data data

The byte-array representation of the given Tcl object will be used as the response body. No character set conversion will be done.

ns_gzipfile source target

Compresses the file source to target using the gzip command configured by the gzip_cmd parameter in the ns/fastpath section.

This command is called internally by NaviServer when fastpath gzip refresh is enabled and a stale ".gz" variant of a static file has to be refreshed. It creates or replaces the compressed file target in the filesystem; the command itself does not return the compressed content to the client.

Applications may redefine this command when different gzip or preprocessing behavior is required.

When source has the extension .css or .js, NaviServer checks the optional minify_css_cmd or minify_js_cmd configuration parameters. If a matching minifier is configured, the source is first passed through the minifier and then through gzip. The minifier command must read from standard input and write the minified content to standard output.

ns_brotlifile source target

Compresses the file source to target using the Brotli command configured by the brotli_cmd parameter in the ns/fastpath section.

This command is called internally by NaviServer when fastpath Brotli refresh is enabled and a stale ".br" variant of a static file has to be refreshed. It creates or replaces the compressed file target in the filesystem; the command itself does not return the compressed content to the client.

Applications may redefine this command when different Brotli compression behavior is required.

EXAMPLES

A traditional geek greeting:

 ns_register_proc GET /hello {
   ns_return 200 text/plain "Hello World!"
 }

A traditional Albanian greeting, using an explicit charset:

 ns_register_proc GET /hello {
   ns_return 200 "text/plain; charset=iso-8859-2" "Përshëndetje të gjithëve!"
 }

CONFIGURATION

The behavior of ns_returnfile, ns_respond -file ..., and automatic static-file delivery is controlled by fastpath configuration. Fastpath has global settings in ns/fastpath and per-server settings in ns/server/$server/fastpath.

 ns_section ns/fastpath {
    # Global fastpath delivery settings.
    ns_param cache false
    ns_param mmap  false
 
    # Serve existing .gz files when the client accepts gzip content.
    ns_param gzip_static true
 
    # Refresh stale .gz files by invoking ns_gzipfile.
    ns_param gzip_refresh true
    ns_param gzip_cmd     "/usr/bin/gzip -9"
 
    # Optional minification before gzip refresh for CSS and JavaScript.
    # The commands must read from stdin and write to stdout.
    # ns_param minify_css_cmd "/usr/bin/yui-compressor --type css"
    # ns_param minify_js_cmd  "/usr/bin/yui-compressor --type js"
 }
 
 ns_section ns/server/$server/fastpath {
    # Per-server file location and directory handling.
    ns_param pagedir          pages
    ns_param directoryfile    {index.adp index.tcl index.html index.htm}
    ns_param directorylisting fancy
 }

File Delivery Modes

Fastpath supports several delivery modes for static content.

  1. If both cache and mmap are disabled, files are delivered by reading from the file descriptor and sending chunks to the client. This is similar to ns_respond -fileid ... and ns_returnfp.

  2. If mmap is enabled and supported by the operating system, files can be mapped into memory and served from the mapped region.

  3. If cache is enabled, eligible files are stored in NaviServer's fastpath file cache and served from memory.

Pre-Compressed Static Files

Fastpath can serve pre-compressed gzip or brotli versions of static files when the client indicates support for the corresponding content encoding. For example, if path/foo.ext is requested and path/foo.ext.gz or path/foo.ext.br exists and is current, NaviServer can deliver the compressed file directly.

The refresh options can be used to regenerate stale compressed files through the configured helper commands. These commands are only used for refreshing existing compressed files; they do not proactively compress arbitrary files.

Directory Handling

Per-server fastpath settings control what happens when a request maps to a directory. NaviServer first looks for one of the configured directoryfile names. If no index file is found, it can use an ADP page configured by directoryadp, or otherwise call the Tcl procedure named by directoryproc.

The directorylisting and hidedotfiles parameters control the behavior of the default directory listing procedure.

Global Fastpath Settings

The global ns/fastpath section controls process-wide static-file delivery behavior. These settings determine whether eligible files may be served from the fastpath cache, through memory-mapped I/O, or directly from the filesystem.

The same section also controls delivery of pre-compressed static files. When gzip_static or brotli_static is enabled, NaviServer checks for a corresponding ".gz" or ".br" file when the client advertises support for the encoding. If the compressed file exists and is current, it is served instead of the uncompressed source file.

When gzip_refresh or brotli_refresh is enabled, NaviServer can refresh stale compressed files by invoking ::ns_gzipfile or ::ns_brotlifile. These commands are used only for refreshing existing compressed files; they do not proactively create compressed variants for files that do not already have one.

For gzip refresh, ::ns_gzipfile uses the configured gzip_cmd. For CSS and JavaScript files, optional minify_css_cmd and minify_js_cmd commands can be configured. When present, the minifier is run before gzip compression. The minifier command must read the source content from standard input and write the minified result to standard output.

Parameter name: brotli_cmd

Use for re-compressing

  • Type: command

Parameter name: brotli_refresh

Refresh stale .br files

  • Type: boolean

  • Default: false

Parameter name: brotli_static

Check for static brotli files

  • Type: boolean

  • Default: false

Parameter name: cache

Enable the global fastpath file-content cache for small static files; cached entries are validated against file mtime, size, device, and inode, while recently changed files and files larger than cachemaxentry are served directly

  • Type: boolean

  • Default: false

Parameter name: cachemaxentry

Maximum size of an individual static file stored in the fastpath cache; files above this limit are not cached and are served directly from the filesystem or via mmap when enabled

  • Type: size

  • Default: 8KB

Parameter name: cachemaxsize

Maximum total memory used by the fastpath file-content cache; applies only when the fastpath cache parameter is enabled

  • Type: size

  • Default: 10MB

Parameter name: gzip_cmd

Use for re-compressing

  • Type: command

Parameter name: gzip_refresh

Refresh stale .gz files

  • Type: boolean

  • Default: false

Parameter name: gzip_static

Check for static gzip file

  • Type: boolean

  • Default: false

Parameter name: minify_css_cmd

Command used to minify CSS files when refreshing stale gzip-compressed static files; the command must read CSS from stdin and write minified CSS to stdout

  • Type: command

  • Default:

Parameter name: minify_js_cmd

Command used to minify JavaScript files when refreshing stale gzip-compressed static files; the command must read JavaScript from stdin and write minified JavaScript to stdout

  • Type: command

  • Default:

Parameter name: mmap

Use memory-mapped I/O for serving static files that are not cached; falls back to normal file reading when mmap is unavailable or disabled

  • Type: boolean

  • Default: false

Per-Server Fastpath Settings

The per-server ns/server/$server/fastpath section defines where static files are found and how directory requests are handled for a virtual server.

The pagedir parameter defines the page directory below the server directory. It is the root for static-file delivery by fastpath.

Directory handling is controlled by parameters such as directoryfile, directoryadp, directoryproc, directorylisting, and hidedotfiles. When a request maps to a directory, NaviServer first looks for one of the configured index files. If no index file is found, it can use a configured directory-listing ADP or invoke a Tcl directory-listing procedure.

Parameter name: directoryadp

ADP page invoked to generate a directory listing when a request maps to a directory and no directory index file is found; when unset, NaviServer falls back to directoryproc if configured

  • Type: path

  • Default:

Parameter name: directoryfile

List of filenames to try when a request maps to a directory; the first existing file is served as the directory index

  • Type: list

  • Default: index.adp index.tcl index.html index.htm

Parameter name: directorylisting

Directory listing style

  • Type: enum

  • Allowed values: simple, fancy, none

Parameter name: directoryproc

Tcl procedure used to generate directory listings when no directory index file is found and directory listing is enabled

  • Type: proc

  • Default: _ns_dirlist

Parameter name: hidedotfiles

Hide files and directories whose names start with a dot from generated directory listings

  • Type: boolean

  • Default: true

Parameter name: pagedir

Root directory for static files and fastpath content for this server; relative paths are resolved against the server home directory

  • Type: path

  • Default: pages

See Also

admin-config-params, ns_adp_puts, ns_conn, ns_guesstype, ns_register, ns_write, ns_writer, returnstatus-cmds

Keywords

brotli, cache, charset, configuration, encoding, fastpath, gzip, minify, mmap, pagedir, response, return, server built-in, serverdir, status, writer