From 1fcfc2df8f2af05278f8f9d822f6b00c0c55a73c Mon Sep 17 00:00:00 2001 From: durbok Date: Sat, 28 Dec 2024 16:08:13 +0100 Subject: [PATCH] update go app --- Dockerfile | 10 ++++++++++ db/mysql.go | 38 ++++++++++++++++++++++++++++++++++++++ docker-compose.yml | 0 3 files changed, 48 insertions(+) create mode 100644 Dockerfile create mode 100644 docker-compose.yml diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..ff20d3c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,10 @@ +FROM golang:1.23.4 + +COPY . /app + +WORKDIR /app + +RUN go build && chmod +x tui-ssh-app + +CMD [/app/tui-ssh-app] + diff --git a/db/mysql.go b/db/mysql.go index 4162ad3..c10b76d 100644 --- a/db/mysql.go +++ b/db/mysql.go @@ -12,8 +12,11 @@ import ( var DB *sql.DB +// ConnectDB establishes the database connection and initializes tables. func ConnectDB() { var err error + + // Form the DSN (Data Source Name) dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", config.GetEnv("DB_USER"), config.GetEnv("DB_PASSWORD"), @@ -21,8 +24,43 @@ func ConnectDB() { config.GetEnv("DB_PORT"), config.GetEnv("DB_NAME"), ) + + // Open the connection DB, err = sql.Open("mysql", dsn) if err != nil { log.Fatalf("Error connecting to database: %v", err) } + + // Ping the database to ensure connection is successful + if err = DB.Ping(); err != nil { + log.Fatalf("Error pinging database: %v", err) + } + + fmt.Println("Connected to MySQL successfully!") + + // Initialize tables + initializeTables() +} + +// initializeTables creates required tables if they don't exist. +func initializeTables() { + queries := []string{ + `CREATE TABLE IF NOT EXISTS sessions ( + id INT AUTO_INCREMENT PRIMARY KEY, + user VARCHAR(255) NOT NULL, + host VARCHAR(255) NOT NULL, + port INT NOT NULL, + password TEXT, + private_key TEXT, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP + );`, + } + + for _, query := range queries { + if _, err := DB.Exec(query); err != nil { + log.Fatalf("Error creating table: %v", err) + } + } + + fmt.Println("Tables are initialized successfully!") } diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..e69de29