Skip to content

Commit

Permalink
Enable nullable types and implicit usings
Browse files Browse the repository at this point in the history
  • Loading branch information
matteocontrini committed Oct 26, 2023
1 parent 2f9b706 commit bf727f7
Show file tree
Hide file tree
Showing 11 changed files with 73 additions and 125 deletions.
5 changes: 1 addition & 4 deletions PlainHttp/AsyncExtensionMethods.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using System;
using System.Threading.Tasks;

namespace PlainHttp;
namespace PlainHttp;

static class AsyncExtensionMethods
{
Expand Down
8 changes: 3 additions & 5 deletions PlainHttp/HttpClientFactory.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Concurrent;
using System.Net;
using System.Net.Http;

namespace PlainHttp;

Expand Down Expand Up @@ -77,7 +75,7 @@ protected virtual HttpClient CreateProxiedClient(Uri proxyUrl)

HttpClient client = new HttpClient(handler)
{
Timeout = System.Threading.Timeout.InfiniteTimeSpan
Timeout = Timeout.InfiniteTimeSpan
};

return client;
Expand All @@ -94,7 +92,7 @@ protected virtual HttpClient CreateClient()

HttpClient client = new HttpClient(handler)
{
Timeout = System.Threading.Timeout.InfiniteTimeSpan
Timeout = Timeout.InfiniteTimeSpan
};

return client;
Expand Down
93 changes: 41 additions & 52 deletions PlainHttp/HttpRequest.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
using Flurl.Util;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;

Expand All @@ -19,36 +13,31 @@ public class HttpRequest : IHttpRequest

public Uri Uri { get; set; }

public Version HttpVersion { get; set; }
public Version? HttpVersion { get; set; }

public static IHttpClientFactory HttpClientFactory { get; set; } = new HttpClientFactory();

public HttpRequestMessage Message { get; protected set; }
public HttpRequestMessage? Message { get; protected set; }

public TimeSpan Timeout { get; set; }
= TimeSpan.Zero;
public TimeSpan? Timeout { get; set; }

public Dictionary<string, string> Headers { get; set; } = new();

public Uri Proxy { get; set; }
public Uri? Proxy { get; set; }

public object Payload { get; set; }
public object? Payload { get; set; }

public ContentType ContentType { get; set; }
public ContentType ContentType { get; set; } = ContentType.Raw;

public string DownloadFileName { get; set; }
public string? DownloadFileName { get; set; }

public Encoding ResponseEncoding { get; set; }
public Encoding? ResponseEncoding { get; set; }

public HttpCompletionOption HttpCompletionOption { get; set; } = HttpCompletionOption.ResponseContentRead;

public bool ReadBody { get; set; } = true;

private static AsyncLocal<TestingMode> testingMode = new();

public HttpRequest()
{
}
private static readonly AsyncLocal<TestingMode> TestingMode = new();

public HttpRequest(Uri uri)
{
Expand All @@ -62,7 +51,7 @@ public HttpRequest(string url)

public async Task<IHttpResponse> SendAsync(CancellationToken cancellationToken = default)
{
if (testingMode.Value != null)
if (TestingMode.Value != null)
{
return await MockedResponse().ConfigureAwait(false);
}
Expand Down Expand Up @@ -94,9 +83,9 @@ public async Task<IHttpResponse> SendAsync(CancellationToken cancellationToken =
var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

// Enable timeout, if set
if (this.Timeout != TimeSpan.Zero)
if (this.Timeout != default)
{
cts.CancelAfter(this.Timeout);
cts.CancelAfter(this.Timeout.Value);
}

Stopwatch stopwatch = Stopwatch.StartNew();
Expand All @@ -106,22 +95,22 @@ public async Task<IHttpResponse> SendAsync(CancellationToken cancellationToken =
// Serialize the payload
if (this.Payload != null)
{
if (this.ContentType == ContentType.Json)
{
SerializeToJson(requestMessage);
}
else if (this.ContentType == ContentType.Xml)
{
SerializeToXml(requestMessage);
}
else if (this.ContentType == ContentType.UrlEncoded)
{
SerializeToUrlEncoded(requestMessage);
}
// Raw
else
switch (this.ContentType)
{
requestMessage.Content = new StringContent(this.Payload.ToString());
case ContentType.Json:
SerializeToJson(requestMessage);
break;
case ContentType.Xml:
SerializeToXml(requestMessage);
break;
case ContentType.UrlEncoded:
SerializeToUrlEncoded(requestMessage);
break;
case ContentType.Raw:
requestMessage.Content = new StringContent(this.Payload.ToString()!);
break;
default:
throw new ArgumentException($"Unknown content type: {this.ContentType}");
}
}

Expand All @@ -132,7 +121,7 @@ public async Task<IHttpResponse> SendAsync(CancellationToken cancellationToken =

// Wrap the content into an HttpResponse instance,
// also reading the body (string or file), if requested
IHttpResponse response = await CreateHttpResponse(responseMessage).ConfigureAwait(false);
HttpResponse response = await CreateHttpResponse(responseMessage).ConfigureAwait(false);

response.ElapsedTime = stopwatch.Elapsed;

Expand All @@ -149,12 +138,12 @@ public async Task<IHttpResponse> SendAsync(CancellationToken cancellationToken =
}
}

private async Task<IHttpResponse> CreateHttpResponse(HttpResponseMessage responseMessage)
private async Task<HttpResponse> CreateHttpResponse(HttpResponseMessage responseMessage)
{
// No file name given, read the body of the response as a string
if (this.DownloadFileName == null)
{
IHttpResponse response = new HttpResponse(this, responseMessage);
HttpResponse response = new HttpResponse(this, responseMessage);

if (this.ReadBody)
{
Expand All @@ -166,8 +155,8 @@ private async Task<IHttpResponse> CreateHttpResponse(HttpResponseMessage respons
// Copy the response to a file
else
{
using (Stream stream = await responseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false))
using (FileStream fs = new FileStream(this.DownloadFileName, FileMode.Create, FileAccess.Write))
await using (Stream stream = await responseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false))
await using (FileStream fs = new FileStream(this.DownloadFileName, FileMode.Create, FileAccess.Write))
{
await stream.CopyToAsync(fs).ConfigureAwait(false);
}
Expand All @@ -179,18 +168,18 @@ private async Task<IHttpResponse> CreateHttpResponse(HttpResponseMessage respons
private async Task<IHttpResponse> MockedResponse()
{
// Get the testing mode instance for this async context
HttpResponseMessage message = testingMode.Value.RequestsQueue.Dequeue();
HttpResponseMessage message = TestingMode.Value!.RequestsQueue.Dequeue();

return await CreateHttpResponse(message).ConfigureAwait(false);
}

private void SerializeToUrlEncoded(HttpRequestMessage requestMessage)
{
// Already serialized
if (this.Payload is string)
if (this.Payload is string stringPayload)
{
requestMessage.Content = new StringContent(
content: this.Payload.ToString(),
content: stringPayload,
encoding: Encoding.UTF8,
mediaType: "application/x-www-form-urlencoded"
);
Expand Down Expand Up @@ -219,13 +208,13 @@ private void SerializeToXml(HttpRequestMessage requestMessage)
string serialized;

// Already serialized
if (this.Payload is string)
if (this.Payload is string stringPayload)
{
serialized = this.Payload.ToString();
serialized = stringPayload;
}
else
{
XmlSerializer serializer = new XmlSerializer(this.Payload.GetType());
XmlSerializer serializer = new XmlSerializer(this.Payload!.GetType());
StringBuilder result = new StringBuilder();

using (var writer = XmlWriter.Create(result))
Expand All @@ -248,9 +237,9 @@ private void SerializeToJson(HttpRequestMessage requestMessage)
string serialized;

// Already serialized
if (this.Payload is string)
if (this.Payload is string stringPayload)
{
serialized = this.Payload.ToString();
serialized = stringPayload;
}
else
{
Expand All @@ -271,6 +260,6 @@ public override string ToString()

public static void SetTestingMode(TestingMode t)
{
testingMode.Value = t;
TestingMode.Value = t;
}
}
4 changes: 1 addition & 3 deletions PlainHttp/HttpRequestException.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System;

namespace PlainHttp;
namespace PlainHttp;

public class HttpRequestException : Exception
{
Expand Down
4 changes: 1 addition & 3 deletions PlainHttp/HttpRequestTimeoutException.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System;

namespace PlainHttp;
namespace PlainHttp;

public class HttpRequestTimeoutException : HttpRequestException
{
Expand Down
38 changes: 10 additions & 28 deletions PlainHttp/HttpResponse.cs
Original file line number Diff line number Diff line change
@@ -1,41 +1,23 @@
using System;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Diagnostics;

namespace PlainHttp;

public class HttpResponse : IHttpResponse, IDisposable
{
public HttpResponseMessage Message { get; set; }
public HttpRequest Request { get; init; }
public HttpResponseMessage Message { get; init; }
public string? Body { get; private set; }
public bool Succeeded => this.Message.IsSuccessStatusCode;

public string Body { get; set; }

public HttpRequest Request { get; set; }

public bool Succeeded
{
get { return this.Message.IsSuccessStatusCode; }
}

public TimeSpan ElapsedTime { get; set; }
public TimeSpan ElapsedTime { get; internal set; }

public HttpResponse(HttpRequest request, HttpResponseMessage message)
{
this.Request = request;
this.Message = message;
}

public HttpResponse(HttpRequest request, HttpResponseMessage message, string body)
: this(request, message)
{
this.Request = request;
this.Message = message;
this.Body = body;
}

public string GetSingleHeader(string name)
public string? GetSingleHeader(string name)
{
if (this.Message.Headers.TryGetValues(name, out var values) ||
this.Message.Content.Headers.TryGetValues(name, out values))
Expand All @@ -50,12 +32,12 @@ public string GetSingleHeader(string name)

public async Task ReadBody()
{
if (Body != null)
if (this.Body != null)
{
return;
}

Stopwatch stopwatch = null;
Stopwatch? stopwatch = null;
TimeSpan newTimeout = default;

// If the HttpCompletionOption is set to ResponseHeadersRead,
Expand All @@ -68,7 +50,7 @@ public async Task ReadBody()
if (this.Request.Timeout != default)
{
// Calculate how much time we have left
newTimeout = this.Request.Timeout - this.ElapsedTime;
newTimeout = this.Request.Timeout.Value - this.ElapsedTime;
}
}

Expand Down
5 changes: 1 addition & 4 deletions PlainHttp/IHttpClientFactory.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using System;
using System.Net.Http;

namespace PlainHttp;
namespace PlainHttp;

public interface IHttpClientFactory
{
Expand Down
18 changes: 6 additions & 12 deletions PlainHttp/IHttpRequest.cs
Original file line number Diff line number Diff line change
@@ -1,21 +1,15 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace PlainHttp;
namespace PlainHttp;

public interface IHttpRequest
{
ContentType ContentType { get; set; }
string DownloadFileName { get; set; }
string? DownloadFileName { get; set; }
Dictionary<string, string> Headers { get; set; }
HttpRequestMessage Message { get; }
HttpRequestMessage? Message { get; }
HttpMethod Method { get; set; }
object Payload { get; set; }
Uri Proxy { get; set; }
TimeSpan Timeout { get; set; }
object? Payload { get; set; }
Uri? Proxy { get; set; }
TimeSpan? Timeout { get; set; }
Uri Uri { get; set; }
HttpCompletionOption HttpCompletionOption { get; set; }
bool ReadBody { get; set; }
Expand Down
16 changes: 6 additions & 10 deletions PlainHttp/IHttpResponse.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
using System;
using System.Net.Http;
using System.Threading.Tasks;

namespace PlainHttp;
namespace PlainHttp;

public interface IHttpResponse
{
string Body { get; set; }
HttpResponseMessage Message { get; set; }
HttpRequest Request { get; set; }
HttpRequest Request { get; }
HttpResponseMessage Message { get; }
string? Body { get; }
bool Succeeded { get; }
TimeSpan ElapsedTime { get; set; }
TimeSpan ElapsedTime { get; }

string GetSingleHeader(string name);
string? GetSingleHeader(string name);
Task ReadBody();
}
Loading

0 comments on commit bf727f7

Please sign in to comment.