Files
MailPocket/batched-server/main.go
T

122 lines
2.3 KiB
Go
Raw Normal View History

2025-02-08 13:05:53 -05:00
package main
import (
"encoding/csv"
"encoding/json"
2025-02-24 12:32:02 -05:00
"log"
2025-02-08 13:05:53 -05:00
"net/http"
"os"
2025-02-24 18:53:25 -05:00
"path/filepath"
"shared"
2025-02-08 13:05:53 -05:00
"strings"
"sync"
"time"
)
var (
emailQueue []string
queueLock sync.Mutex
2025-02-24 18:53:25 -05:00
dbdir string
PORT string
fpath string
2025-02-08 13:05:53 -05:00
)
func saveEmails() {
queueLock.Lock()
defer queueLock.Unlock()
if len(emailQueue) == 0 {
return
}
fileExists := true
2025-02-24 18:53:25 -05:00
if _, err := os.Stat(fpath); os.IsNotExist(err) {
2025-02-08 13:05:53 -05:00
fileExists = false
}
2025-02-24 18:53:25 -05:00
f, err := os.OpenFile(fpath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
2025-02-08 13:05:53 -05:00
if err != nil {
2025-02-24 12:32:02 -05:00
log.Println("Failed to open file:", err)
2025-02-08 13:05:53 -05:00
return
}
defer f.Close()
writer := csv.NewWriter(f)
defer writer.Flush()
2025-02-24 12:32:02 -05:00
// Write header if file is new
2025-02-08 13:05:53 -05:00
if !fileExists {
if err := writer.Write([]string{"email", "timestamp"}); err != nil {
2025-02-24 12:32:02 -05:00
log.Println("Failed to write header:", err)
2025-02-08 13:05:53 -05:00
return
}
}
2025-02-24 12:32:02 -05:00
// Write each email with timestamp
2025-02-08 13:05:53 -05:00
for _, email := range emailQueue {
timestamp := time.Now().Format(time.RFC3339)
if err := writer.Write([]string{email, timestamp}); err != nil {
2025-02-24 12:32:02 -05:00
log.Println("Failed to write email:", err)
2025-02-08 13:05:53 -05:00
return
}
}
2025-02-24 12:32:02 -05:00
// Clear queue
2025-02-08 13:05:53 -05:00
emailQueue = emailQueue[:0]
}
// background goroutine to batch writes
func init() {
go func() {
for {
2025-02-24 12:32:02 -05:00
time.Sleep(5 * time.Second)
queueLock.Lock()
hasEmails := len(emailQueue) > 0
queueLock.Unlock()
2025-02-08 13:05:53 -05:00
if hasEmails {
2025-02-24 12:32:02 -05:00
log.Println("Flushing email queue...")
saveEmails()
2025-02-08 13:05:53 -05:00
}
}
2025-02-24 12:32:02 -05:00
}()
2025-02-08 13:05:53 -05:00
}
func submitHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
email := strings.TrimSpace(r.FormValue("email"))
if email == "" {
http.Error(w, "Email required", http.StatusBadRequest)
return
}
queueLock.Lock()
emailQueue = append(emailQueue, email)
shouldFlush := len(emailQueue) >= 100
queueLock.Unlock()
if shouldFlush {
saveEmails()
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"message": "data received"})
}
func main() {
2025-02-24 18:53:25 -05:00
PORT, dbdir = shared.GetArgs()
fpath = filepath.Join(dbdir, "emails.csv")
2025-02-24 12:32:02 -05:00
2025-02-08 13:05:53 -05:00
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"))
})
2025-02-24 12:32:02 -05:00
log.Println("Starting server on port", PORT)
log.Fatal(http.ListenAndServe(":"+PORT, nil))
2025-02-24 18:53:25 -05:00
}