Skip to content

Commit

Permalink
feat: add http server factory
Browse files Browse the repository at this point in the history
  • Loading branch information
flexwie committed Oct 25, 2024
1 parent 0955de2 commit 4044053
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions http/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ import (
"go.uber.org/fx"
)

func WithHttpFactory(addr string) fx.Option {
return fx.Provide(
newHttpServerFactory(addr),
fx.Annotate(
newServeMux,
fx.ParamTags(`group:"routes"`),
),
)
}

var WithHttp = fx.Provide(
newHttpServer,
fx.Annotate(
Expand All @@ -17,6 +27,31 @@ var WithHttp = fx.Provide(
),
)

func newHttpServerFactory(addr string) func(fx.Lifecycle, *http.ServeMux, *log.Logger) *http.Server {
return func(lc fx.Lifecycle, mux *http.ServeMux, logger *log.Logger) *http.Server {
s := &http.Server{Addr: addr, Handler: mux}

lc.Append(fx.Hook{
OnStart: func(ctx context.Context) error {
ln, err := net.Listen("tcp", s.Addr)
if err != nil {
return err
}

go s.Serve(ln)
logger.Info("started http server", "addr", s.Addr)

return nil
},
OnStop: func(ctx context.Context) error {
return s.Shutdown(ctx)
},
})

return s
}
}

func newHttpServer(lc fx.Lifecycle, mux *http.ServeMux, logger *log.Logger) *http.Server {
s := &http.Server{Addr: ":8080", Handler: mux}

Expand Down

0 comments on commit 4044053

Please sign in to comment.