ReverseProxyMiddleware.cs 3.7 KB

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