Skip to content

Commit 2b91cf3

Browse files
committed
Ocsigen_response: Fix well-formedness of response body
1 parent 4adb9e8 commit 2b91cf3

File tree

1 file changed

+26
-15
lines changed

1 file changed

+26
-15
lines changed

src/server/ocsigen_response.ml

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
1+
open Cohttp
2+
open Lwt.Syntax
3+
14
module Body = struct
2-
type t = ((string -> unit Lwt.t) -> unit Lwt.t) * Cohttp.Transfer.encoding
5+
type t = ((string -> unit Lwt.t) -> unit Lwt.t) * Transfer.encoding
36

47
let make encoding writer : t = writer, encoding
58
let empty = make (Fixed 0L) (fun _write -> Lwt.return_unit)
69

710
let of_string s =
811
make
9-
(Cohttp.Transfer.Fixed (Int64.of_int (String.length s)))
12+
(Transfer.Fixed (Int64.of_int (String.length s)))
1013
(fun write -> write s)
1114

1215
let of_cohttp body =
@@ -18,9 +21,7 @@ module Body = struct
1821
end
1922

2023
type t =
21-
{ a_response : Cohttp.Response.t
22-
; a_body : Body.t
23-
; a_cookies : Ocsigen_cookie_map.t }
24+
{a_response : Response.t; a_body : Body.t; a_cookies : Ocsigen_cookie_map.t}
2425

2526
let make ?(body = Body.empty) ?(cookies = Ocsigen_cookie_map.empty) a_response =
2627
{a_response; a_body = body; a_cookies = cookies}
@@ -76,20 +77,30 @@ let make_cookies_headers path t hds =
7677
(make_cookies_header path exp name v secure))
7778
t hds
7879

79-
let to_cohttp_response {a_response; a_cookies; _} =
80+
let to_cohttp_response {a_response; a_cookies; a_body = _} =
8081
let headers =
81-
Cohttp.Header.add_unless_exists
82-
(Cohttp.Header.add_unless_exists
83-
(Ocsigen_cookie_map.Map_path.fold make_cookies_headers a_cookies
84-
(Cohttp.Response.headers a_response))
85-
"server" Ocsigen_config.server_name)
86-
"date"
87-
(Ocsigen_lib.Date.to_string (Unix.time ()))
82+
let add name value headers = Header.add_unless_exists headers name value in
83+
Ocsigen_cookie_map.Map_path.fold make_cookies_headers a_cookies
84+
(Response.headers a_response)
85+
|> add "server" Ocsigen_config.server_name
86+
|> add "date" (Ocsigen_lib.Date.to_string (Unix.time ()))
8887
in
89-
{a_response with Cohttp.Response.headers}
88+
{a_response with Response.headers}
9089

9190
let to_response_expert t =
92-
to_cohttp_response t, fun _ic oc -> fst t.a_body (Lwt_io.write oc)
91+
let module R = Cohttp_lwt_unix.Response in
92+
let write_footer {R.encoding; _} oc =
93+
(* Copied from [cohttp/response.ml]. *)
94+
match encoding with
95+
| Transfer.Chunked -> Lwt_io.write oc "0\r\n\r\n"
96+
| Transfer.Fixed _ | Transfer.Unknown -> Lwt.return_unit
97+
in
98+
let res = to_cohttp_response t in
99+
( res
100+
, fun _ic oc ->
101+
let writer = R.make_body_writer ~flush:false res oc in
102+
let* () = fst t.a_body (R.write_body writer) in
103+
write_footer res oc )
93104

94105
let response t = t.a_response
95106
let body t = t.a_body

0 commit comments

Comments
 (0)