diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ec625bb --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.sqlite3 +.DS_Store diff --git a/server/go.mod b/server/go.mod new file mode 100644 index 0000000..8d01cfe --- /dev/null +++ b/server/go.mod @@ -0,0 +1,5 @@ +module wa5p.eu/datefinder + +go 1.22.0 + +require github.com/mattn/go-sqlite3 v1.14.24 diff --git a/server/go.sum b/server/go.sum new file mode 100644 index 0000000..9dcdc9b --- /dev/null +++ b/server/go.sum @@ -0,0 +1,2 @@ +github.com/mattn/go-sqlite3 v1.14.24 h1:tpSp2G2KyMnnQu99ngJ47EIkWVmliIizyZBfPrBWDRM= +github.com/mattn/go-sqlite3 v1.14.24/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= diff --git a/server/server.go b/server/server.go index 3dba34d..b7a1abc 100644 --- a/server/server.go +++ b/server/server.go @@ -1,16 +1,45 @@ package main import ( + "database/sql" "encoding/json" "fmt" "log" "net/http" + + _ "github.com/mattn/go-sqlite3" ) const ( - PORT = "8080" + PORT = "8080" + DB_FILE = "./datefinder.sqlite3" ) +var ( + db *sql.DB +) + +func initDatabase() { + var err error + db, err = sql.Open("sqlite3", DB_FILE) + if err != nil { + log.Fatalf("[!] Could not open database file %s, error: %s\n", DB_FILE, err) + } + + const query = ` + CREATE TABLE IF NOT EXISTS choices ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + username TEXT NOT NULL, + choices TEXT NOT NULL + ); + ` + + _, err = db.Exec(query) + if err != nil { + log.Fatalf("[!] Could not create database table, error: %s\n", err) + } +} + func handleGetPing(w http.ResponseWriter, r *http.Request) { log.Printf("[*] Received request %v %v\n", r.Method, r.URL) fmt.Fprintf(w, "PONG\n") @@ -32,7 +61,22 @@ func handlePostSubmit(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadRequest) } - log.Printf("TODO: Persist to database %v\n", choices) + choicesJson, err := json.Marshal(choices) + if err != nil { + log.Printf("[!] Could not marshal choices, error: %s\n", err) + } + + const query = ` + INSERT INTO choices (username, choices) + VALUES (?, ?); + ` + + _, err = db.Exec(query, "DUMMY USERNAME", string(choicesJson)) + if err != nil { + log.Printf("[!] Could not insert choices into database, error: %s\n", err) + } + + log.Printf("[*] Persisted choices for %s to database\n", "DUMMY USERNAME") w.WriteHeader(http.StatusOK) } @@ -45,6 +89,9 @@ func handleOptionsSubmit(w http.ResponseWriter, r *http.Request) { } func main() { + initDatabase() + defer db.Close() + http.HandleFunc( "GET /api/ping", handleGetPing,