package themes // Declare the package at the top import ( "fmt" "html/template" "net/http" "os" "path/filepath" "strings" ) // ThemeManager manages themes for the blog system type ThemeManager struct { CurrentTheme string // Name of the currently active theme Templates map[string]*template.Template // Cached compiled HTML templates } // LoadTheme loads a specified theme by its name func (tm *ThemeManager) LoadTheme(themeName string) error { // 1. 读取theme.yaml验证主题有效性 // 2. 预编译所有HTML模板,缓存到Templates // 3. 注册静态资源路由:/themes/[name]/static/*filepath tm.CurrentTheme = themeName // Step 1: Validate the theme by reading theme.yaml themeConfigPath := fmt.Sprintf("h:/code/go_blog/themes/%s/theme.yaml", themeName) if _, err := os.Stat(themeConfigPath); os.IsNotExist(err) { return fmt.Errorf("theme %s does not exist or is invalid", themeName) } // Step 2: Precompile all HTML templates and cache them tm.Templates = make(map[string]*template.Template) templateDir := fmt.Sprintf("h:/code/go_blog/themes/%s/templates", themeName) err := filepath.Walk(templateDir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() && strings.HasSuffix(info.Name(), ".html") { tmpl, err := template.ParseFiles(path) if err != nil { return err } tm.Templates[info.Name()] = tmpl } return nil }) if err != nil { return fmt.Errorf("failed to load templates: %v", err) } // Step 3: Register static resource routes http.Handle(fmt.Sprintf("/themes/%s/static/", themeName), http.StripPrefix(fmt.Sprintf("/themes/%s/static/", themeName), http.FileServer(http.Dir(fmt.Sprintf("h:/code/go_blog/themes/%s/static", themeName))))) return nil } func NewManager() *ThemeManager { return &ThemeManager{} }