ReverseProxyMiddleware.cs 3.8 KB

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