ReverseProxyMiddleware.cs 3.9 KB

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