From 5b6525a26eb0d80653779b7b239831677f7dac73 Mon Sep 17 00:00:00 2001 From: Serhii Kozlov Date: Sat, 5 Jul 2025 22:39:06 +0200 Subject: [PATCH] Add support for listening on unix socket Imaginary is often used locally, and using unix socket: - Makes it easier to control access - Reduces transport overhead --- imaginary.go | 4 ++++ server.go | 9 +++++++++ 2 files changed, 13 insertions(+) diff --git a/imaginary.go b/imaginary.go index b46f86d9..e91158be 100644 --- a/imaginary.go +++ b/imaginary.go @@ -18,6 +18,7 @@ import ( var ( aAddr = flag.String("a", "", "Bind address") + aUnixSocket = flag.String("unix-socket", "", "Path to the unix socket to listen on. If specified - address and port flags are ignored") aPort = flag.Int("p", 8088, "Port to listen") aVers = flag.Bool("v", false, "Show version") aVersl = flag.Bool("version", false, "Show version") @@ -58,6 +59,7 @@ const usage = `imaginary %s Usage: imaginary -p 80 + imaginary -unix-socket /var/run/imaginary.sock imaginary -cors imaginary -concurrency 10 imaginary -path-prefix /api/v1 @@ -76,6 +78,7 @@ Usage: Options: -a Bind address [default: *] + -unix-socket Path to the unix socket to listen on. If specified - address and port flags are ignored -p Bind port [default: 8088] -h, -help Show help -v, -version Show version @@ -138,6 +141,7 @@ func main() { opts := ServerOptions{ Port: port, Address: *aAddr, + UnixSocket: *aUnixSocket, CORS: *aCors, AuthForwarding: *aAuthForwarding, EnableURLSource: *aEnableURLSource, diff --git a/server.go b/server.go index f3a17d73..4734cddd 100644 --- a/server.go +++ b/server.go @@ -3,6 +3,7 @@ package main import ( "context" "log" + "net" "net/http" "net/url" "os" @@ -17,6 +18,7 @@ import ( type ServerOptions struct { Port int Burst int + UnixSocket string Concurrency int HTTPCacheTTL int HTTPReadTimeout int @@ -98,6 +100,13 @@ func Server(o ServerOptions) { } func listenAndServe(s *http.Server, o ServerOptions) error { + if o.UnixSocket != "" { + listener, err := net.Listen("unix", o.UnixSocket) + if err != nil { + return err + } + return s.Serve(listener) + } if o.CertFile != "" && o.KeyFile != "" { return s.ListenAndServeTLS(o.CertFile, o.KeyFile) }