Add custom http listener support

This commit is contained in:
Ryan McGuire 2025-01-29 17:26:29 -05:00
parent 004c1b1ee6
commit ae00c64684
2 changed files with 20 additions and 6 deletions

View File

@ -3,6 +3,7 @@ package app
import ( import (
"context" "context"
"errors" "errors"
"net"
"net/http" "net/http"
"github.com/rs/zerolog" "github.com/rs/zerolog"
@ -25,9 +26,10 @@ type App struct {
} }
type AppHTTP struct { type AppHTTP struct {
Funcs []srv.HTTPFunc Funcs []srv.HTTPFunc // Handle funcs to serve
Middleware []http.Handler Middleware []http.Handler // Optional middleware. Next handler called by app framework.
HealthChecks []srv.HealthCheckFunc HealthChecks []srv.HealthCheckFunc // Health-check functions to be called by health endpoint
CustomListener net.Listener // Optional listener for http server
httpDone <-chan interface{} httpDone <-chan interface{}
} }
@ -85,6 +87,7 @@ func (a *App) initHTTP() {
HandleFuncs: a.HTTP.Funcs, HandleFuncs: a.HTTP.Funcs,
Middleware: a.HTTP.Middleware, Middleware: a.HTTP.Middleware,
HealthCheckFuncs: a.HTTP.HealthChecks, HealthCheckFuncs: a.HTTP.HealthChecks,
CustomListener: a.HTTP.CustomListener,
}, },
) )
a.shutdownFuncs = append(a.shutdownFuncs, httpShutdown) a.shutdownFuncs = append(a.shutdownFuncs, httpShutdown)

View File

@ -37,6 +37,7 @@ type HTTPServerOpts struct {
HandleFuncs []HTTPFunc HandleFuncs []HTTPFunc
Middleware []http.Handler Middleware []http.Handler
HealthCheckFuncs []HealthCheckFunc HealthCheckFuncs []HealthCheckFunc
CustomListener net.Listener
} }
func prepHTTPServer(opts *HTTPServerOpts) *http.Server { func prepHTTPServer(opts *HTTPServerOpts) *http.Server {
@ -155,16 +156,26 @@ func InitHTTPServer(opts *HTTPServerOpts) (
server = prepHTTPServer(opts) server = prepHTTPServer(opts)
go func() { go func() {
l.Debug().Msg("HTTP Server Started") var err error
err := server.ListenAndServe()
if opts.CustomListener != nil {
err = server.Serve(opts.CustomListener)
} else {
err = server.ListenAndServe()
}
if err != nil && err != http.ErrServerClosed { if err != nil && err != http.ErrServerClosed {
l.Err(err).Msg("HTTP server error") l.Err(err).Msg("HTTP server error")
} else { } else {
l.Info().Msg("HTTP server shut down") l.Info().Msg("HTTP server shut down")
} }
// Notify app initiator
doneChan <- nil doneChan <- nil
}() }()
l.Debug().Msg("HTTP Server Started")
// Shut down http server with a deadline // Shut down http server with a deadline
return func(shutdownCtx context.Context) error { return func(shutdownCtx context.Context) error {
l.Debug().Msg("stopping http server") l.Debug().Msg("stopping http server")