3

I've been looking into Mochiweb, but I can't find a way to read the body while I'm receiving the request through the socket.

I'm not limited to Mochiweb, any other HTTP library would be good for me.

I also tried gen_tcp:listen(Port, [{packet, http}]), this way I can read the body/headers while I'm receiving the HTTP request, but I must handle manually the responses and keeping the socket open for more requests, so I prefer not to use this solution.

My intention is to receive request with large bodies and not to wait to receive the full body in order to start reading/processing them.

Ricardo
  • 1,778
  • 1
  • 19
  • 32

1 Answers1

3

With mochiweb you can fold over chunks of the request body using Req:stream_body/3. It expects a chunk handler function as the second argument. This handler is called with {ChunkSize, BinaryData} and your state for every chunk, as it is received from the socket.

Example (retrieving a [reversed] list of chunks):

MaxChunkSize = 100,
InitialState = [],
ChunkHandler = fun ({_Size, Bin}, State) -> [Bin | State] end, 
List = Req:stream_body(MaxChunkSize, ChunkHandler, InitialState),
...
Felix Lange
  • 1,572
  • 11
  • 15
  • This must be done inside the defined request handler? But the request handler is invoked when the full request has been received, isn't it? I don't see how `Req:stream_body(...)` reads the body while it is arriving through the socket. I must be wrong in something, but don't know where. – Ricardo Nov 30 '10 at 18:04
  • the request handler is invoked quite early, as soon as the headers have been read. inside of the handler you can either receive the full request using `Req:recv_body/0` or stream it using `Req:stream_body/3`. The implementation of `stream_body` reads data from the socket in chunks and passes them to your chunk handler function. believe me, it works! – Felix Lange Nov 30 '10 at 18:16