From 8a2207bd29a97f27a7a08c0542c7a6154d9af542 Mon Sep 17 00:00:00 2001 From: wood chen Date: Sat, 15 Feb 2025 09:40:52 +0800 Subject: [PATCH] feat(templates): Implement template rendering for admin routes - Replace static file serving with Go template rendering - Add template parsing for login, metrics, and config pages - Set appropriate content type headers for HTML responses - Improve error handling for template rendering - Enhance logging for template-related errors --- main.go | 34 +++++++++++++++++++++++++++++++--- 1 file changed, 31 insertions(+), 3 deletions(-) diff --git a/main.go b/main.go index dc8e2ad..8d92865 100644 --- a/main.go +++ b/main.go @@ -13,6 +13,7 @@ import ( "proxy-go/internal/middleware" "strings" "syscall" + "text/template" ) func main() { @@ -22,6 +23,17 @@ func main() { log.Fatal("Error loading config:", err) } + // 加载模板 + tmpl, err := template.ParseFiles( + "/app/web/templates/admin/layout.html", + "/app/web/templates/admin/login.html", + "/app/web/templates/admin/metrics.html", + "/app/web/templates/admin/config.html", + ) + if err != nil { + log.Fatal("Error parsing templates:", err) + } + // 更新常量配置 constants.UpdateFromConfig(cfg) @@ -63,11 +75,27 @@ func main() { switch r.URL.Path { case "/admin/login": log.Printf("[Debug] 提供登录页面,文件路径: /app/web/templates/admin/login.html") - http.ServeFile(w, r, "/app/web/templates/admin/login.html") + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if err := tmpl.ExecuteTemplate(w, "login.html", nil); err != nil { + log.Printf("[Error] 渲染登录页面失败: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } case "/admin/metrics": - proxyHandler.AuthMiddleware(proxyHandler.MetricsHandler)(w, r) + proxyHandler.AuthMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if err := tmpl.ExecuteTemplate(w, "metrics.html", nil); err != nil { + log.Printf("[Error] 渲染监控页面失败: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } + }))(w, r) case "/admin/config": - proxyHandler.AuthMiddleware(handler.NewConfigHandler(cfg).ServeHTTP)(w, r) + proxyHandler.AuthMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + if err := tmpl.ExecuteTemplate(w, "config.html", nil); err != nil { + log.Printf("[Error] 渲染配置页面失败: %v", err) + http.Error(w, "Internal Server Error", http.StatusInternalServerError) + } + }))(w, r) case "/admin/config/get": proxyHandler.AuthMiddleware(handler.NewConfigHandler(cfg).ServeHTTP)(w, r) case "/admin/config/save":