HttpProxyPacMiddleware.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using FastGithub.Configuration;
  2. using FastGithub.HttpServer.TcpMiddlewares;
  3. using Microsoft.AspNetCore.Http;
  4. using System.IO;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace FastGithub.HttpServer.HttpMiddlewares
  8. {
  9. /// <summary>
  10. /// http代理策略中间件
  11. /// </summary>
  12. sealed class HttpProxyPacMiddleware
  13. {
  14. private readonly FastGithubConfig fastGithubConfig;
  15. /// <summary>
  16. /// http代理策略中间件
  17. /// </summary>
  18. /// <param name="fastGithubConfig"></param>
  19. public HttpProxyPacMiddleware(FastGithubConfig fastGithubConfig)
  20. {
  21. this.fastGithubConfig = fastGithubConfig;
  22. }
  23. /// <summary>
  24. /// 处理请求
  25. /// </summary>
  26. /// <param name="context"></param>
  27. /// <param name="next"></param>
  28. /// <returns></returns>
  29. public async Task InvokeAsync(HttpContext context, RequestDelegate next)
  30. {
  31. // http请求经过了httpProxy中间件
  32. var proxyFeature = context.Features.Get<IHttpProxyFeature>();
  33. if (proxyFeature != null && proxyFeature.ProxyProtocol == ProxyProtocol.None)
  34. {
  35. var proxyPac = this.CreateProxyPac(context.Request.Host);
  36. context.Response.ContentType = "application/x-ns-proxy-autoconfig";
  37. context.Response.Headers.Add("Content-Disposition", $"attachment;filename=proxy.pac");
  38. await context.Response.WriteAsync(proxyPac);
  39. }
  40. else
  41. {
  42. await next(context);
  43. }
  44. }
  45. /// <summary>
  46. /// 创建proxypac脚本
  47. /// </summary>
  48. /// <param name="proxyHost"></param>
  49. /// <returns></returns>
  50. private string CreateProxyPac(HostString proxyHost)
  51. {
  52. var buidler = new StringBuilder();
  53. buidler.AppendLine("function FindProxyForURL(url, host){");
  54. buidler.AppendLine($" var fastgithub = 'PROXY {proxyHost}';");
  55. foreach (var domain in fastGithubConfig.GetDomainPatterns())
  56. {
  57. buidler.AppendLine($" if (shExpMatch(host, '{domain}')) return fastgithub;");
  58. }
  59. buidler.AppendLine(" return 'DIRECT';");
  60. buidler.AppendLine("}");
  61. return buidler.ToString();
  62. }
  63. }
  64. }