Serve html from golang server via template

This commit is contained in:
2025-01-01 14:33:35 +01:00
parent 10d588e1a7
commit e4e745cb57
3 changed files with 120 additions and 4 deletions
+1
View File
@@ -1,3 +1,4 @@
*.sqlite3 *.sqlite3
*.sqlite3-journal *.sqlite3-journal
.DS_Store .DS_Store
.vscode
+40 -2
View File
@@ -4,6 +4,7 @@ import (
"database/sql" "database/sql"
"encoding/json" "encoding/json"
"fmt" "fmt"
"html/template"
"log" "log"
"net/http" "net/http"
@@ -17,6 +18,7 @@ const (
var ( var (
db *sql.DB db *sql.DB
indexHtmlTemplate *template.Template
) )
type ChoicesPost struct { type ChoicesPost struct {
@@ -60,6 +62,22 @@ func initDatabase() {
} }
} }
func prepareStaticContent() {
var err error
indexHtmlTemplate, err = template.ParseFiles("./static/index.html")
if err != nil {
log.Fatalf("[!] Could not parse index.html template, error: %s\n", err)
}
}
func handleGetRoot(w http.ResponseWriter, r *http.Request) {
err := indexHtmlTemplate.Execute(w, nil)
if err != nil {
log.Printf("[!] Could not execute index.html template, error: %s\n", err)
http.Error(w, "Error rendering template", http.StatusInternalServerError)
}
}
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")
@@ -86,17 +104,30 @@ func handlePostSubmit(w http.ResponseWriter, r *http.Request) {
log.Printf("[!] Could not marshal choices, error: %s\n", err) log.Printf("[!] Could not marshal choices, error: %s\n", err)
} }
tx, err := db.Begin()
if err != nil {
log.Printf("[!] Could not begin database transaction, error: %s\n", err)
w.WriteHeader(http.StatusBadRequest)
return
}
const query = ` const query = `
INSERT INTO choices (pollid, username, choices) INSERT INTO choices (pollid, username, choices)
VALUES (?, ?, ?); VALUES (?, ?, ?);
` `
_, err = db.Exec(query, choicesPost.PollId, choicesPost.Username, string(choicesJson)) _, err = tx.Exec(query, choicesPost.PollId, choicesPost.Username, string(choicesJson))
if err != nil { if err != nil {
log.Printf("[!] Could not insert choices into database, error: %s\n", err) log.Printf("[!] Could not insert choices into database, error: %s\n", err)
tx.Rollback()
w.WriteHeader(http.StatusBadRequest)
return
} }
log.Printf("[*] Persisted choices for %s to database\n", "DUMMY USERNAME") tx.Commit()
log.Printf("[*] Persisted choices for poll %d, username %s to database\n",
choicesPost.PollId, choicesPost.Username)
w.WriteHeader(http.StatusOK) w.WriteHeader(http.StatusOK)
} }
@@ -112,11 +143,18 @@ func main() {
initDatabase() initDatabase()
defer db.Close() defer db.Close()
prepareStaticContent()
http.HandleFunc( http.HandleFunc(
"GET /api/ping", "GET /api/ping",
handleGetPing, handleGetPing,
) )
http.HandleFunc(
"GET /",
handleGetRoot,
)
http.HandleFunc( http.HandleFunc(
"POST /api/submit", "POST /api/submit",
handlePostSubmit, handlePostSubmit,
+78 -1
View File
@@ -54,7 +54,84 @@
<input id="submit-name" type="text" placeholder="Enter your name" /> <input id="submit-name" type="text" placeholder="Enter your name" />
<button id="submit-btn" type="submit" onclick="submit">Submit</button> <button id="submit-btn" type="submit" onclick="submit">Submit</button>
</div> </div>
<script src="index.js"></script> <script>
// Days of the week
const daysOfWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
// Select the calendar container
const calendar = document.getElementById("calendar");
// Create the weekly calendar
daysOfWeek.forEach((day) => {
// Create a column for each day
const dayColumn = document.createElement("div");
dayColumn.classList.add("day-column");
// Add a header for the day
const dayHeader = document.createElement("div");
dayHeader.classList.add("day-header");
dayHeader.textContent = day;
dayColumn.appendChild(dayHeader);
// Add hourly blocks for each day
for (let hour = 0; hour < 24; hour++) {
const hourBlock = document.createElement("div");
hourBlock.classList.add("hour-block");
hourBlock.textContent = `${hour}:00`;
// Add a click event listener to toggle color
hourBlock.addEventListener("click", () => {
hourBlock.classList.toggle("clicked");
});
dayColumn.appendChild(hourBlock);
}
// Append the day column to the calendar
calendar.appendChild(dayColumn);
});
const submitName = document.getElementById("submit-name")
const submitBtn = document.getElementById("submit-btn")
submitBtn.onclick = function () {
if (submitName.value == "") {
console.log("Submitter name is missing.")
return
}
const days = calendar.children
const choices = Array.from(days).map(
day => Array.from(day.children).slice(1, 25).map(
hour => hour.classList.contains("clicked")))
console.log(`Submitting dates for ${submitName.value}`)
console.log(JSON.stringify(choices))
const url = "http://localhost:8080/api/submit";
fetch(url, {
method: "POST", // Specify the HTTP method
headers: {
"Content-Type": "application/json", // Inform the server about the data format
},
body: JSON.stringify({pollId: 1, username: submitName.value, choices: choices}), // Convert the data to JSON string
})
/*
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json(); // Parse the JSON response
})
.then(data => {
console.log('Success:', data); // Handle the response data
})
.catch(error => {
console.error('Error:', error); // Handle errors
});
*/
}
</script>
</body> </body>
</html> </html>