The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
eudore

embed 小技巧-动态文件更新

  •  
  •   eudore · Feb 22, 2021 · 2573 views
    This topic created in 1907 days ago, the information mentioned may be changed or developed.

    go1.16 embed 可以将文件嵌入到编译后的二进制中,以后发布一个 web 程序可以只提供一个二进制程序,不需要其他文件,同时避免重复文件 io 读取。

    但是在开发时,使用 embed 后如果修改前端文件那么需要重启 GO 程序,重新生成 embed 数据,导致开发过程不方便。

    提供一个 embed 支持动态文件的小技巧,使用 http.Dir 和 embed.FS 混合组合一个新的 http.FileSystem,如果当前目录存在静态文件,那么使用 http.Dir 返回静态文件内容,否则使用 embed.FS 编译的内容,这样既可以使用 http.Dir 访问时时的静态文件,可以使发布的二进制程序使用 embed.FS 编译内置的静态文件数据。

    package main
    
    import (
    	"embed"
    	"net/http"
    )
    
    //go:embed static
    var f embed.FS
    
    func main() {
    	http.ListenAndServe(":8088", http.FileServer(FileSystems{
    		http.Dir("."),
    		http.FS(f),
    	}))
    }
    
    // 组合多个 http.FileSystem
    type FileSystems []http.FileSystem
    
    func (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 访问到静态文件,在修改文件后不重启也会显示最新的文件内容。

    7 replies    2021-02-23 14:15:38 +08:00
    freestyle
        1
    freestyle  
       Feb 23, 2021 via iPhone
    tairan2006
        2
    tairan2006  
       Feb 23, 2021
    我还在等 brew 发 1.16 呢……
    zhs227
        3
    zhs227  
       Feb 23, 2021
    @tairan2006 可以使用 gvm,已经用上 1.6 了。
    zhs227
        4
    zhs227  
       Feb 23, 2021
    typo: 1.6 -> 1.16
    tairan2006
        5
    tairan2006  
       Feb 23, 2021
    @zhs227 懒得搞,golang 兼容性还行,一直用最新版…java 和 node 倒是用了版本管理
    kuoruan
        6
    kuoruan  
       Feb 23, 2021
    @tairan2006 哈哈,我也在等,天天在看状态
    https://github.com/Homebrew/homebrew-core/pull/71289

    最后一个前置修改刚刚已经 merge 了,现在正在跑 Test,应该马上就会合并了
    mauve
        7
    mauve  
    PRO
       Feb 23, 2021
    nice idea, 顺便问一下楼主那边,后端 host 一个静态文件服务器的应用场景是什么样的?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   914 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 20:44 · PVG 04:44 · LAX 13:44 · JFK 16:44
    ♥ Do have faith in what you're doing.