-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06_Testing.cs
More file actions
92 lines (80 loc) · 3.34 KB
/
06_Testing.cs
File metadata and controls
92 lines (80 loc) · 3.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using ProxyKit.Testing;
namespace ProxyKit.Recipes
{
public class Testing
{
public async Task Run(CancellationToken cancellationToken)
{
var router = new RoutingMessageHandler();
// Build Proxy TestServer
var proxyWebHostBuilder = new WebHostBuilder()
.UseStartup<ProxyStartup>()
.ConfigureServices(services =>
{
// configure proxy to forward requests to the router
services.AddSingleton<Func<HttpMessageHandler>>(() => router);
})
.UseUrls("http://localhost:5000");
var proxyTestServer = new TestServer(proxyWebHostBuilder);
router.AddHandler("localhost", 5000, proxyTestServer.CreateHandler());
// Build Host1 TestServer
var host1WebHostBuilder = new WebHostBuilder()
.UseStartup<Program.HostStartup>()
.UseSetting("hostname", "HOST 1")
.UseUrls("http://localhost:5001");
var host1TestServer = new TestServer(host1WebHostBuilder);
router.AddHandler("localhost", 5001, host1TestServer.CreateHandler());
// Build Host2 TestServer
var host2WebHostBuilder = new WebHostBuilder()
.UseStartup<Program.HostStartup>()
.UseSetting("hostname", "HOST 2")
.UseUrls("http://localhost:5002");
var host2TestServer = new TestServer(host2WebHostBuilder);
router.AddHandler("localhost", 5002, host2TestServer.CreateHandler());
// Get HttpClient make a request to the proxy
var httpClient = new HttpClient(router);
var response = await httpClient.GetAsync("http://localhost:5000/", cancellationToken);
}
// The Proxy Startup that has a handler (the routing handler) injected.
public class ProxyStartup
{
private readonly Func<HttpMessageHandler> _createHandler;
public ProxyStartup(Func<HttpMessageHandler> createHandler)
{
_createHandler = createHandler;
}
public void ConfigureServices(IServiceCollection services)
{
// Set the primary handler to the injected handler
// so upstream requests are sent to the router
services.AddProxy(httpClientBuilder
=> httpClientBuilder.ConfigurePrimaryHttpMessageHandler(_createHandler));
}
public void Configure(IApplicationBuilder app)
{
var roundRobin = new RoundRobin
{
"http://localhost:5001",
"http://localhost:5002"
};
app.RunProxy(
context =>
{
var host = roundRobin.Next();
return context
.ForwardTo(host)
.AddXForwardedHeaders()
.Send();
});
}
}
}
}