In go, we can handle static files, by defining their directory as static directory as shown below:
fs := http.FileServer(http.Dir("./static/"))
http.Handle("/files/", fs)
Where static files folder static
should be beside the binary.
Another way, is to use the new //go embed
as:
//go:embed static
var staticFiles embed.FS
// http.FS can be used to create a http Filesystem
var staticFS = http.FS(staticFiles)
fs := http.FileServer(staticFS) // embeded static files
// Serve static files
http.Handle("/static/", fs)
But what if I want to have most of my static files embedded in the binary, and some are not, that can be used alongside the binary, I tried to mix both method defined above, but did not work, only the embedded
ones run smoothly, below code failed, any thought?:
//go:embed static
var staticFiles embed.FS
// http.FS can be used to create a http Filesystem
var staticFS = http.FS(staticFiles)
fs := http.FileServer(staticFS) // embeded static files
// Serve static files
http.Handle("/static/", fs)
www := http.FileServer(http.Dir("./files/")) // side static files, to be beside binary
// Serve static files
http.Handle("/files/", www)