diff --git a/lib/response.ml b/lib/response.ml index f6c36682fc..3702ca9874 100644 --- a/lib/response.ml +++ b/lib/response.ml @@ -67,18 +67,26 @@ module Make(IO : S.IO) = struct let flush = false in return (`Ok { encoding; headers; version; status; flush }) - let has_body {status; encoding} = - (* rfc7230#section-5.7.1 *) - match status with - | #Code.informational_status | `No_content | `Not_modified -> `No - | #Code.status_code -> Transfer.has_body encoding + let allowed_body response = (* rfc7230#section-5.7.1 *) + match status response with + | #Code.informational_status | `No_content | `Not_modified -> false + | #Code.status_code -> true + + let has_body response = + if allowed_body response + then Transfer.has_body (encoding response) + else `No + let make_body_reader {encoding} ic = Transfer_IO.make_reader encoding ic let read_body_chunk = Transfer_IO.read let write_header res oc = write oc (Printf.sprintf "%s %s\r\n" (Code.string_of_version res.version) (Code.string_of_status res.status)) >>= fun () -> - let headers = Header.add_transfer_encoding res.headers res.encoding in + let headers = + if allowed_body res + then Header.add_transfer_encoding res.headers res.encoding + else res.headers in Header_IO.write headers oc let make_body_writer ?flush {encoding} oc = diff --git a/lib_test/test_sanity.ml b/lib_test/test_sanity.ml index 096cd86662..1a3c7861de 100644 --- a/lib_test/test_sanity.ml +++ b/lib_test/test_sanity.ml @@ -1,5 +1,6 @@ open Lwt open OUnit +open Cohttp open Cohttp_lwt_unix open Cohttp_lwt_unix_test @@ -57,6 +58,9 @@ let ts = let not_modified_has_no_body () = Client.get uri >>= fun (resp, body) -> assert_equal (Response.status resp) `Not_modified; + let headers = Response.headers resp in + assert_equal ~printer:Transfer.string_of_encoding + Transfer.Unknown (Header.get_transfer_encoding headers); body |> Body.is_empty >|= fun is_empty -> assert_bool "No body returned when not modified" is_empty in [ "sanity test", t diff --git a/lwt/cohttp_lwt.ml b/lwt/cohttp_lwt.ml index 81c0243ddc..1d07a291b7 100644 --- a/lwt/cohttp_lwt.ml +++ b/lwt/cohttp_lwt.ml @@ -310,7 +310,7 @@ module Make_server(IO:IO) = struct Filename.concat docroot rel_path let respond ?headers ?(flush=true) ~status ~body () = - let encoding = + let encoding = match headers with | None -> Cohttp_lwt_body.transfer_encoding body | Some headers ->