Files
MusicServer/cmd/main.go
T

80 lines
2.1 KiB
Go

package main
import (
"context"
"music-server/internal/db"
"music-server/internal/logging"
"music-server/internal/server"
"net/http"
"os/signal"
"syscall"
"time"
"go.uber.org/zap"
)
//
// @Title Swagger Example API
// @version 0.5
// @description This is a sample server Petstore server.
// @termsOfService http://swagger.io/terms/
// @contact.name Sebastian Olsson
// @contact.email zarnor91@gmail.com
// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
// @host localhost:8080
func main() {
/*f, perr := os.Create("cpu.pprof")
if perr != nil {
log.Fatal(perr)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()*/
server := server.NewServer()
// Create a done channel to signal when the shutdown is complete
done := make(chan bool, 1)
// Run graceful shutdown in a separate goroutine
go gracefulShutdown(server, done)
logging.GetLogger().Info("Server starting", zap.String("address", server.Addr))
err := server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
logging.GetLogger().Fatal("HTTP server error", zap.String("error", err.Error()))
}
// Wait for the graceful shutdown to complete
<-done
logging.GetLogger().Info("Graceful shutdown complete")
}
func gracefulShutdown(apiServer *http.Server, done chan bool) {
// Create context that listens for the interrupt signal from the OS.
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
// Listen for the interrupt signal.
<-ctx.Done()
logging.GetLogger().Info("Shutting down gracefully, press Ctrl+C again to force")
db.CloseDb()
// The context is used to inform the server it has 5 seconds to finish
// the request it is currently handling
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := apiServer.Shutdown(ctx); err != nil {
logging.GetLogger().Error("Server forced to shutdown with error", zap.String("error", err.Error()))
}
logging.GetLogger().Info("Server exiting")
// Notify the main goroutine that the shutdown is complete
done <- true
}