From ae00c6468409faab11d8ed61225ab670ecbb3764 Mon Sep 17 00:00:00 2001 From: Ryan McGuire Date: Wed, 29 Jan 2025 17:26:29 -0500 Subject: [PATCH] Add custom http listener support --- pkg/app/app.go | 11 +++++++---- pkg/srv/http.go | 15 +++++++++++++-- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/pkg/app/app.go b/pkg/app/app.go index 8ca8142..40a61f8 100644 --- a/pkg/app/app.go +++ b/pkg/app/app.go @@ -3,6 +3,7 @@ package app import ( "context" "errors" + "net" "net/http" "github.com/rs/zerolog" @@ -25,10 +26,11 @@ type App struct { } type AppHTTP struct { - Funcs []srv.HTTPFunc - Middleware []http.Handler - HealthChecks []srv.HealthCheckFunc - httpDone <-chan interface{} + Funcs []srv.HTTPFunc // Handle funcs to serve + Middleware []http.Handler // Optional middleware. Next handler called by app framework. + HealthChecks []srv.HealthCheckFunc // Health-check functions to be called by health endpoint + CustomListener net.Listener // Optional listener for http server + httpDone <-chan interface{} } type ( @@ -85,6 +87,7 @@ func (a *App) initHTTP() { HandleFuncs: a.HTTP.Funcs, Middleware: a.HTTP.Middleware, HealthCheckFuncs: a.HTTP.HealthChecks, + CustomListener: a.HTTP.CustomListener, }, ) a.shutdownFuncs = append(a.shutdownFuncs, httpShutdown) diff --git a/pkg/srv/http.go b/pkg/srv/http.go index 8f58ef4..57635e2 100644 --- a/pkg/srv/http.go +++ b/pkg/srv/http.go @@ -37,6 +37,7 @@ type HTTPServerOpts struct { HandleFuncs []HTTPFunc Middleware []http.Handler HealthCheckFuncs []HealthCheckFunc + CustomListener net.Listener } func prepHTTPServer(opts *HTTPServerOpts) *http.Server { @@ -155,16 +156,26 @@ func InitHTTPServer(opts *HTTPServerOpts) ( server = prepHTTPServer(opts) go func() { - l.Debug().Msg("HTTP Server Started") - err := server.ListenAndServe() + var err error + + if opts.CustomListener != nil { + err = server.Serve(opts.CustomListener) + } else { + err = server.ListenAndServe() + } + if err != nil && err != http.ErrServerClosed { l.Err(err).Msg("HTTP server error") } else { l.Info().Msg("HTTP server shut down") } + + // Notify app initiator doneChan <- nil }() + l.Debug().Msg("HTTP Server Started") + // Shut down http server with a deadline return func(shutdownCtx context.Context) error { l.Debug().Msg("stopping http server")