Persist choices to database
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
module wa5p.eu/datefinder
|
||||
|
||||
go 1.22.0
|
||||
|
||||
require github.com/mattn/go-sqlite3 v1.14.24
|
||||
@@ -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=
|
||||
+49
-2
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user