是否可以在 Golang 应用程序中嵌入 Angular?

问题描述

我想知道是否可以将 Angular gui(index.html、javascripts、css、图像等)嵌入到可执行的 go 应用程序中。

例如,Spring Boot (Java) 可以通过将编译后的 Angular 文件复制到 src/main/resources/static 文件夹中来做到这一点,然后将这些文件提供在根路径上(前提是具有 spring-boot- starter-web 依赖)。

Go 1.16 的新功能(2021 年 2 月)//go:embed 是否可以对整个文件夹执行此操作?

解决方法

使用 Go 1.16,您现在可以在源代码中使用 //go:embed 指令嵌入文件和目录。

这是 embedpackage documentation

这是在发布 embed 包时 Go 博客引用的 a blog post by Carl Johnson

您的用例听起来像是可以从嵌入目录和使用 http.FileServer 中受益。在链接的博客文章中有一个例子。我也贴在下面了。

此示例展示了如何嵌入名为 static 的目录并通过 HTTP 提供服务:

package main

import (
    "embed"
    "io/fs"
    "log"
    "net/http"
    "os"
)

func main() {
    useOS := len(os.Args) > 1 && os.Args[1] == "live"
    http.Handle("/",http.FileServer(getFileSystem(useOS)))
    http.ListenAndServe(":8888",nil)
}

//go:embed static
var embededFiles embed.FS

func getFileSystem(useOS bool) http.FileSystem {
    if useOS {
        log.Print("using live mode")
        return http.FS(os.DirFS("static"))
    }

    log.Print("using embed mode")
    fsys,err := fs.Sub(embededFiles,"static")
    if err != nil {
        panic(err)
    }

    return http.FS(fsys)
}