From 426f850f0129ffeebc26d932f02c456c9fde34b0 Mon Sep 17 00:00:00 2001 From: "moosavi.smd" Date: Thu, 25 Apr 2024 18:49:47 +0330 Subject: [PATCH] add daatabase dependency --- go.mod | 5 ++++ go.sum | 4 +++ main.go | 88 +++++++++++++++++++++++++++++++++++++++++++++++++-------- 3 files changed, 86 insertions(+), 11 deletions(-) diff --git a/go.mod b/go.mod index 5514d96..0980b8b 100644 --- a/go.mod +++ b/go.mod @@ -3,3 +3,8 @@ module github.com/moosavismd/app go 1.22 require github.com/google/uuid v1.6.0 + +require ( + filippo.io/edwards25519 v1.1.0 // indirect + github.com/go-sql-driver/mysql v1.8.1 // indirect +) diff --git a/go.sum b/go.sum index 7790d7c..999c59c 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,6 @@ +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= +github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= diff --git a/main.go b/main.go index 3598f8b..2351ecb 100644 --- a/main.go +++ b/main.go @@ -1,37 +1,103 @@ package main import ( + "database/sql" + "encoding/json" "fmt" "log" "net/http" "os" + "time" + _ "github.com/go-sql-driver/mysql" "github.com/google/uuid" ) +type Config struct { + Database struct { + Host string `json:"host"` + Port int `json:"port"` + User string `json:"user"` + Password string `json:"password"` + Dbname string `json:"dbname"` + } `json:"database"` +} + func main() { - // Get the port number from the environment variable + config, err := readConfig("./config.json") + if err != nil { + log.Fatal(err) + } + + db := setupDatabase(config) + defer db.Close() + + http.HandleFunc("/uid", func(w http.ResponseWriter, r *http.Request) { + uidHandler(w, r, db) + }) + http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { + healthHandler(w, r, db) + }) + port := os.Getenv("PORT") if port == "" { log.Fatal("PORT environment variable not set.") } - http.HandleFunc("/uid", uidHandler) + log.Printf("Server is running on port %s\n", port) + log.Fatal(http.ListenAndServe(":"+port, nil)) +} - // Start the HTTP server - fmt.Printf("Server is running on port %s\n", port) - if err := http.ListenAndServe(":"+port, nil); err != nil { - log.Fatalf("Failed to start server: %v", err) +func readConfig(filePath string) (Config, error) { + var config Config + bytes, err := os.ReadFile(filePath) + if err != nil { + return config, err } + err = json.Unmarshal(bytes, &config) + return config, err } -func uidHandler(w http.ResponseWriter, r *http.Request) { - if r.Method != "GET" { - http.Error(w, "Method is not supported.", http.StatusNotFound) - return +func setupDatabase(cfg Config) *sql.DB { + dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s", cfg.Database.User, cfg.Database.Password, cfg.Database.Host, cfg.Database.Port, cfg.Database.Dbname) + db, err := sql.Open("mysql", dsn) + if err != nil { + log.Fatalf("Error opening database: %v", err) + } + + err = db.Ping() + if err != nil { + log.Fatalf("Error connecting to database: %v", err) } - // Generate a new UUID + createTableSQL := `CREATE TABLE IF NOT EXISTS uids ( + id INT AUTO_INCREMENT PRIMARY KEY, + uid VARCHAR(255) NOT NULL, + timestamp DATETIME NOT NULL + );` + _, err = db.Exec(createTableSQL) + if err != nil { + log.Fatalf("Error creating table: %v", err) + } + + return db +} + +func uidHandler(w http.ResponseWriter, r *http.Request, db *sql.DB) { uid := uuid.New() + _, err := db.Exec("INSERT INTO uids (uid, timestamp) VALUES (?, ?)", uid.String(), time.Now()) + if err != nil { + http.Error(w, "Error saving UID", http.StatusInternalServerError) + return + } fmt.Fprintf(w, "%s", uid.String()) } + +func healthHandler(w http.ResponseWriter, r *http.Request, db *sql.DB) { + if err := db.Ping(); err != nil { + http.Error(w, "Database not accessible", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusOK) + w.Write([]byte("OK")) +}