downstreambaseurl placeholder for multiple location value redirects (#207)

This commit is contained in:
Tom Pallister
2018-01-27 20:03:49 +00:00
committed by GitHub
parent d0eee70c46
commit f572d1b0ca
8 changed files with 265 additions and 10 deletions

View File

@ -1,22 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using Ocelot.Configuration;
using Ocelot.Infrastructure.Extensions;
using Ocelot.Responses;
namespace Ocelot.Headers
{
public class HttpResponseHeaderReplacer : IHttpResponseHeaderReplacer
{
public Response Replace(HttpResponseMessage response, List<HeaderFindAndReplace> fAndRs)
private Dictionary<string, Func<HttpRequestMessage, string>> _placeholders;
public HttpResponseHeaderReplacer()
{
_placeholders = new Dictionary<string, Func<HttpRequestMessage, string>>();
_placeholders.Add("{DownstreamBaseUrl}", x => {
var downstreamUrl = $"{x.RequestUri.Scheme}://{x.RequestUri.Host}";
if(x.RequestUri.Port != 80 && x.RequestUri.Port != 443)
{
downstreamUrl = $"{downstreamUrl}:{x.RequestUri.Port}";
}
return $"{downstreamUrl}/";
});
}
public Response Replace(HttpResponseMessage response, List<HeaderFindAndReplace> fAndRs, HttpRequestMessage httpRequestMessage)
{
foreach (var f in fAndRs)
{
//if the response headers contain a matching find and replace
if(response.Headers.TryGetValues(f.Key, out var values))
{
var replaced = values.ToList()[f.Index].Replace(f.Find, f.Replace);
response.Headers.Remove(f.Key);
response.Headers.Add(f.Key, replaced);
//check to see if it is a placeholder in the find...
if(_placeholders.TryGetValue(f.Find, out var replacePlaceholder))
{
//if it is we need to get the value of the placeholder
var find = replacePlaceholder(httpRequestMessage);
var replaced = values.ToList()[f.Index].Replace(find, f.Replace.LastCharAsForwardSlash());
response.Headers.Remove(f.Key);
response.Headers.Add(f.Key, replaced);
}
else
{
var replaced = values.ToList()[f.Index].Replace(f.Find, f.Replace);
response.Headers.Remove(f.Key);
response.Headers.Add(f.Key, replaced);
}
}
}

View File

@ -7,6 +7,6 @@ namespace Ocelot.Headers
{
public interface IHttpResponseHeaderReplacer
{
Response Replace(HttpResponseMessage response, List<HeaderFindAndReplace> fAndRs);
Response Replace(HttpResponseMessage response, List<HeaderFindAndReplace> fAndRs, HttpRequestMessage httpRequestMessage);
}
}

View File

@ -36,7 +36,7 @@ namespace Ocelot.Headers.Middleware
var postFAndRs = this.DownstreamRoute.ReRoute.DownstreamHeadersFindAndReplace;
_postReplacer.Replace(HttpResponseMessage, postFAndRs);
_postReplacer.Replace(HttpResponseMessage, postFAndRs, DownstreamRequest);
}
}
}

View File

@ -20,5 +20,14 @@ namespace Ocelot.Infrastructure.Extensions
return s;
}
public static string LastCharAsForwardSlash(this string source)
{
if(source.EndsWith('/'))
{
return source;
}
return $"{source}/";
}
}
}