NaviServer - programmable web server
4.99  5.0

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

ns_getcontent(n) 5.0.0a naviserver "NaviServer Built-in Commands"

Name

ns_getcontent - Return the message body of a received request

Table Of Contents

Synopsis

Description

This command returns the content of a request as file or as string, no matter, whether it was spooled during upload into a file or not. The user can specify, whether the result should treated as binary or not. the default is "-as_file true", since this will not run into memory problems on huge files.

COMMANDs

ns_getcontent ?-as_file true|false? ?-binary true|false?

Returns as result the filename of the temporary file (when spooled to a file, default) or the content of the file (when -as_file is false). When -binary is true (default) the result is returned literally, otherwise the content is translated to the active charset.

Typically this command is used on POST, PUT, PROPFIND or similar requests.

EXAMPLES

The following script checks, whether the received request was a POST or POST requests, it checks the provided content type, and in case it was a JSON type, it retrieves the payload of the request and converts it to a Tcl dict. Note that the json package form tcllib has some restrictions. There are several alternative JSON parsers available for Tcl.

 if {[ns_conn method] in {PUT POST}
    && [ns_set get -nocase [ns_conn headers] content-type] eq "application/json"
 } {
    package req json
 
    set dict [json::json2dict [ns_getcontent -as_file false -binary false]]
    ns_return 200 text/plain $dict\n
 
 } else {
    ad_return_complaint 1 "unsupported HTTP method: [ns_conn method]"
 }

When the script above is saved in the page directory under the name json_receiver.tcl, and the server is running under port 8100 on localhost, the example above can be tested e.g. with the following command from the shell.

 curl --header "content-type: application/json" --request POST --data '{
   "username":"xyz","password":"xyz"
 }' http://localhost:8100/json-receiver.tcl

See Also

ns_conn, ns_getform, ns_return

Keywords

form