相关疑难解决方法(0)

你如何使用 Go 1.16 在子文件夹/包中嵌入功能?

Go 1.16 已经发布,我想使用新的嵌入功能。如果一切都在主包中,我可以让它工作。但是不清楚如何处理从子文件夹/包访问资源。尝试通过 embed.FS 支持来实现。

例如,我在处理程序包/文件夹中有一个 main.go 和一个 HTTP 处理程序

如果我将处理程序放在主程序中,它就可以工作。如果我把它放在处理程序包中,它找不到模板。我得到:

handlers/indexHandler.go:11:12: pattern templates: no matching files found exit status 1

同样,如果我从 / 提供它,我可以让它从静态文件夹提供图像。但是我不能同时提供来自 / 的处理程序和来自 / 的静态/图像。如果我将图像放在 /static/ 上,它找不到图像。

我认为这与相对路径有关。但是我无法通过反复试验找到正确的组合......依赖这些功能是否为时过早?

以前我用的是 go-rice,我没有这些问题。但我想尽可能多地使用 std 库。

main.go:

package main

import (...)

//go:embed static
var static embed.FS

func main() {

    fsRoot, _ := fs.Sub(static, "static")
    fsStatic := http.FileServer(http.FS(fsRoot))
    http.Handle("/", fsStatic)
    http.HandleFunc("/index", Index)
    http.ListenAndServe(":8080", nil)
}
Run Code Online (Sandbox Code Playgroud)

处理程序/indexHandler.go:

package handlers

import (...)

//go:embed templates
var templates embed.FS

// Index handler
func Index(w http.ResponseWriter, r …
Run Code Online (Sandbox Code Playgroud)

go go-http

8
推荐指数
1
解决办法
3421
查看次数

标签 统计

go ×1

go-http ×1