From 3d0c20ae4883d1505154feef043ee1a5bd02f925 Mon Sep 17 00:00:00 2001 From: Aadhavan Srinivasan Date: Sat, 29 Mar 2025 11:59:36 -0500 Subject: [PATCH] Added signal handling --- golangServer/testing.go | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/golangServer/testing.go b/golangServer/testing.go index e210c07..2aebb69 100644 --- a/golangServer/testing.go +++ b/golangServer/testing.go @@ -7,6 +7,9 @@ import ( "fmt" "log" "net/http" + "os" + "os/signal" + "syscall" "github.com/jmoiron/sqlx" _ "github.com/mattn/go-sqlite3" @@ -72,6 +75,13 @@ var lang_codes []string = []string{ var db *sqlx.DB +func cleanup() { + db.Close() + log.Printf("Shutting down...\n") + return +} + + /* Returns the cached translation from the database, for the given english text. The first parameter @@ -168,13 +178,28 @@ func handler(w http.ResponseWriter, r *http.Request) { } func main() { - fmt.Printf("Starting server...") + log.Printf("Starting server...") var err error db, err = sqlx.Connect("sqlite3", "../translations.db") if err != nil { panic(err) } defer db.Close() + // Catch signal + sigs := make(chan os.Signal, 1) + signal.Notify(sigs) + go func() { + for sig := range sigs { + log.Printf("Received signal: %s", sig) + switch sig { + case syscall.SIGURG: + log.Printf("Ignoring sigurg") + case syscall.SIGTERM, syscall.SIGINT: + cleanup() + os.Exit(1) + } + } + }() http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe(":9090", nil))