Go 1.16已經出來了,我想使用新的嵌入功能。如果所有內容都在主包中,我可以讓它工作。但目前尚不清楚如何處理從子文件夾/包訪問資源。嘗試使用嵌入來執行此操作。金融服務支持。例如,我在處理程序包/文件夾中有一個main.go和一個HTTP處理程序如果我將處理程序放在主要位置,它就可以工作了。如果我把它放在處理程序包中,它找不到模板。我得到:handlers/indexHandler.go:11:12: pattern templates: no matching files found exit status 1同樣,如果我從 / 提供靜態文件夾中的圖像,我可以讓它從靜態文件夾中提供圖像。但是我不能同時提供來自 / 的處理程序和來自 / 的靜態/圖像。如果我將圖像放在/static/上,它找不到圖像。我認為這與相對路徑有關。但是我無法通過反復試驗找到正確的組合...依賴這些功能是否為時過早?以前我使用的是go-rice,我沒有這些問題。但我想盡可能多地使用std庫。main.go:package mainimport (...)//go:embed staticvar static embed.FSfunc main() { fsRoot, _ := fs.Sub(static, "static") fsStatic := http.FileServer(http.FS(fsRoot)) http.Handle("/", fsStatic) http.HandleFunc("/index", Index) http.ListenAndServe(":8080", nil)}handlers/indexHandler.go:package handlersimport (...)//go:embed templatesvar templates embed.FS// Index handlerfunc Index(w http.ResponseWriter, r *http.Request) { tmpl := template.New("") var err error if tmpl, err = tmpl.ParseFS(templates, "simple.gohtml"); err != nil { fmt.Println(err) } if err = tmpl.ExecuteTemplate(w, "simple", nil); err != nil { log.Print(err) } }結構如下....├── go.mod├── go.sum├── handlers│ └── indexHandler.go├── main.go├── static│ ├── css│ │ └── layout.css│ └── images│ └── logo.png└── templates └── simple.gohtml
2 回答

撒科打諢
TA貢獻1934條經驗 獲得超2個贊
我終于想通了...
您可以將模板文件夾保留在主文件夾中,然后從那里嵌入它們。然后,您需要將 FS 變量注入到另一個處理程序包中。在你弄清楚之后,它總是很容易的。
例如:
package main
//go:embed templates/*
var templateFs embed.FS
func main() {
handlers.TemplateFs = templateFs
...
package handlers
var TemplateFs embed.FS
func handlerIndex() {
...
tmpl, err = tmpl.ParseFS(TemplateFs, "templates/layout.gohtml",...
...

蝴蝶刀刀
TA貢獻1801條經驗 獲得超8個贊
目前在Go 1.17中,嵌入不支持子文件夾/包,請參閱 https://github.com/golang/go/issues/41191#issuecomment-686616556
- 2 回答
- 0 關注
- 207 瀏覽
添加回答
舉報
0/150
提交
取消