1 回答

TA貢獻1828條經驗 獲得超6個贊
使用Go 1.16,您現在可以使用源代碼中的指令嵌入文件和目錄。//go:embed
下面是 的軟件包文檔。embed
這是Carl Johnson的一篇博客文章,Go博客在軟件包發布時引用了該博客。embed
您的用例聽起來好像您可以從嵌入目錄和使用http中受益。文件服務器
。在鏈接的博客文章中有一個示例。我也把它貼在下面。
此示例演示如何嵌入通過 HTTP 調用和服務的目錄:static
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)
}
- 1 回答
- 0 關注
- 121 瀏覽
添加回答
舉報