Added Ctrl+C handler

This commit is contained in:
Verox007 2023-12-17 01:03:49 +01:00
parent 720f70338f
commit 8a4e29a3ce
3 changed files with 22 additions and 58 deletions

View File

@ -28,9 +28,6 @@ func Run(baseCtx context.Context, addr string) {
// var wg sync.WaitGroup
go func() {
go func() {
<-ctx.Done()
}()
for {
// Print test every second
select {
@ -44,10 +41,12 @@ func Run(baseCtx context.Context, addr string) {
}()
// Listen for an incoming connection in a goroutine.
// wg.Add(1)
go func() {
go func() {
// Waiting for the context to be done
<-ctx.Done()
// Waiting for the listener to be closed, so the port is safely released
listener.Close()
}()
for {

View File

@ -1,53 +0,0 @@
package utils
// Queue implementation
type Node struct {
Value interface{}
Next *Node
}
type Queue struct {
Head *Node
Tail *Node
}
func (q *Queue) Enqueue(value interface{}) {
node := &Node{Value: value}
if q.Head == nil {
q.Head = node
q.Tail = node
return
}
q.Tail.Next = node
q.Tail = node
}
func (q *Queue) Dequeue() interface{} {
if q.Head == nil {
return nil
}
node := q.Head
q.Head = node.Next
if q.Head == nil {
q.Tail = nil
}
return node.Value
}
func (q *Queue) Peek() interface{} {
if q.Head == nil {
return nil
}
return q.Head.Value
}
func (q *Queue) IsEmpty() bool {
return q.Head == nil
}

View File

@ -4,7 +4,11 @@ import (
"cimeyclust.com/steel/pkg/cmd"
"cimeyclust.com/steel/pkg/net"
"context"
"fmt"
"os"
"os/signal"
"sync"
"syscall"
)
func main() {
@ -12,6 +16,9 @@ func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
var wg sync.WaitGroup
// Start the console handler
@ -32,8 +39,19 @@ func main() {
net.Run(ctx, "localhost:8080")
}()
cmd.Logger.Info("Started")
// Handles Ctrl+C
go func() {
defer cancel()
select {
case <-sigChan:
cmd.Logger.Info("Received stop command via Ctrl+C")
cancel()
}
}()
// Wait for all components to finish
cmd.Logger.Info("Server started successfully")
wg.Wait()
fmt.Println("Server stopped successfully")
}