1
1
/*
2
- * Copyright 2002-2019 the original author or authors.
2
+ * Copyright 2002-2020 the original author or authors.
3
3
*
4
4
* Licensed under the Apache License, Version 2.0 (the "License");
5
5
* you may not use this file except in compliance with the License.
16
16
17
17
package org .springframework .http .server .reactive ;
18
18
19
- import java .util .function .BiFunction ;
20
-
21
19
import org .reactivestreams .Publisher ;
22
20
import reactor .core .publisher .Flux ;
23
21
import reactor .core .publisher .Mono ;
@@ -41,24 +39,30 @@ public HttpHeadResponseDecorator(ServerHttpResponse delegate) {
41
39
42
40
43
41
/**
44
- * Apply {@link Flux#reduce(Object, BiFunction) reduce} on the body, count
45
- * the number of bytes produced, release data buffers without writing, and
46
- * set the {@literal Content-Length} header .
42
+ * Consume and release the body without writing.
43
+ * <p>If the headers contain neither Content-Length nor Transfer-Encoding,
44
+ * count the bytes and set Content-Length.
47
45
*/
48
46
@ Override
49
47
public final Mono <Void > writeWith (Publisher <? extends DataBuffer > body ) {
50
- return Flux .from (body )
51
- .reduce (0 , (current , buffer ) -> {
52
- int next = current + buffer .readableByteCount ();
53
- DataBufferUtils .release (buffer );
54
- return next ;
55
- })
56
- .doOnNext (length -> {
57
- if (length > 0 || getHeaders ().getFirst (HttpHeaders .CONTENT_LENGTH ) == null ) {
58
- getHeaders ().setContentLength (length );
59
- }
60
- })
61
- .then ();
48
+ if (shouldSetContentLength ()) {
49
+ return Flux .from (body )
50
+ .reduce (0 , (current , buffer ) -> {
51
+ int next = current + buffer .readableByteCount ();
52
+ DataBufferUtils .release (buffer );
53
+ return next ;
54
+ })
55
+ .doOnNext (length -> getHeaders ().setContentLength (length ))
56
+ .then ();
57
+ }
58
+ else {
59
+ return Flux .from (body ).then ();
60
+ }
61
+ }
62
+
63
+ private boolean shouldSetContentLength () {
64
+ return (getHeaders ().getFirst (HttpHeaders .CONTENT_LENGTH ) == null &&
65
+ getHeaders ().getFirst (HttpHeaders .TRANSFER_ENCODING ) == null );
62
66
}
63
67
64
68
/**
0 commit comments