forked from shiftwinting/FastGithub
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
using Microsoft.Extensions.Logging; | ||
using Microsoft.Extensions.Options; | ||
using System; | ||
using System.Linq; | ||
using System.Net.Http; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
|
||
namespace FastGithub.Middlewares | ||
{ | ||
sealed class HttpsScanMiddleware : IGithubMiddleware | ||
{ | ||
private readonly IOptionsMonitor<GithubOptions> options; | ||
private readonly ILogger<HttpsScanMiddleware> logger; | ||
|
||
public HttpsScanMiddleware( | ||
IOptionsMonitor<GithubOptions> options, | ||
ILogger<HttpsScanMiddleware> logger) | ||
{ | ||
this.options = options; | ||
this.logger = logger; | ||
} | ||
|
||
public async Task InvokeAsync(GithubContext context, Func<Task> next) | ||
{ | ||
try | ||
{ | ||
var request = new HttpRequestMessage | ||
{ | ||
Method = HttpMethod.Get, | ||
RequestUri = new Uri($"https://{context.Address}"), | ||
}; | ||
request.Headers.Host = context.Domain; | ||
|
||
using var httpClient = new HttpClient(new HttpClientHandler | ||
{ | ||
Proxy = null, | ||
UseProxy = false, | ||
ServerCertificateCustomValidationCallback = (_, _, _, _) => true | ||
}); | ||
|
||
var startTime = DateTime.Now; | ||
using var cancellationTokenSource = new CancellationTokenSource(this.options.CurrentValue.HttpsScanTimeout); | ||
var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationTokenSource.Token); | ||
var server = response.EnsureSuccessStatusCode().Headers.Server; | ||
if (server.Any(s => string.Equals("GitHub.com", s.Product?.Name, StringComparison.OrdinalIgnoreCase))) | ||
{ | ||
context.HttpElapsed = DateTime.Now.Subtract(startTime); | ||
this.logger.LogWarning(context.ToString()); | ||
|
||
await next(); | ||
} | ||
} | ||
catch (TaskCanceledException) | ||
{ | ||
this.logger.LogInformation($"{context.Domain} {context.Address}连接超时"); | ||
} | ||
catch (Exception ex) | ||
{ | ||
this.logger.LogInformation($"{context.Domain} {context.Address} {ex.Message}"); | ||
} | ||
} | ||
} | ||
} |