Перенести решение лабораторной 1 как основу для лабораторной 2
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
// Package server runs the HTTP listener with the lifecycle the lab
|
||||
// requires: readiness drops first, the listener stops accepting, in-flight
|
||||
// requests drain within a bounded timeout, then the process exits.
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"messenger/internal/app"
|
||||
)
|
||||
|
||||
// Run serves until ctx is cancelled, then shuts down within shutdownTimeout.
|
||||
func Run(ctx context.Context, log *slog.Logger, ln net.Listener, a *app.App, shutdownTimeout time.Duration) error {
|
||||
srv := &http.Server{
|
||||
Handler: a.Engine,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: 10 * time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
MaxHeaderBytes: 64 * 1024,
|
||||
ErrorLog: slog.NewLogLogger(log.Handler(), slog.LevelWarn),
|
||||
}
|
||||
|
||||
served := make(chan error, 1)
|
||||
go func() {
|
||||
err := srv.Serve(ln)
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
err = nil
|
||||
}
|
||||
served <- err
|
||||
}()
|
||||
log.Info("listening", "addr", ln.Addr().String())
|
||||
|
||||
select {
|
||||
case err := <-served:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
}
|
||||
|
||||
log.Info("shutdown started", "timeout", shutdownTimeout.String())
|
||||
a.Health.SetReady(false)
|
||||
drain, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
||||
defer cancel()
|
||||
if err := srv.Shutdown(drain); err != nil {
|
||||
log.Error("shutdown forced", "error", err.Error())
|
||||
_ = srv.Close()
|
||||
return err
|
||||
}
|
||||
<-served
|
||||
log.Info("shutdown completed")
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user