TSHttpTxnPostBufferReaderGet

Synopsis

#include <ts/ts.h>
TSIOBufferReader TSHttpTxnPostBufferReaderGet(TSHttpTxn txnp)

Description

Retrieve the client request body for the transaction referenced by txnp. The body is read from via the returned TSIOBufferReader. The returned TSIOBufferReader is owned by the caller and the caller must free it via TSIOBufferReaderFree(). This function should be used in the handler for TS_HTTP_REQUEST_BUFFER_READ_COMPLETE_HOOK. The following example handler makes use of TSHttpTxnPostBufferReaderGet().

int
CB_Read_Request_Body_Hook(TSCont contp, TSEvent event, void* data) {
  ink_assert(event == TS_EVENT_HTTP_REQUEST_BUFFER_COMPLETE);
  auto txnp = reinterpret_cast<TSHttpTxn>(data);

  TSIOBufferReader post_buffer_reader = TSHttpTxnPostBufferReaderGet(txnp);
  int64_t read_avail                  = TSIOBufferReaderAvail(post_buffer_reader);

  if (read_avail > 0) {
    char *body_bytes = reinterpret_cast<char *>(TSmalloc(sizeof(char) * read_avail));

    int64_t consumed      = 0;
    TSIOBufferBlock block = TSIOBufferReaderStart(post_buffer_reader);
    while (block != NULL) {
      int64_t data_len        = 0;
      const char *block_bytes = TSIOBufferBlockReadStart(block, post_buffer_reader, &data_len);
      memcpy(body_bytes + consumed, block_bytes, data_len);
      consumed += data_len;
      block = TSIOBufferBlockNext(block);
    }

    // Now do something with body_bytes which contains the contents of the
    // request's body.
  }

  // Remeber to free the TSIOBufferReader.
  TSIOBufferReaderFree(post_buffer_reader);

  TSHttpTxnReenable(txnp);
  return 0;
}

example/plugins/c-api/request_buffer/request_buffer.c is a simple yet complete plugin that accesses HTTP request bodies.