Embed tips – dynamic file update

Time:2021-6-23

Go1.16 embed can embed the file into the compiled binary. When a web program is published in the future, it can only provide one binary program without other files and avoid repeated file reading.

However, in the development, if the front-end file is modified after using embed, the Go program needs to be restarted to regenerate the embedded data, which makes the development process inconvenient.

This paper provides a trick to support dynamic files with embedded. Use http.dir and embedded.fs to mix and combine a new http.filesystem. If there are static files in the current directory, use http.dir to return the contents of the static files. Otherwise, use embedded.fs to compile the contents. In this way, you can use http.dir to access the static files, You can make the published binaries use embed.fs to compile the built-in static file data.

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),
    }))
}

//Combining multiple http.filesystem
type FileSystems []http.FileSystem

func (fs FileSystems) Open(name string) (file http.File, err error) {
    for _, i := range fs {
        //Open multiple http. File systems in turn and return a successfully opened data.
        file, err = i.Open(name)
        if err == nil {
            return
        }
    }
    return
}

Create a static directory in the code directory, and then create an index.html auth.html in it, which can be used after starting the programlocalhost:8088/static/index.htmlAccess to the static file, after modifying the file will not restart will also display the latest file content.

This work adoptsCC agreementReprint must indicate the author and the link of this article