42 lines
833 B
Go
42 lines
833 B
Go
|
package mux
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"log/slog"
|
||
|
"net/http"
|
||
|
"os"
|
||
|
"os/signal"
|
||
|
)
|
||
|
|
||
|
type ServeCB func(srv *http.Server) error
|
||
|
|
||
|
// Serve with gracefull shutdown
|
||
|
func (r *Router) Serve(cb ServeCB) {
|
||
|
srv := &http.Server{
|
||
|
Handler: r,
|
||
|
}
|
||
|
|
||
|
idleConnsClosed := make(chan struct{})
|
||
|
go func() {
|
||
|
sigint := make(chan os.Signal, 1)
|
||
|
signal.Notify(sigint, os.Interrupt)
|
||
|
<-sigint
|
||
|
|
||
|
// We received an interrupt signal, shut down.
|
||
|
if err := srv.Shutdown(context.Background()); err != nil {
|
||
|
// Error from closing listeners, or context timeout:
|
||
|
slog.Error("server shutdown error", "error", err)
|
||
|
} else {
|
||
|
slog.Info("server shutdown")
|
||
|
}
|
||
|
close(idleConnsClosed)
|
||
|
}()
|
||
|
|
||
|
if err := cb(srv); err != http.ErrServerClosed {
|
||
|
// Error starting or closing listener:
|
||
|
slog.Error("start server error", "error", err)
|
||
|
}
|
||
|
|
||
|
<-idleConnsClosed
|
||
|
}
|