Add graceful shutdown option to webserver
This commit is contained in:
31
main.go
31
main.go
@ -1,14 +1,41 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"gitlab.hpi.de/codeocean/codemoon/coolcodeoceannomadmiddleware/api"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
err := http.ListenAndServe("0.0.0.0:4000", api.NewRouter())
|
||||
if err != nil {
|
||||
server := &http.Server{
|
||||
Addr: "0.0.0.0:4000",
|
||||
WriteTimeout: time.Second * 15,
|
||||
ReadTimeout: time.Second * 15,
|
||||
IdleTimeout: time.Second * 60,
|
||||
Handler: api.NewRouter(),
|
||||
}
|
||||
go func() {
|
||||
if err := server.ListenAndServe(); err != nil {
|
||||
if err == http.ErrServerClosed {
|
||||
log.Println(err)
|
||||
} else {
|
||||
log.Fatal("Error during listening and serving: ", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// wait for SIGINT
|
||||
signals := make(chan os.Signal, 1)
|
||||
signal.Notify(signals, os.Interrupt)
|
||||
<-signals
|
||||
log.Println("Received SIGINT, shutting down ...")
|
||||
|
||||
// shutdown the server but wait up to 15 seconds to close remaining connections
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
_ = server.Shutdown(ctx)
|
||||
}
|
||||
|
Reference in New Issue
Block a user