255 lines
7.5 KiB
Go
255 lines
7.5 KiB
Go
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, `
|
|
<!DOCTYPE html>
|
|
<html><head><meta charset="utf-8"><title>Erro 502</title>
|
|
<style>body{background:#090d16;color:#f3f4f6;font-family:sans-serif;padding:3rem;text-align:center;}</style></head>
|
|
<body>
|
|
<h1>502 Bad Gateway</h1>
|
|
<p>Não foi possível conectar ao app <strong>%s</strong> na porta interna <strong>:%d</strong>.</p>
|
|
<p><a href="/" style="color:#38bdf8;">Voltar ao Dashboard</a></p>
|
|
</body></html>
|
|
`, 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, `
|
|
<!DOCTYPE html>
|
|
<html><head><meta charset="utf-8"><title>Iniciando...</title>
|
|
<style>body{background:#090d16;color:#f3f4f6;font-family:sans-serif;padding:3rem;text-align:center;}</style></head>
|
|
<body>
|
|
<h2>🚀 Aplicação '%s' está iniciando...</h2>
|
|
<p>Aguarde um instante. Esta página será recarregada automaticamente.</p>
|
|
</body></html>
|
|
`, 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, `
|
|
<!DOCTYPE html>
|
|
<html><head><meta charset="utf-8"><title>App Crashed</title>
|
|
<style>body{background:#090d16;color:#f3f4f6;font-family:sans-serif;padding:2rem;}pre{background:#111827;padding:1rem;border-radius:8px;color:#f87171;overflow:auto;}</style></head>
|
|
<body>
|
|
<h2>❌ O app '%s' encerrou inesperadamente (Crash)</h2>
|
|
<p>Verifique se o binário está escutando na variável de ambiente <code>PORT</code>.</p>
|
|
<p><a href="/" style="color:#38bdf8;">← Voltar ao Dashboard</a></p>
|
|
</body></html>
|
|
`, 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, `
|
|
<!DOCTYPE html>
|
|
<html><head><meta charset="utf-8"><title>App Não Encontrado</title>
|
|
<style>body{background:#090d16;color:#f3f4f6;font-family:sans-serif;padding:3rem;text-align:center;}a{color:#38bdf8;}</style></head>
|
|
<body>
|
|
<h1>404 - Aplicação Não Encontrada</h1>
|
|
<p>Não há nenhum binário ativo na pasta <code>%s/%s</code>.</p>
|
|
<p style="margin-top:1.5rem;"><a href="/">← Ir para o Dashboard do Mini PaaS</a></p>
|
|
</body></html>
|
|
`, 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 ""
|
|
}
|