Gracefully shut down server when interrupt signal is received and remove panic when creating log directory
This commit is contained in:
parent
5ae84c1995
commit
f7eb852c66
26
main.go
26
main.go
@ -6,10 +6,13 @@ import (
|
|||||||
"GoWeb/database"
|
"GoWeb/database"
|
||||||
"GoWeb/models"
|
"GoWeb/models"
|
||||||
"GoWeb/routes"
|
"GoWeb/routes"
|
||||||
|
"context"
|
||||||
"embed"
|
"embed"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -30,7 +33,9 @@ func main() {
|
|||||||
if _, err := os.Stat("logs"); os.IsNotExist(err) {
|
if _, err := os.Stat("logs"); os.IsNotExist(err) {
|
||||||
err := os.Mkdir("logs", 0755)
|
err := os.Mkdir("logs", 0755)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic("Failed to create log directory")
|
log.Println("Failed to create log directory")
|
||||||
|
log.Println(err)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -53,10 +58,23 @@ func main() {
|
|||||||
routes.PostRoutes(&appLoaded)
|
routes.PostRoutes(&appLoaded)
|
||||||
|
|
||||||
// Start server
|
// Start server
|
||||||
|
server := &http.Server{Addr: appLoaded.Config.Listen.Ip + ":" + appLoaded.Config.Listen.Port}
|
||||||
|
go func() {
|
||||||
log.Println("Starting server and listening on " + appLoaded.Config.Listen.Ip + ":" + appLoaded.Config.Listen.Port)
|
log.Println("Starting server and listening on " + appLoaded.Config.Listen.Ip + ":" + appLoaded.Config.Listen.Port)
|
||||||
err = http.ListenAndServe(appLoaded.Config.Listen.Ip+":"+appLoaded.Config.Listen.Port, nil)
|
err := server.ListenAndServe()
|
||||||
|
if err != nil && err != http.ErrServerClosed {
|
||||||
|
log.Fatalf("Could not listen on %s: %v\n", appLoaded.Config.Listen.Ip+":"+appLoaded.Config.Listen.Port, err)
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
// Wait for interrupt signal and shut down the server
|
||||||
|
interrupt := make(chan os.Signal, 1)
|
||||||
|
signal.Notify(interrupt, os.Interrupt, syscall.SIGTERM)
|
||||||
|
<-interrupt
|
||||||
|
log.Println("Interrupt signal received. Shutting down server...")
|
||||||
|
|
||||||
|
err = server.Shutdown(context.Background())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Println(err)
|
log.Fatalf("Could not gracefully shutdown the server: %v\n", err)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user