ReverseProxyMiddleware.cs 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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 httpClient = new HttpClient(this.httpClientHanlder, false, domainConfig.TlsSni);
  56. var error = await httpForwarder.SendAsync(context, destinationPrefix, httpClient, requestConfig);
  57. await ResponseErrorAsync(context, error);
  58. }
  59. }
  60. /// <summary>
  61. /// 获取目标前缀
  62. /// </summary>
  63. /// <param name="host"></param>
  64. /// <param name="destination"></param>
  65. /// <returns></returns>
  66. private string GetDestinationPrefix(string host, Uri? destination)
  67. {
  68. var defaultValue = $"https://{host}/";
  69. if (destination == null)
  70. {
  71. return defaultValue;
  72. }
  73. var baseUri = new Uri(defaultValue);
  74. var result = new Uri(baseUri, destination).ToString();
  75. this.logger.LogInformation($"[{defaultValue}->{result}]");
  76. return result;
  77. }
  78. /// <summary>
  79. /// 写入错误信息
  80. /// </summary>
  81. /// <param name="context"></param>
  82. /// <param name="error"></param>
  83. /// <returns></returns>
  84. private static async Task ResponseErrorAsync(HttpContext context, ForwarderError error)
  85. {
  86. if (error == ForwarderError.None)
  87. {
  88. return;
  89. }
  90. var errorFeature = context.GetForwarderErrorFeature();
  91. if (errorFeature == null)
  92. {
  93. return;
  94. }
  95. await context.Response.WriteAsJsonAsync(new
  96. {
  97. error = error.ToString(),
  98. message = errorFeature.Exception?.Message
  99. });
  100. }
  101. }
  102. }