ReverseProxyMiddleware.cs 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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"?
  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. var scheme = context.Request.Scheme;
  46. var destinationPrefix = GetDestinationPrefix(scheme, host, domainConfig.Destination);
  47. var httpClient = this.httpClientFactory.CreateHttpClient(domainConfig);
  48. var error = await httpForwarder.SendAsync(context, destinationPrefix, httpClient);
  49. await HandleErrorAsync(context, error);
  50. }
  51. else
  52. {
  53. context.Response.StatusCode = domainConfig.Response.StatusCode;
  54. context.Response.ContentType = domainConfig.Response.ContentType;
  55. if (domainConfig.Response.ContentValue != null)
  56. {
  57. await context.Response.WriteAsync(domainConfig.Response.ContentValue);
  58. }
  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 || context.Response.HasStarted)
  89. {
  90. return;
  91. }
  92. await context.Response.WriteAsJsonAsync(new
  93. {
  94. error = error.ToString(),
  95. message = context.GetForwarderErrorFeature()?.Exception?.Message
  96. });
  97. }
  98. }
  99. }