embed小技巧-動態文件更新

go1.16 embed能夠將文件嵌入到編譯後的二進制中,之後發佈一個web程序能夠只提供一個二進制程序,不須要其餘文件,同時避免重複文件io讀取。html

可是在開發時,使用embed後若是修改前端文件那麼須要重啓GO程序,從新生成embed數據,致使開發過程不方便。前端

提供一個embed支持動態文件的小技巧,使用http.Dir和embed.FS混合組合一個新的http.FileSystem,若是當前目錄存在靜態文件,那麼使用http.Dir返回靜態文件內容,不然使用embed.FS編譯的內容,這樣既能夠使用http.Dir訪問時時的靜態文件,能夠使發佈的二進制程序使用embed.FS編譯內置的靜態文件數據。web

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訪問到靜態文件,在修改文件後不重啓也會顯示最新的文件內容。code

相關文章
相關標籤/搜索