go1.16 embed能够将文件嵌入到编译后的二进制中,当前公布一个web程序能够只提供一个二进制程序,不须要其余文件,同时防止反复文件io读取。
然而在开发时,应用embed后如果批改前端文件那么须要重启GO程序,从新生成embed数据,导致开发过程不不便。
提供一个embed反对动静文件的小技巧,应用http.Dir和embed.FS混合组合一个新的http.FileSystem,如果当前目录存在动态文件,那么应用http.Dir返回动态文件内容,否则应用embed.FS编译的内容,这样既能够应用http.Dir拜访时时的动态文件,能够使公布的二进制程序应用embed.FS编译内置的动态文件数据。
package mainimport ( "embed" "net/http")//go:embed staticvar f embed.FSfunc main() { http.ListenAndServe(":8088", http.FileServer(FileSystems{ http.Dir("."), http.FS(f), }))}// 组合多个http.FileSystemtype FileSystems []http.FileSystemfunc (fs FileSystems) Open(name string) (file http.File, err error) { for _, i := range fs { // 顺次关上多个http.FileSystem返回一个胜利关上的数据。 file, err = i.Open(name) if err == nil { return } } return}
在代码目录创立一个static目录,而后外面创立一个index.html auth.html,启动程序后就能够应用http://localhost:8088/static/index.html拜访到动态文件,在批改文件后不重启也会显示最新的文件内容。