go - 嵌入目录是否支持交叉编译?
问题描述
问题总结:对目录中嵌入文件的访问适用于本机编译,但不适用于交叉编译代码
我有以下代码将文件 ( 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
然后我通过(或 Windows 10 中的相关咒语设置环境变量)编译它(仍在 WSL2/Win10中)并goembed.linux
在 Ubuntu 18.04 服务器上启动。
程序已启动,但输出curl localhost:1495
为404 File Not Found
.
为什么会这样?
有趣的是,嵌入单个文件(包含它的变量类型为[]byte
)通过 HTTP 服务器在两个二进制文件(本机 WSL 文件和 amd64)中正确公开它。
编辑:在本机 Windows 10 中编译时我有相同的行为,我更新了上面的引用
解决方案
这是我的一个错误:我嵌入static
但服务./static/
是本地(OS)目录,而不是嵌入的目录。它应该是:
r.PathPrefix("/").Handler(http.FileServer(http.FS(content)))
推荐阅读
- spring-boot - maven 在 springboot 的 META-INF/maven/plugin.xml 中找不到插件描述符
- javascript - 为什么在 jQuery 中添加类的函数不起作用?
- git - 如何将回购重置为另一个回购?
- google-bigquery - Bigquery 在数据中使用逗号拆分
- laravel - Laravel Vuejs,如何防止用户走一些路线并且仍然使该方法有效
- apache-nifi - 如何从第一行提取数据并放入nifi中的属性?
- python - RabbitMQ - 仅在满足条件时才使用
- pandas - 在 Pandas 数据框中创建一个包含布尔列组合计数的方阵
- java - 如何用Java中的不同值替换字符串中多次出现的相同正则表达式模式
- ios - SwiftUI onAppear 异步函数