Last active
March 10, 2017 17:27
-
-
Save AnthonySteele/8174e97ce815889154ccdef20633cb85 to your computer and use it in GitHub Desktop.
EndpointData
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Net; | |
namespace JustEat.StatsD.EndpointLookups | |
{ | |
public class EndpointData | |
{ | |
private readonly IPEndPoint _ipEndpoint; | |
private readonly string _hostName; | |
private readonly int _port; | |
public EndpointData(string hostNameOrAddress, int port) | |
{ | |
IPAddress address; | |
if (IPAddress.TryParse(hostNameOrAddress, out address)) | |
{ | |
//if we were given an IP instead of a hostname, | |
//we can happily cache it off for the life of this class | |
_ipEndpoint = new IPEndPoint(address, _port); | |
_hostName = null; | |
_port = 0; | |
} | |
else | |
{ | |
_hostName = hostNameOrAddress; | |
_port = port; | |
_ipEndpoint = null; | |
} | |
} | |
// todo- decide | |
// inject the IDnsEndpointMapper here or constructor?, | |
// or fold that code in here? | |
// this might need to be async as there is a ".Result" inside GetIPEndPoint | |
public IPEndPoint GetEndpoint(IDnsEndpointMapper mapper) | |
{ | |
if (_ipEndpoint != null) | |
{ | |
return _ipEndpoint; | |
} | |
// Only DNS resolve if we were given a hostname | |
return mapper.GetIPEndPoint(_hostName, _port); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// the functional approach is less code. | |
// and it only closes over the parts that it uses | |
// what you need is a way to get the IPEndPoint as it is now, | |
// so this can be typed as Func<IPEndPoint>, i.e. an IPEndPoint factory. | |
// and a factory to build that factory | |
public static class EnpointFactoryFactory | |
{ | |
public static Func<IPEndPoint> ManufactureEndpointFactory(string hostNameOrAddress, int port, IDnsEndpointMapper mapper) | |
{ | |
IPAddress address; | |
if (IPAddress.TryParse(hostNameOrAddress, out address)) | |
{ | |
//if we were given an IP instead of a hostname, | |
//we can happily cache it off for the life of this class | |
var ipEndpoint = new IPEndPoint(address, port); | |
return () => ipEndpoint; | |
} | |
// Only DNS resolve if we were given a hostname | |
// still have the problem that the "GetIPEndPoint" is potentially async | |
return () => mapper.GetIPEndPoint(hostNameOrAddress, port); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment