Skip to content

Commit

Permalink
Make possible to use non-root consul urls (#333)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcin-krystianc committed Jul 17, 2024
1 parent b24dd66 commit ef310c2
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 25 deletions.
26 changes: 22 additions & 4 deletions Consul.Test/ClientTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
// -----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
Expand All @@ -31,10 +32,12 @@ namespace Consul.Test
[Collection(nameof(ExclusiveCollection))]
public class ClientTest : BaseFixture
{
[Fact]
public void Client_DefaultConfig_env()
[Theory]
[InlineData("1.2.3.4:5678", "https://1.2.3.4:5678/")]
[InlineData("1.2.3.4:5678/sub-path", "https://1.2.3.4:5678/sub-path")]
[InlineData("http://1.2.3.4:5678/sub-path", "https://1.2.3.4:5678/sub-path")]
public void Client_DefaultConfig_env(string addr, string expected)
{
const string addr = "1.2.3.4:5678";
const string token = "abcd1234";
const string auth = "username:password";

Expand All @@ -55,7 +58,7 @@ public void Client_DefaultConfig_env()
var client = new ConsulClient();
var config = client.Config;

Assert.Equal(addr, string.Format("{0}:{1}", config.Address.Host, config.Address.Port));
Assert.Equal(expected, config.Address.ToString());
Assert.Equal(token, config.Token);
#pragma warning disable CS0618 // Type or member is obsolete
Assert.NotNull(config.HttpAuth);
Expand Down Expand Up @@ -151,6 +154,21 @@ await Assert.ThrowsAsync<ConsulRequestException>(async () =>
Assert.Equal("1m40s", request.Params["wait"]);
}
}

[Fact]
public void Client_NonRootUri()
{
using (var client = new ConsulClient(c =>
{
c.Address = new Uri("http://127.0.0.1:1234/my-subpath");
}))
{
var request = client.Get<KVPair>("/v1/kv/foo");
var uri = request.BuildConsulUri("/v1/kv/foo", new Dictionary<string, string>());
Assert.Equal("http://127.0.0.1:1234/my-subpath/v1/kv/foo", uri.AbsoluteUri);
}
}

[Fact]
public async Task Client_SetWriteOptions()
{
Expand Down
25 changes: 9 additions & 16 deletions Consul/Client.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,26 +164,19 @@ private void ConfigureFromEnvironment(UriBuilder consulAddress)
var envAddr = (Environment.GetEnvironmentVariable("CONSUL_HTTP_ADDR") ?? string.Empty).Trim().ToLowerInvariant();
if (!string.IsNullOrEmpty(envAddr))
{
var addrParts = envAddr.Split(':');
for (int i = 0; i < addrParts.Length; i++)
if (!Uri.TryCreate(envAddr, UriKind.Absolute, out Uri uri))
{
addrParts[i] = addrParts[i].Trim();
// If the URI cannot be parsed it probably lacks the schema, use http as a default
uri = new Uri($"http://{envAddr}");
}
if (!string.IsNullOrEmpty(addrParts[0]))
{
consulAddress.Host = addrParts[0];
}
if (addrParts.Length > 1 && !string.IsNullOrEmpty(addrParts[1]))

if (!string.IsNullOrEmpty(uri.Host))
{
try
{
consulAddress.Port = ushort.Parse(addrParts[1]);
}
catch (Exception ex)
{
throw new ConsulConfigurationException("Failed parsing port from environment variable CONSUL_HTTP_ADDR", ex);
}
consulAddress.Host = uri.Host;
}

consulAddress.Port = uri.Port;
consulAddress.Path = uri.AbsolutePath;
}

var useSsl = (Environment.GetEnvironmentVariable("CONSUL_HTTP_SSL") ?? string.Empty).Trim().ToLowerInvariant();
Expand Down
9 changes: 4 additions & 5 deletions Consul/Client_Request.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,11 @@ internal ConsulRequest(ConsulClient client, string url, HttpMethod method)
protected abstract void ApplyOptions(ConsulClientConfiguration clientConfig);
protected abstract void ApplyHeaders(HttpRequestMessage message, ConsulClientConfiguration clientConfig);

protected Uri BuildConsulUri(string url, Dictionary<string, string> p)
protected internal Uri BuildConsulUri(string url, Dictionary<string, string> p)
{
var builder = new UriBuilder(Client.Config.Address)
{
Path = url
};
var builder = new UriBuilder(Client.Config.Address);
builder.Path += url;
builder.Path = builder.Path.Replace("//", "/");

ApplyOptions(Client.Config);

Expand Down

0 comments on commit ef310c2

Please sign in to comment.