@@ -3,6 +3,7 @@ package fx
33import (
44 "context"
55 "fmt"
6+ "net"
67 "net/http"
78 "time"
89
@@ -47,29 +48,27 @@ func RegisterServerLifecycle(
4748 logger * zap.Logger ,
4849) {
4950 lc .Append (fx.Hook {
50- OnStart : func (ctx context.Context ) error {
51- addr := fmt .Sprintf ("%s:%d" , cfg .Host , cfg .Port )
51+ OnStart : func (ctx context.Context ) error {
52+ addr := fmt .Sprintf ("%s:%d" , cfg .Host , cfg .Port )
5253
53- // Bind synchronously so a failure (e.g. port already in use) is
54- // returned from OnStart and aborts fx startup. Racing the bind
55- // against a timer can report success over a dead listener and
56- // silently drop a late bind error.
57- ln , err := net .Listen ("tcp" , addr )
58- if err != nil {
59- return fmt .Errorf ("binding %s: %w" , addr , err )
60- }
61- e .Listener = ln
62- logger .Info ("starting Hilt service" , zap .String ("address" , addr ))
63- go func () {
64- // e.Start reuses the listener bound above and blocks serving
65- // until Shutdown, which returns http.ErrServerClosed.
66- if err := e .Start (addr ); err != nil && err != http .ErrServerClosed {
67- logger .Error ("server stopped unexpectedly" , zap .Error (err ))
68- }
69- }()
54+ // Bind synchronously so a failure (e.g. port already in use) is
55+ // returned from OnStart and aborts fx startup.
56+ ln , err := net .Listen ("tcp" , addr )
57+ if err != nil {
58+ return fmt .Errorf ("binding %s: %w" , addr , err )
59+ }
60+ e .Listener = ln
61+ logger .Info ("starting Hilt service" , zap .String ("address" , addr ))
62+ go func () {
63+ // e.Start reuses the listener bound above and blocks serving
64+ // until Shutdown, which returns http.ErrServerClosed.
65+ if err := e .Start (addr ); err != nil && err != http .ErrServerClosed {
66+ logger .Error ("server stopped unexpectedly" , zap .Error (err ))
67+ }
68+ }()
7069
71- return nil
72- },
70+ return nil
71+ },
7372 OnStop : func (ctx context.Context ) error {
7473 logger .Info ("shutting down server" )
7574 shutdownCtx , cancel := context .WithTimeout (ctx , 10 * time .Second )
0 commit comments