Skip to content

Instantly share code, notes, and snippets.

@fzankl
Last active February 2, 2022 13:45
Show Gist options
  • Save fzankl/806b77cf6d07dd28ba7313f110d82146 to your computer and use it in GitHub Desktop.
Save fzankl/806b77cf6d07dd28ba7313f110d82146 to your computer and use it in GitHub Desktop.
Sample how to access services on ctrlX CORE via Unix Domain Sockets
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