Skip to content

ctrl + c not properly handled #15

@ChristianSch

Description

@ChristianSch

I'm running a go program that handles SIGTERM to shutdown resources. Like so:

	// 1️⃣ Create a context that listens for shutdown signals
	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
	defer stop()

	// 2️⃣ Run Fiber in a Goroutine
	go func() {
		if err := app.Listen(fmt.Sprintf(":%d", config.Port)); err != nil {
			log.Fatalf("❌ Server failed to start: %v", err)
		}
	}()

	zap.L().Info("🚀 Server started.", zap.String("service", serviceName), zap.String("serviceID", serviceID), zap.String("location", "http://localhost:3000"))

	// process documents use case that creates handlers for each new mailbox we have under management
	cleanup := setupUsecase(config)

	// 3️⃣ Wait for termination signal
	<-ctx.Done()
	zap.L().Debug("Shutdown signal received.")

	// 4️⃣ Gracefully shutdown the Fiber app
	fmt.Println("🧹 Cleaning up resources...")
	_, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := app.Shutdown(); err != nil {
		zap.L().Error("Failed to shutdown Fiber", zap.Error(err))
	}

	err = cleanup()
	if err != nil {
		zap.L().Error("Failed to cleanup resources", zap.Error(err))
	}

	zap.L().Info("✅ Server stopped gracefully.")

When running it with go run cmd/server.go ./config.yml 2>&1 | zap-pretty I have to kill the server command via external means. Without using zap-pretty it works perfectly.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions