/unix-socket-use-case-ctrlx.cs Secret
Last active
February 2, 2022 13:45
Star
You must be signed in to star a gist
Sample how to access services on ctrlX CORE via Unix Domain Sockets
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
internal interface ICtrlXLicenseApi | |
{ | |
[Post("/license-manager/api/v1/license")] | |
Task<ApiResponse<AcquiredLicense>> AcquireLicense([Body] AcquireLicenseRequestBody body); | |
} | |
public class Startup | |
{ | |
// More startup related code... | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
var settings = new RefitSettings(new SystemTextJsonContentSerializer(new JsonSerializerOptions | |
{ | |
PropertyNameCaseInsensitive = true | |
})); | |
services | |
.AddRefitClient<ICtrlXLicenseApi>(settings) | |
.ConfigurePrimaryHttpMessageHandler((sp) => | |
{ | |
var configuration = sp.GetRequiredService<IConfiguration>(); | |
var snapDataFolder = configuration.GetValue<string>("SNAP_DATA"); | |
return new SocketsHttpHandler | |
{ | |
ConnectCallback = async (_, cancellationToken) => | |
{ | |
var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified); | |
var endpoint = new UnixDomainSocketEndPoint($"{snapDataFolder}/licensing-service/licensing-service.sock"); | |
await socket.ConnectAsync(endpoint, cancellationToken).ConfigureAwait(false); | |
return new NetworkStream(socket, ownsSocket: false); | |
} | |
}; | |
}) | |
.ConfigureHttpClient((sp, httpClient) => | |
{ | |
httpClient.BaseAddress = new Uri("http://localhost"); | |
}); | |
} | |
// More startup related code... | |
} | |
internal sealed class CtrlXLicenseValidator | |
{ | |
private readonly ICtrlXLicenseApi _service; | |
private AcquiredLicense _acquiredLicense; | |
public CtrlXLicenseValidator(ICtrlXLicenseApi service) | |
{ | |
_service = service; | |
} | |
public async Task<bool> AcquireLicenseAsync() | |
{ | |
try | |
{ | |
var body = new AcquireLicenseRequestBody | |
{ | |
Name = "CapabilityName", | |
Version = "CapabilityVersion" | |
}; | |
var response = await _service.AcquireLicense(body).ConfigureAwait(false); | |
if (!response.IsSuccessStatusCode || response.Content is null) | |
{ | |
return false; | |
} | |
_acquiredLicense = response.Content; | |
return true; | |
} | |
catch | |
{ | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment