如何解决是否可以在 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
指令嵌入文件和目录。
这是 embed
的 package 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)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。