crm/cmd/server/main.go

119 lines
2.9 KiB
Go

package main
import (
"crm-go/internal/handlers"
"crm-go/internal/middleware"
"crm-go/internal/storage"
"log"
"net/http"
"os"
"path/filepath"
"strings"
)
func main() {
// Initialize storage
customerStorage := storage.NewCustomerStorage("./data/customers.json")
// Initialize handlers
customerHandler := handlers.NewCustomerHandler(customerStorage)
authHandler := handlers.NewAuthHandler()
// Enable CORS manually
corsHandler := func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
h.ServeHTTP(w, r)
})
}
// Auth routes
http.HandleFunc("/api/login", authHandler.Login)
// Set up routes using standard http
http.HandleFunc("/api/customers", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
customerHandler.GetCustomers(w, r)
case "POST":
customerHandler.CreateCustomer(w, r)
default:
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
}
})
http.HandleFunc("/api/customers/", func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path
// Handle import endpoint
if path == "/api/customers/import" {
if r.Method == "POST" {
customerHandler.ImportCustomers(w, r)
return
}
}
// Handle customer ID endpoints
if strings.HasPrefix(path, "/api/customers/") && path != "/api/customers/" {
// Extract customer ID from URL
id := strings.TrimPrefix(path, "/api/customers/")
// Remove query parameters if any
if idx := strings.Index(id, "?"); idx != -1 {
id = id[:idx]
}
if id != "" {
if r.Method == "GET" {
customerHandler.GetCustomerByID(w, r)
return
}
if r.Method == "PUT" {
customerHandler.UpdateCustomer(w, r)
return
}
if r.Method == "DELETE" {
customerHandler.DeleteCustomer(w, r)
return
}
}
}
http.NotFound(w, r)
})
// Serve static files for the frontend
staticDir := "./frontend"
if _, err := os.Stat(staticDir); os.IsNotExist(err) {
// Create basic frontend directory if it doesn't exist
os.MkdirAll(staticDir, 0755)
}
// Serve static files
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./frontend"))))
// Serve index page
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filepath.Join("./frontend", "index.html"))
})
// Assemble final handler chain: DefaultServeMux -> AuthMiddleware -> CorsHandler
finalHandler := middleware.AuthMiddleware(http.DefaultServeMux)
port := os.Getenv("PORT")
if port == "" {
port = "8081"
}
addr := ":" + port
log.Println("Server starting on " + addr)
log.Fatal(http.ListenAndServe(addr, corsHandler(finalHandler)))
}