package fiber import ( "context" "net" "sync" "go.uber.org/zap" ) // Start opens the listener synchronously so Fx observes bind errors immediately. // It must be called once per Controller; Stop terminates the serving goroutine. func (ctrl *Controller) Start(ctx context.Context) error { listener, err := net.Listen("tcp", ctrl.cfg.Bind()) if err != nil { return err } ready := make(chan struct{}) go ctrl.serve(&acceptingListener{Listener: listener, ready: ready}) select { case <-ready: ctrl.log.Info("http listener started", zap.String("address", listener.Addr().String())) return nil case err := <-ctrl.serveDone: return err case <-ctx.Done(): _ = listener.Close() return ctx.Err() } } // acceptingListener signals after fasthttp registers the listener and enters its // accept loop. An OnListen hook runs earlier and cannot guarantee safe immediate Stop. type acceptingListener struct { // Listener is the bound socket owned by the HTTP lifecycle. net.Listener ready chan struct{} once sync.Once } // Accept marks the server as started before waiting for the next connection. func (listener *acceptingListener) Accept() (net.Conn, error) { listener.once.Do(func() { close(listener.ready) }) return listener.Listener.Accept() } // serve serves the listener and publishes its terminal result to the lifecycle. func (ctrl *Controller) serve(listener net.Listener) { ctrl.serveDone <- ctrl.server.Listener(listener) } // Stop disables admission, closes the listener and drains active requests. // The configured timeout is bounded by the caller's Fx shutdown context. func (ctrl *Controller) Stop(ctx context.Context) error { ctrl.stopping.Store(true) ctx, cancel := context.WithTimeout(ctx, ctrl.cfg.ShutdownTimeout()) defer cancel() if err := ctrl.server.ShutdownWithContext(ctx); err != nil { return err } select { case err := <-ctrl.serveDone: ctrl.log.Info("http listener stopped") return err case <-ctx.Done(): return ctx.Err() } }