added admin routes

This commit is contained in:
2025-02-28 19:11:16 -05:00
parent 29ef485e29
commit da40f652a7
10 changed files with 152 additions and 82 deletions
+34 -17
View File
@@ -13,8 +13,13 @@ import (
"time"
)
type EmailEntry struct {
Email string
FormName string
}
var (
emailQueue []string
emailQueue []EmailEntry // Changed to struct slice
queueLock sync.Mutex
dbdir string
PORT string
@@ -46,26 +51,24 @@ func saveEmails() {
// Write header if file is new
if !fileExists {
if err := writer.Write([]string{"email", "timestamp"}); err != nil {
if err := writer.Write([]string{"email", "formname", "timestamp"}); err != nil {
log.Println("Failed to write header:", err)
return
}
}
// Write each email with timestamp
for _, email := range emailQueue {
// Write each entry
for _, entry := range emailQueue {
timestamp := time.Now().Format(time.RFC3339)
if err := writer.Write([]string{email, timestamp}); err != nil {
if err := writer.Write([]string{entry.Email, entry.FormName, timestamp}); err != nil {
log.Println("Failed to write email:", err)
return
}
}
// Clear queue
emailQueue = emailQueue[:0]
emailQueue = emailQueue[:0] // Clear queue
}
// background goroutine to batch writes
func init() {
go func() {
for {
@@ -81,12 +84,28 @@ func init() {
}()
}
func submitHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
func handler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte("Batched Write Server is running"))
return
}
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
formName := strings.Trim(r.URL.Path, "/")
if formName == "" {
http.Error(w, "Form name required", http.StatusBadRequest)
return
}
email := strings.TrimSpace(r.FormValue("email"))
if email == "" {
http.Error(w, "Email required", http.StatusBadRequest)
@@ -94,7 +113,7 @@ func submitHandler(w http.ResponseWriter, r *http.Request) {
}
queueLock.Lock()
emailQueue = append(emailQueue, email)
emailQueue = append(emailQueue, EmailEntry{Email: email, FormName: formName})
shouldFlush := len(emailQueue) >= 100
queueLock.Unlock()
@@ -107,14 +126,12 @@ func submitHandler(w http.ResponseWriter, r *http.Request) {
}
func main() {
PORT, dbdir = shared.GetArgs()
_, PORT, dbdir = shared.GetArgs()
fpath = filepath.Join(dbdir, "emails.csv")
http.HandleFunc("/submit", submitHandler)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("Batched Write Server is running"))
})
shared.StartAdminServer(dbdir)
http.HandleFunc("/", handler) // Single handler for all routes
log.Println("Starting server on port", PORT)
log.Fatal(http.ListenAndServe(":"+PORT, nil))