package publicweb import ( "encoding/json" "net/http" "github.com/gorilla/mux" "github.com/rs/zerolog/log" ) func (s *PublicWebServer) setupAPIRoutes(r *mux.Router) { api := r.PathPrefix("/api").Subrouter() api.HandleFunc("/contact", s.contactHandler).Methods("POST", "OPTIONS") } func (s *PublicWebServer) contactHandler(w http.ResponseWriter, r *http.Request) { // Handle CORS preflight if r.Method == "OPTIONS" { w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS") w.Header().Set("Access-Control-Allow-Headers", "Content-Type") w.WriteHeader(http.StatusOK) return } var data map[string]any if err := json.NewDecoder(r.Body).Decode(&data); err != nil { log.Error().Err(err).Msg("Failed to decode contact request") http.Error(w, "Invalid request body", http.StatusBadRequest) return } if len(data) == 0 { http.Error(w, "Request body cannot be empty", http.StatusBadRequest) return } // Structure data for email template emailData := map[string]any{ "baseUrl": s.cfg.GetString("base_url"), "fields": data, } // Send email using the mailer contactEmail := s.cfg.GetString("server.publicweb.contact_email") if contactEmail == "" { log.Error().Msg("Contact email not configured") http.Error(w, "Contact service not configured", http.StatusInternalServerError) return } if err := s.mailer.Send("contact.request", contactEmail, emailData); err != nil { log.Error().Err(err).Msg("Failed to send contact email") http.Error(w, "Failed to send message", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(map[string]string{ "status": "success", "message": "Message sent successfully", }) }