Persist choices to database

This commit is contained in:
2025-01-01 11:52:33 +01:00
parent 8244916c8f
commit b587845823
4 changed files with 58 additions and 2 deletions
+2
View File
@@ -0,0 +1,2 @@
*.sqlite3
.DS_Store
+5
View File
@@ -0,0 +1,5 @@
module wa5p.eu/datefinder
go 1.22.0
require github.com/mattn/go-sqlite3 v1.14.24
+2
View File
@@ -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=
+48 -1
View File
@@ -1,16 +1,45 @@
package main package main
import ( import (
"database/sql"
"encoding/json" "encoding/json"
"fmt" "fmt"
"log" "log"
"net/http" "net/http"
_ "github.com/mattn/go-sqlite3"
) )
const ( 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) { func handleGetPing(w http.ResponseWriter, r *http.Request) {
log.Printf("[*] Received request %v %v\n", r.Method, r.URL) log.Printf("[*] Received request %v %v\n", r.Method, r.URL)
fmt.Fprintf(w, "PONG\n") fmt.Fprintf(w, "PONG\n")
@@ -32,7 +61,22 @@ func handlePostSubmit(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest) 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) w.WriteHeader(http.StatusOK)
} }
@@ -45,6 +89,9 @@ func handleOptionsSubmit(w http.ResponseWriter, r *http.Request) {
} }
func main() { func main() {
initDatabase()
defer db.Close()
http.HandleFunc( http.HandleFunc(
"GET /api/ping", "GET /api/ping",
handleGetPing, handleGetPing,