Skip to content

Commit

Permalink
add daatabase dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
moosavi.smd committed Apr 25, 2024
1 parent 2116530 commit 426f850
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 11 deletions.
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -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=
88 changes: 77 additions & 11 deletions main.go
Original file line number Diff line number Diff line change
@@ -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"))
}

0 comments on commit 426f850

Please sign in to comment.