go - 未搜索 Html 模板文件

标签 go goland

关于

我正在尝试查找 GO 编程语言中许多嵌套子文件夹下存在的文件。

问题详细信息

下面有两个代码块。第一个(工作代码)工作正常,因为下面的代码行

templates = template.Must(template.ParseGlob("templates/front/auth/login/*.html"))

第二个代码块(不工作代码)由于以下行而无法工作。

templates = template.Must(template.ParseGlob("*.*"))

当我尝试使用下面的代码打印 html 搜索文件时...它仅列出 main.go

fmt.Println(templates.DefinedTemplates())

enter image description here

以上是目录结构。 Go文件夹是根目录。它包含两个子文件夹。

  1. static folder - for keeping css and js folders
  2. templates - for keeping html files

工作代码

package main

import (
    "fmt"
    "html/template"
    "net/http"
)

var templates *template.Template

func loginhandler(w http.ResponseWriter, r *http.Request) { 
    templates.ExecuteTemplate(w, "login.html", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
    switch r.URL.Path {
    case "/login":
        loginhandler(w, r)
    }
}

func main() {
    http.HandleFunc("/", handler)
    
    templates = template.Must(template.ParseGlob("templates/front/auth/login/*.html"))
    fmt.Println(templates.DefinedTemplates())

    http.ListenAndServe(":8080", nil)
}

代码不工作

package main

import (
    "fmt"
    "html/template"
    "net/http"
)

var templates *template.Template

func loginhandler(w http.ResponseWriter, r *http.Request) { 
    templates.ExecuteTemplate(w, "login.html", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
    switch r.URL.Path {
    case "/login":
        loginhandler(w, r)
    }
}

func main() {
    http.HandleFunc("/", handler)
    
    templates = template.Must(template.ParseGlob("*.*"))
    fmt.Println(templates.DefinedTemplates())

    http.ListenAndServe(":8080", nil)
}

如果您需要更多信息,请告诉我

最佳答案

参数“*.*”仅匹配当前目录中具有任何扩展名的文件。它不遍历子目录。

Go's filepath.Glob pattern , * 匹配任何非分隔符字符序列,并且 ** is not supported就像某些 shell (bash v4) 或其他语言(例如 Python)中一样。所以它无法匹配子目录中的文件。

如果要解析templates目录下的所有.html文件及其子目录,则需要显式给出路径。

由于您提到目录结构可能包含多个嵌套子文件夹,并且您的文件采用 .html 格式,不幸的是,您需要手动列出每个目录。 Go的标准库不支持使用**进行递归搜索。

但是,您可以编写一个函数来遍历目录并选择所需的文件。
这是an example :

package main

import (
    "fmt"
    "html/template"
    "net/http"
    "path/filepath"
    "strings"
)

var templates *template.Template

func loginhandler(w http.ResponseWriter, r *http.Request) { 
    templates.ExecuteTemplate(w, "login.html", nil)
}

func handler(w http.ResponseWriter, r *http.Request) {
    switch r.URL.Path {
    case "/login":
        loginhandler(w, r)
    }
}

func parseHTMLTemplates(root string) (*template.Template, error) {
    var allFiles []string

    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if !info.IsDir() && strings.HasSuffix(info.Name(), ".html") {
            allFiles = append(allFiles, path)
        }
        return nil
    })
    if err != nil {
        return nil, err
    }

    templates, err := template.ParseFiles(allFiles...)
    return templates, err
}

func main() {
    http.HandleFunc("/", handler)
    
    var err error
    templates, err = parseHTMLTemplates("./templates")
    if err != nil {
        panic(err)
    }
    
    fmt.Println(templates.DefinedTemplates())

    http.ListenAndServe(":8080", nil)
}

parseHTMLTemplates 函数将递归地遍历 templates 目录并收集所有 .html 文件。然后它将解析所有这些文件并返回*template.Template。这样,您就不必手动列出每个目录。

注意:代码中使用了filepath.Walk函数来遍历以root为根的目录树中的所有文件。为树中的每个文件或目录调用提供给 filepath.Walk 的函数,包括 root。如果filepath.Walk遇到错误,它将被传递给filepath.Walk提供的函数。如果函数返回错误,则行走停止。

strings.HasSuffix(info.Name(), ".html") 检查可确保我们的模板仅考虑 .html 文件。如果您要考虑其他文件类型,您可能需要更新此检查或使其更加复杂。

关于go - 未搜索 Html 模板文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59041875/

相关文章:

azure - VS Code + Go 扩展 : Turn off Workspace loading

go - 无法在 Intellij 2020.1 中的 golang 包中设置断点

debugging - GoLand 在 macOS Sierra 上调试运行失败

go - 列出在 Go 中实现接口(interface)的所有类型

git - 我无法从 CircleCi 上的多个存储库中克隆

go - 如何将错误消息从 C 传递给 Go?

go - 在 Go amqp 客户端中设置连接友好名称

go - 在 IntelliJ 中保存文件时执行 gofmt

testing - Go gRPC 服务器使集成测试失败

go - 打开数据通道的请求不包含 token