zhaojh329 / libuhttpd

A very flexible, lightweight and high performance HTTP server library based on libev and http-parser for Embedded Linux.
MIT License
386 stars 67 forks source link

Provide a way to send neither Content-Length nor a chunked body #20

Open edgar-bonet opened 2 years ago

edgar-bonet commented 2 years ago

This is a feature request.

The send_head() method either sends a Content-Length header (if a valid length is provided), or enables chunked transfer encoding. It would be nice if it could be instructed to do neither.

Use case: Server-sent events (SSE) are a nice way to send a stream of messages to the client without requiring a request/response pair for each message. Although not as popular as WebSockets, SSE has the advantage of simplicity. Being plain HTTP, it is easier to implement on an HTTP server, as it doesn't require switching protocols. The framing overhead can be as small as 7 bytes per message:

/* This is a complete SSE message. */
conn->printf(conn, "data:%s\n\n", message_payload);

Even though SSE seems to work fine with chunked transfer encoding, using this encoding is not required, and is actually not recommended:

Authors are also cautioned that HTTP chunking can have unexpected negative effects on the reliability of this protocol, in particular if the chunking is done by a different layer unaware of the timing requirements. If this is a problem, chunking can be disabled for serving event streams.

Also, wrapping SSE with chunked transfer encoding amounts to redundant message framing, which practically doubles the framing overhead.