Skip to content

Instantly share code, notes, and snippets.

@fzankl
Created January 28, 2022 17:24
Show Gist options
  • Save fzankl/777406e655266eac70e114e4d3509bf8 to your computer and use it in GitHub Desktop.
Save fzankl/777406e655266eac70e114e4d3509bf8 to your computer and use it in GitHub Desktop.
Request API over unix socket using .NET 6 minimal API and Refit
using System.Net.Sockets;
using Refit;
const string BaseAddress = "http://localhost";
const string UnixSocketPath = "/tmp/foo.sock";
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddRefitClient<IFooApi>()
.ConfigurePrimaryHttpMessageHandler((_) =>
{
return new SocketsHttpHandler
{
ConnectCallback = async (_, _) =>
{
var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
var endpoint = new UnixDomainSocketEndPoint(UnixSocketPath);
await socket.ConnectAsync(endpoint).ConfigureAwait(false);
return new NetworkStream(socket, ownsSocket: false);
}
};
})
.ConfigureHttpClient((_, client) =>
{
client.BaseAddress = new Uri(BaseAddress);
});
var app = builder.Build();
app.MapGet("/", (IFooApi fooApi) =>
{
return fooApi.GetFoo();
});
app.Run();
internal interface IFooApi
{
[Get("/")]
Task<string> GetFoo();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment