Created
January 28, 2022 17:24
-
-
Save fzankl/777406e655266eac70e114e4d3509bf8 to your computer and use it in GitHub Desktop.
Request API over unix socket using .NET 6 minimal API and Refit
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.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