ReverseProxyMiddleware.cs 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. using FastGithub.Configuration;
  2. using FastGithub.Http;
  3. using Microsoft.AspNetCore.Http;
  4. using Microsoft.Extensions.Logging;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Threading.Tasks;
  8. using Yarp.ReverseProxy.Forwarder;
  9. namespace FastGithub.ReverseProxy
  10. {
  11. /// <summary>
  12. /// 反向代理中间件
  13. /// </summary>
  14. sealed class ReverseProxyMiddleware
  15. {
  16. private readonly IHttpForwarder httpForwarder;
  17. private readonly IHttpClientFactory httpClientFactory;
  18. private readonly FastGithubConfig fastGithubConfig;
  19. private readonly ILogger<ReverseProxyMiddleware> logger;
  20. private readonly HashSet<string> localHostNames = LocalMachine.GetAllHostNames();
  21. private readonly DomainConfig defaultDomainConfig = new() { TlsSni = true };
  22. public ReverseProxyMiddleware(
  23. IHttpForwarder httpForwarder,
  24. IHttpClientFactory httpClientFactory,
  25. FastGithubConfig fastGithubConfig,
  26. ILogger<ReverseProxyMiddleware> logger)
  27. {
  28. this.httpForwarder = httpForwarder;
  29. this.httpClientFactory = httpClientFactory;
  30. this.fastGithubConfig = fastGithubConfig;
  31. this.logger = logger;
  32. }
  33. /// <summary>
  34. /// 处理请求
  35. /// </summary>
  36. /// <param name="context"></param>
  37. /// <param name="next"?
  38. /// <returns></returns>
  39. public async Task InvokeAsync(HttpContext context, RequestDelegate next)
  40. {
  41. var host = context.Request.Host.Host;
  42. if (this.localHostNames.Contains(host) == true)
  43. {
  44. await next(context);
  45. return;
  46. }
  47. if (this.fastGithubConfig.TryGetDomainConfig(host, out var domainConfig) == false)
  48. {
  49. domainConfig = this.defaultDomainConfig;
  50. }
  51. if (domainConfig.Response == null)
  52. {
  53. var scheme = context.Request.Scheme;
  54. var destinationPrefix = GetDestinationPrefix(scheme, host, domainConfig.Destination);
  55. var httpClient = this.httpClientFactory.CreateHttpClient(domainConfig);
  56. var error = await httpForwarder.SendAsync(context, destinationPrefix, httpClient);
  57. await HandleErrorAsync(context, error);
  58. }
  59. else
  60. {
  61. context.Response.StatusCode = domainConfig.Response.StatusCode;
  62. context.Response.ContentType = domainConfig.Response.ContentType;
  63. if (domainConfig.Response.ContentValue != null)
  64. {
  65. await context.Response.WriteAsync(domainConfig.Response.ContentValue);
  66. }
  67. }
  68. }
  69. /// <summary>
  70. /// 获取目标前缀
  71. /// </summary>
  72. /// <param name="scheme"></param>
  73. /// <param name="host"></param>
  74. /// <param name="destination"></param>
  75. /// <returns></returns>
  76. private string GetDestinationPrefix(string scheme, string host, Uri? destination)
  77. {
  78. var defaultValue = $"{scheme}://{host}/";
  79. if (destination == null)
  80. {
  81. return defaultValue;
  82. }
  83. var baseUri = new Uri(defaultValue);
  84. var result = new Uri(baseUri, destination).ToString();
  85. this.logger.LogInformation($"[{defaultValue} <-> {result}]");
  86. return result;
  87. }
  88. /// <summary>
  89. /// 处理错误信息
  90. /// </summary>
  91. /// <param name="context"></param>
  92. /// <param name="error"></param>
  93. /// <returns></returns>
  94. private static async Task HandleErrorAsync(HttpContext context, ForwarderError error)
  95. {
  96. if (error == ForwarderError.None || context.Response.HasStarted)
  97. {
  98. return;
  99. }
  100. await context.Response.WriteAsJsonAsync(new
  101. {
  102. error = error.ToString(),
  103. message = context.GetForwarderErrorFeature()?.Exception?.Message
  104. });
  105. }
  106. }
  107. }