about summary refs log tree commit diff stats
path: root/internal/listenfd
diff options
context:
space:
mode:
authorAlan Pearce2024-06-18 15:58:53 +0200
committerAlan Pearce2024-06-18 15:58:53 +0200
commita238c7e0889cbe7dfaa1a700dea30686a4e2139a (patch)
tree812878165bb8bdfe1f7fa28921b9ceae2e8fd45f /internal/listenfd
parentf69b6432cd1f921909b254c1adc93080e844f2f5 (diff)
downloadwebsite-a238c7e0889cbe7dfaa1a700dea30686a4e2139a.tar.lz
website-a238c7e0889cbe7dfaa1a700dea30686a4e2139a.tar.zst
website-a238c7e0889cbe7dfaa1a700dea30686a4e2139a.zip
extract socket passing protocol handler to package
Diffstat (limited to 'internal/listenfd')
-rw-r--r--internal/listenfd/listenfd.go33
1 files changed, 33 insertions, 0 deletions
diff --git a/internal/listenfd/listenfd.go b/internal/listenfd/listenfd.go
new file mode 100644
index 0000000..7d020b0
--- /dev/null
+++ b/internal/listenfd/listenfd.go
@@ -0,0 +1,33 @@
+package listenfd
+
+import (
+	"net"
+	"os"
+	"strconv"
+
+	"github.com/pkg/errors"
+)
+
+const fdStart = 3
+
+func GetListener(i uint64) (net.Listener, error) {
+	lfds, present := os.LookupEnv("LISTEN_FDS")
+	if !present {
+		return nil, nil
+	}
+
+	fds, err := strconv.ParseUint(lfds, 10, 32)
+	if err != nil {
+		return nil, errors.Wrap(err, "could not parse LISTEN_FDS")
+	}
+	if i >= fds {
+		return nil, errors.Errorf("only %d fds available, requested index %d", fds, i)
+	}
+
+	l, err := net.FileListener(os.NewFile(uintptr(i+fdStart), ""))
+	if err != nil {
+		return nil, errors.Wrap(err, "could not create listener")
+	}
+
+	return l, nil
+}