Files
MailPocket/batched-server/main.go
T

121 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"
"strings"
"sync"
"time"
)
var (
emailQueue []string
queueLock sync.Mutex
)
func saveEmails() {
queueLock.Lock()
defer queueLock.Unlock()
if len(emailQueue) == 0 {
return
}
fileExists := true
if _, err := os.Stat("emails.csv"); os.IsNotExist(err) {
fileExists = false
}
f, err := os.OpenFile("emails.csv", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
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 12:32:02 -05:00
var PORT string
if len(os.Args) > 1 {
PORT = os.Args[1]
} else {
PORT = "15521"
}
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))
}