ns_getcontent - Return the message body of a received request
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.
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.
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