Refactor main.go

This commit is contained in:
nemunaire 2025-10-18 11:41:07 +07:00
commit ef433bfbe5
5 changed files with 325 additions and 118 deletions

View file

@ -24,17 +24,11 @@ package main
import (
"flag"
"fmt"
"io"
"log"
"os"
"github.com/gin-gonic/gin"
"git.happydns.org/happyDeliver/internal/api"
"git.happydns.org/happyDeliver/internal/app"
"git.happydns.org/happyDeliver/internal/config"
"git.happydns.org/happyDeliver/internal/receiver"
"git.happydns.org/happyDeliver/internal/storage"
"git.happydns.org/happyDeliver/web"
)
const version = "0.1.0-dev"
@ -52,9 +46,13 @@ func main() {
switch command {
case "server":
runServer(cfg)
if err := app.RunServer(cfg); err != nil {
log.Fatalf("Server error: %v", err)
}
case "analyze":
runAnalyzer(cfg)
if err := app.RunAnalyzer(cfg, flag.Args()[1:], os.Stdin, os.Stdout); err != nil {
log.Fatalf("Analyzer error: %v", err)
}
case "version":
fmt.Println(version)
default:
@ -64,94 +62,11 @@ func main() {
}
}
func runServer(cfg *config.Config) {
if err := cfg.Validate(); err != nil {
log.Fatalf("Invalid configuration: %v", err)
}
// Initialize storage
store, err := storage.NewStorage(cfg.Database.Type, cfg.Database.DSN)
if err != nil {
log.Fatalf("Failed to initialize storage: %v", err)
}
defer store.Close()
log.Printf("Connected to %s database", cfg.Database.Type)
// Create API handler
handler := api.NewAPIHandler(store, cfg)
// Set up Gin router
if os.Getenv("GIN_MODE") == "" {
gin.SetMode(gin.ReleaseMode)
}
router := gin.Default()
// Register API routes
apiGroup := router.Group("/api")
api.RegisterHandlers(apiGroup, handler)
web.DeclareRoutes(cfg, router)
// Start server
log.Printf("Starting API server on %s", cfg.Bind)
log.Printf("Test email domain: %s", cfg.Email.Domain)
if err := router.Run(cfg.Bind); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}
func runAnalyzer(cfg *config.Config) {
// Parse command-line flags
fs := flag.NewFlagSet("analyze", flag.ExitOnError)
recipientEmail := fs.String("recipient", "", "Recipient email address (optional, will be extracted from headers if not provided)")
fs.Parse(flag.Args()[1:])
if err := cfg.Validate(); err != nil {
log.Fatalf("Invalid configuration: %v", err)
}
// Initialize storage
store, err := storage.NewStorage(cfg.Database.Type, cfg.Database.DSN)
if err != nil {
log.Fatalf("Failed to initialize storage: %v", err)
}
defer store.Close()
log.Printf("Email analyzer ready, reading from stdin...")
// Read email from stdin
emailData, err := io.ReadAll(os.Stdin)
if err != nil {
log.Fatalf("Failed to read email from stdin: %v", err)
}
// If recipient not provided, try to extract from headers
var recipient string
if *recipientEmail != "" {
recipient = *recipientEmail
} else {
recipient, err = receiver.ExtractRecipientFromHeaders(emailData)
if err != nil {
log.Fatalf("Failed to extract recipient: %v", err)
}
log.Printf("Extracted recipient: %s", recipient)
}
// Process the email
recv := receiver.NewEmailReceiver(store, cfg)
if err := recv.ProcessEmailBytes(emailData, recipient); err != nil {
log.Fatalf("Failed to process email: %v", err)
}
log.Println("Email processed successfully")
}
func printUsage() {
fmt.Println("\nCommand availables:")
fmt.Println(" happyDeliver server - Start the API server")
fmt.Println(" happyDeliver analyze [-recipient EMAIL] - Analyze email from stdin (MDA mode)")
fmt.Println(" happyDeliver version - Print version information")
fmt.Println(" happyDeliver server - Start the API server")
fmt.Println(" happyDeliver analyze [-json] - Analyze email from stdin and output results to terminal")
fmt.Println(" happyDeliver version - Print version information")
fmt.Println("")
flag.Usage()
}