From d5ceb647d4cdfdbfae499b0c9517cd6f00a29d01 Mon Sep 17 00:00:00 2001 From: Imbus Date: Sun, 12 Nov 2023 06:42:55 +0100 Subject: [PATCH] Server --- server/go.mod | 8 +++++++ server/go.sum | 7 ++++++ server/main.go | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 server/go.mod create mode 100644 server/go.sum create mode 100644 server/main.go diff --git a/server/go.mod b/server/go.mod new file mode 100644 index 0000000..27d1c1c --- /dev/null +++ b/server/go.mod @@ -0,0 +1,8 @@ +module swrm + +go 1.21.1 + +require ( + github.com/jmoiron/sqlx v1.3.5 + github.com/mattn/go-sqlite3 v1.14.18 +) diff --git a/server/go.sum b/server/go.sum new file mode 100644 index 0000000..4e47865 --- /dev/null +++ b/server/go.sum @@ -0,0 +1,7 @@ +github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/jmoiron/sqlx v1.3.5 h1:vFFPA71p1o5gAeqtEAwLU4dnX2napprKtHr7PYIcN3g= +github.com/jmoiron/sqlx v1.3.5/go.mod h1:nRVWtLre0KfCLJvgxzCsLVMogSvQ1zNJtpYr2Ccp0mQ= +github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= +github.com/mattn/go-sqlite3 v1.14.18 h1:JL0eqdCOq6DJVNPSvArO/bIV9/P7fbGrV00LZHc+5aI= +github.com/mattn/go-sqlite3 v1.14.18/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= diff --git a/server/main.go b/server/main.go new file mode 100644 index 0000000..3ff5e24 --- /dev/null +++ b/server/main.go @@ -0,0 +1,65 @@ +package main + +import ( + "fmt" + "io" + "net/http" + "os" + "time" + + "github.com/jmoiron/sqlx" + _ "github.com/mattn/go-sqlite3" +) + +// This is a function that takes a long time to run +// Useful for demonstrating concurrency (goroutines) +func delayPrint() { + time.Sleep(5 * time.Second) + fmt.Printf("delay print\n") +} + +// This is what a handler looks like +func getRoot(w http.ResponseWriter, r *http.Request) { + fmt.Printf("got / request\n") + go delayPrint() + io.WriteString(w, "This is my website!\n") +} + +func main() { + println("Starting server...") + // Check for the environment variable + dbpath := os.Getenv("SQLITE_DB_PATH") + + // Default to something reasonable + if dbpath == "" { + dbpath = "./db.sqlite3" + } + + // Open the database + // db, err := sqlx.Connect("sqlite3", ":memory:") + db, err := sqlx.Connect("sqlite3", dbpath) + if err != nil { + panic(err) + } + defer db.Close() + + err = db.Ping() + if err != nil { + panic(err) + } + + // Slide into the database dms with some slick SQL + db.MustExec("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, email TEXT)") + + // Mounting the handler + // http.HandleFunc("/", getRoot) + + fs := http.FileServer(http.Dir("static")) + http.Handle("/", fs) + + // Start the server on port 8080 + err = http.ListenAndServe(":8080", nil) + if err != nil { + panic(err) + } +}