-
Notifications
You must be signed in to change notification settings - Fork 0
/
GZipCompressor.cs
43 lines (35 loc) · 1.47 KB
/
GZipCompressor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace Jaahas.Http {
/// <summary>
/// <see cref="DelegatingHandler"/> that adds GZip compression to outgoing HTTP request
/// content.
/// </summary>
public class GZipCompressor : DelegatingHandler {
/// <summary>
/// A callback that will decide if the content of a given <see cref="HttpRequestMessage"/>
/// should be compressed.
/// </summary>
private readonly Func<HttpRequestMessage, bool>? _callback;
/// <summary>
/// Creates a new <see cref="GZipCompressor"/> object.
/// </summary>
/// <param name="callback">
/// A callback that will decide if the content of a given <see cref="HttpRequestMessage"/>
/// should be compressed. Specify <see langword="null"/> to apply compression to all
/// outgoing requests.
/// </param>
public GZipCompressor(Func<HttpRequestMessage, bool>? callback = null) {
_callback = callback;
}
/// <inheritdoc/>
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
if (request.Content != null && (_callback?.Invoke(request) ?? true)) {
request.Content = new GZipHttpContent(request.Content);
}
return base.SendAsync(request, cancellationToken);
}
}
}