我正在io/ioutil阅读一个小文本文件:
fileBytes, err := ioutil.ReadFile("/absolute/path/to/file.txt")
Run Code Online (Sandbox Code Playgroud)
这样做很好,但这不是完全可移植的.在我的例子中,我要打开的文件在我的GOPATH中,例如:
/Users/matt/Dev/go/src/github.com/mholt/mypackage/data/file.txt
Run Code Online (Sandbox Code Playgroud)
由于data文件夹与源代码一起使用,我只想指定相对路径:
data/file.txt
Run Code Online (Sandbox Code Playgroud)
但后来我得到了这个错误:
恐慌:打开data/file.txt:没有这样的文件或目录
如何使用相对路径打开文件,特别是如果它们与我的Go代码一起使用?
我基本上试图浏览一个html文件的文件夹.我想将它们嵌入到二进制文件中,并能够根据模板执行目的请求解析它们.(如果我没有正确措辞,请原谅我).
任何想法,提示,技巧或更好的方法来实现这一点非常感谢.
// Template Files
type TempFiles struct {
Files map[string]string
}
// Loop through view files and load them
func LoadTempFiles() {
t := new(TempFiles)
// Load template files
filepath.Walk("application/views", func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
content, _ := ioutil.ReadFile(path)
t.Files[path] = string(content)
}
return nil
})
}
func ViewTemp(w http.ResponseWriter, path string) {
t := new(TempFiles)
temp, err := template.New().Parse(t.Files[path])
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
} else {
temp.Execute(w, nil) …Run Code Online (Sandbox Code Playgroud) 我正在尝试实现一个简单的wiki,如图所示=> https://golang.org/doc/articles/wiki/
我知道已经多次询问过了,但是我无法在我的代码中加载静态内容.这是愚蠢的,我按照说明,让我为静态内容添加一个处理程序,但CSS仍然没有在html文件中使用.
我添加了这样的处理程序:
http.Handle("tmp/css", http.StripPrefix("tmp/css", http.FileServer(http.Dir("tmp/css"))))
http.Handle("tmp/img", http.StripPrefix("tmp/img", http.FileServer(http.Dir("tmp/img"))))
Run Code Online (Sandbox Code Playgroud)
整个代码可以在这里看到,在我的github页面上=> https://github.com/Skarlso/goprojects/tree/master/golangwiki
谢谢您的帮助!盖尔盖伊.
我有一组模板作为文件,例如base.html,,login.htmlprofile.html等header.html。它们以文件夹的形式组织。
在开发过程中将它们作为单独的文件很好,但是当我部署应用程序时,我希望将它们全部嵌入为字符串或解析和编译的模板,以便像往常一样从代码中使用。
我应该如何更好地将这些模板制作为 Go 代码?这样我就不必在生产中拥有templates文件夹,而是在单个可执行文件中拥有所有内容?
当我从除 main 之外的其他 go 文件访问文件时,如何处理文件路径。
\n在 other.go 文件中,我尝试运行 ParseFS,但它给出了 template:pattern matches no files:templates/test.tmpl错误。这是我的文件树。
\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 go.mod\n\xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 main\n\xe2\x94\x82 \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.go\n\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 other\n \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 other.go\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 templates\n \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 test.tmpl\nRun Code Online (Sandbox Code Playgroud)\n其他/其他.go
\npackage other\n\nimport (\n "embed"\n "fmt"\n "html/template"\n)\n\nvar templateFS embed.FS\n\nfunc Check() error {\n _, err := template.New("email").ParseFS(templateFS, "templates/"+ "test.tmpl")\n\n if err != nil {\n fmt.Println(err)\n }\n return nil\n}\nRun Code Online (Sandbox Code Playgroud)\n主/main.go
\nfunc main() {\n err :=othher.Check()\n\n if err != nil {\n fmt.Println(err)\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n