Streaming HTTP Responses

The low-level function response.flush() should not be used to manage HTTP responses. Ivanti recommends using the http.stream.* functions instead.

If you wish to generate or modify an HTTP response, the simplest way to do so is to read the response in its entirety (using http.getResponseBody()), manipulate it, and then write it using http.setResponseBody(). However, this can be inefficient when managing large HTTP responses for the following reasons:

Data is not written to the client until the response rule completes. If it takes time to read the entire response and manipulate it, this can potentially cause the client to timeout and close the connection.

The entire response needs to be managed in memory, which can be very memory-inefficient. The memory is not discarded until the rule has completed and the data is written to the client.

As an alternative, you can stream HTTP responses, reading and writing them in smaller quantities. Response data is written as soon as it is available, ensuring lower memory use and better performance.

The following functions manage HTTP streaming:

Function

Notes

http.stream.startResponse()

This function should be called before any data is written to the client. The headers for the response as assembled and written to the client. No response header manipulation can be performed after this point.

http.stream.readResponse()

Reads and returns a portion of the HTTP response body, limited by length or a delimiter character.

http.stream.writeResponse()

Writes the supplied body data to the client, but holds the connection open for additional body data if required.

http.stream.finishResponse()

Indicates that response streaming has finished. Rules processing is halted and any remaining response data is sent to the client.

 

The following TrafficScript rule processes HTML responses line by line, making a simple substitution:

$status = http.getResponseCode();

if( $status != 200 ) break;

 

$type = http.getResponseHeader("Content-Type");

if( !string.startsWith( $type, "text/") ) break;

 

http.stream.startResponse( $rcode, $type );

 

while( $line = http.stream.readResponse( 2048, "\n" ) ) {

$line = string.replaceAll( $line, "TrafficScript", "TRAFFICSCRIPT" );

http.stream.writeResponse( $line );

}

 

http.stream.finishResponse();

The http.stream.* series of TrafficScript functions cannot be used in conjunction with the Traffic Manager’s Web content optimization technology - Aptimizer. Executing any of these functions bypasses Aptimizer completely and return the response directly to the client.