all repos — website @ a238c7e0889cbe7dfaa1a700dea30686a4e2139a

My website

extract socket passing protocol handler to package
Alan Pearce alan@alanpearce.eu
Tue, 18 Jun 2024 15:58:53 +0200
commit

a238c7e0889cbe7dfaa1a700dea30686a4e2139a

parent

f69b6432cd1f921909b254c1adc93080e844f2f5

2 files changed, 40 insertions(+), 3 deletions(-)

jump to
A 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
+}
M internal/server/server.gointernal/server/server.go
@@ -6,12 +6,12 @@ "fmt" 	"net"
 	"net/http"
 	"net/url"
-	"os"
 	"slices"
 	"time"
 
 	"website/internal/builder"
 	cfg "website/internal/config"
+	"website/internal/listenfd"
 	"website/internal/log"
 	"website/internal/website"
 
@@ -161,14 +161,18 @@ }, nil }
 
 func (s *Server) Start() error {
-	f := os.NewFile(uintptr(3), "")
-	l, err := net.FileListener(f)
+	l, err := listenfd.GetListener(0)
 	if err != nil {
+		log.Warn("could not create listener from listenfd", "error", err)
+	}
+
+	if l == nil {
 		l, err = net.Listen("tcp", s.Addr)
 		if err != nil {
 			return errors.Wrap(err, "could not create listener")
 		}
 	}
+
 	if err := http.Serve(l, s.Handler); err != http.ErrServerClosed {
 		return errors.Wrap(err, "error creating/closing server")
 	}