首页 > 解决方案 > 嵌入目录是否支持交叉编译?

问题描述

问题总结:对目录中嵌入文件的访问适用于本机编译,但不适用于交叉编译代码

我有以下代码将文件 ( 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:1495404 File Not Found.

为什么会这样?

有趣的是,嵌入单个文件(包含它的变量类型为[]byte)通过 HTTP 服务器在两个二进制文件(本机 WSL 文件和 amd64)中正确公开它。

编辑:在本机 Windows 10 中编译时我有相同的行为,我更新了上面的引用

标签: goembedcross-compiling

解决方案


这是我的一个错误:我嵌入static但服务./static/本地(OS)目录,而不是嵌入的目录。它应该是:

r.PathPrefix("/").Handler(http.FileServer(http.FS(content)))

推荐阅读