package proxy import ( "encoding/json" "fmt" "log" "net/http" "net/http/httputil" "net/url" "strings" "sync" "mini-paas/internal/config" "mini-paas/internal/supervisor" "mini-paas/internal/ui" ) type Server struct { cfg *config.Config manager *supervisor.Manager proxies map[int]*httputil.ReverseProxy mu sync.RWMutex } func NewServer(cfg *config.Config, mgr *supervisor.Manager) *Server { return &Server{ cfg: cfg, manager: mgr, proxies: make(map[int]*httputil.ReverseProxy), } } func (s *Server) getOrCreateProxy(port int, appName string, isSubdomain bool) *httputil.ReverseProxy { s.mu.Lock() defer s.mu.Unlock() targetURL, _ := url.Parse(fmt.Sprintf("http://127.0.0.1:%d", port)) // Cria proxy com reescrita customizada proxy := httputil.NewSingleHostReverseProxy(targetURL) originalDirector := proxy.Director proxy.Director = func(req *http.Request) { originalDirector(req) // Se o roteamento foi por subcaminho, remove o prefixo /appName if !isSubdomain { prefix := "/" + appName if strings.HasPrefix(req.URL.Path, prefix) { req.URL.Path = strings.TrimPrefix(req.URL.Path, prefix) if !strings.HasPrefix(req.URL.Path, "/") { req.URL.Path = "/" + req.URL.Path } } if req.URL.RawPath != "" && strings.HasPrefix(req.URL.RawPath, prefix) { req.URL.RawPath = strings.TrimPrefix(req.URL.RawPath, prefix) if !strings.HasPrefix(req.URL.RawPath, "/") { req.URL.RawPath = "/" + req.URL.RawPath } } req.Header.Set("X-Forwarded-Prefix", prefix) } req.Header.Set("X-Forwarded-Host", req.Host) if req.Header.Get("X-Forwarded-Proto") == "" { req.Header.Set("X-Forwarded-Proto", "http") } } proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, err error) { log.Printf("[Proxy] Erro de conexão com app '%s' (: %d): %v", appName, port, err) w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusBadGateway) fmt.Fprintf(w, ` Erro 502

502 Bad Gateway

Não foi possível conectar ao app %s na porta interna :%d.

Voltar ao Dashboard

`, appName, port) } return proxy } func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // 1. Endpoints do PaaS if r.URL.Path == "/" { s.handleDashboard(w, r) return } if r.URL.Path == "/_paas/api/apps" { s.handleAPIApps(w, r) return } if r.URL.Path == "/_paas/api/logs" { s.handleAPILogs(w, r) return } // 2. Tenta extrair app por Subdomínio (ex: page-teste.paas.weltonmoura.com.br) subdomainApp := s.extractSubdomainApp(r.Host) if subdomainApp != "" { if app, exists := s.manager.GetApp(subdomainApp); exists { s.routeToApp(w, r, app, true) return } } // 3. Roteamento por Subcaminho (ex: /page_teste/...) pathParts := strings.Split(strings.TrimPrefix(r.URL.Path, "/"), "/") appName := pathParts[0] // Redireciona /page_teste -> /page_teste/ para garantir que caminhos relativos de assets funcionem corretamente if r.URL.Path == "/"+appName { http.Redirect(w, r, "/"+appName+"/", http.StatusMovedPermanently) return } app, exists := s.manager.GetApp(appName) if !exists { s.handleNotFound(w, r, appName) return } s.routeToApp(w, r, app, false) } func (s *Server) routeToApp(w http.ResponseWriter, r *http.Request, app *supervisor.AppInstance, isSubdomain bool) { if app.Status == supervisor.StatusStarting { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Refresh", "2") w.WriteHeader(http.StatusServiceUnavailable) fmt.Fprintf(w, ` Iniciando...

🚀 Aplicação '%s' está iniciando...

Aguarde um instante. Esta página será recarregada automaticamente.

`, app.Name) return } if app.Status == supervisor.StatusCrashed { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, ` App Crashed

❌ O app '%s' encerrou inesperadamente (Crash)

Verifique se o binário está escutando na variável de ambiente PORT.

← Voltar ao Dashboard

`, app.Name) return } proxy := s.getOrCreateProxy(app.Port, app.Name, isSubdomain) proxy.ServeHTTP(w, r) } func (s *Server) handleDashboard(w http.ResponseWriter, r *http.Request) { apps := s.manager.ListApps() data := ui.DashboardData{ Domain: s.cfg.Domain, Port: s.cfg.Port, AppsDir: s.cfg.AppsDir, ActiveCount: len(apps), Apps: apps, } w.Header().Set("Content-Type", "text/html; charset=utf-8") if err := ui.RenderDashboard(w, data); err != nil { http.Error(w, "Erro ao renderizar dashboard: "+err.Error(), http.StatusInternalServerError) } } func (s *Server) handleAPIApps(w http.ResponseWriter, r *http.Request) { apps := s.manager.ListApps() w.Header().Set("Content-Type", "application/json") _ = json.NewEncoder(w).Encode(apps) } func (s *Server) handleAPILogs(w http.ResponseWriter, r *http.Request) { appName := r.URL.Query().Get("app") if appName == "" { http.Error(w, "Parâmetro 'app' é obrigatório", http.StatusBadRequest) return } logs, err := s.manager.GetRecentLogs(appName) if err != nil { http.Error(w, err.Error(), http.StatusNotFound) return } w.Header().Set("Content-Type", "text/plain; charset=utf-8") for _, line := range logs { _, _ = w.Write([]byte(line)) } } func (s *Server) handleNotFound(w http.ResponseWriter, r *http.Request, appName string) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(http.StatusNotFound) fmt.Fprintf(w, ` App Não Encontrado

404 - Aplicação Não Encontrada

Não há nenhum binário ativo na pasta %s/%s.

← Ir para o Dashboard do Mini PaaS

`, s.cfg.AppsDir, appName) } func (s *Server) extractSubdomainApp(host string) string { // Remove a porta se houver (ex: page-teste.paas.local:8080) parts := strings.Split(host, ":") hostname := parts[0] // Se for exatamente o domínio configurado ou localhost ou IP, não é subdomínio de app if hostname == s.cfg.Domain || hostname == "localhost" || hostname == "127.0.0.1" { return "" } // Ex: app1.paas.weltonmoura.com.br -> extrai 'app1' if strings.HasSuffix(hostname, "."+s.cfg.Domain) { sub := strings.TrimSuffix(hostname, "."+s.cfg.Domain) if !strings.Contains(sub, ".") { return sub } } // Ex: app1.localhost -> extrai 'app1' if strings.HasSuffix(hostname, ".localhost") { sub := strings.TrimSuffix(hostname, ".localhost") if !strings.Contains(sub, ".") { return sub } } return "" }