问题的摘要:对目录中的嵌入式文件的访问适用于本机编译,而不是跨编译代码。
下面的代码将文件(static/index.html
)嵌入到目录中并通过HTTP公开:
package main
import (
"embed"
"net/http"
"os"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/rs/cors"
"github.com/rs/zerolog/log"
)
//go:embed static
var content embed.FS
func main() {
// API and static site
r := mux.NewRouter()
r.Use(mux.CORSMethodMiddleware(r))
r.Use(func(next http.Handler) http.Handler {
return handlers.LoggingHandler(os.Stdout, next)
})
c := cors.New(cors.Options{
AllowCredentials: true,
//Debug: true,
})
handler := c.Handler(r)
r.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/")))
log.Info().Msg("starting dash webserver at port 1495")
_ = http.ListenAndServe("0.0.0.0:1495", handler)
}
我通过go1.16.7
在Windows 10 WSL2 (编辑:和本机Windows 10)中编译了这段代码( go build -o goembed.wsl2
)。启动时,运行curl localhost:1495
会给出正确的结果(index.html
中的文本)。
然后我通过env GOOS=linux GOARCH=amd64 go build -o goembed.linux
编译了它(仍然在WSL2 2/ via 10中)(或者在Windows 10中使用相关的咒语来设置环境变量),并在Ubuntu18.04服务器上启动了goembed.linux
。
程序启动,但curl localhost:1495
的输出为404 File Not Found
。
为什么会这样呢?
有趣的是,嵌入单个文件(包含它的变量为[]byte
类型)在两个二进制文件(本机WSL和amd64)中通过HTTP服务器正确地公开了它。
编辑:在本机Windows 10中编译时,我有相同的行为,我更新了上面的引用
发布于 2021-08-11 09:18:56
这是我的一个错误:我嵌入了static
,但是服务于./static/
,它是本地(OS)目录,而不是嵌入式目录。它应该是:
r.PathPrefix("/").Handler(http.FileServer(http.FS(content)))
https://stackoverflow.com/questions/68730329
复制相似问题