在go中,我们可以处理静态文件,通过将它们的目录定义为静态目录,如下所示:
fs := http.FileServer(http.Dir("./static/"))
http.Handle("/files/", fs)
静态文件文件夹 static
应位于二进制文件旁边的位置。
另一种方法是使用新的 //go embed
作为:
//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)
但是如果我想将我的大部分静态文件嵌入到二进制文件中,有些不是,可以与二进制文件一起使用,我试图混合上面定义的两种方法,但没有用,只有 { {1}} 个运行顺利,下面的代码失败了,有什么想法吗?:
embedded
答案 0 :(得分:0)
我找到了它,缺少 http.StripPrefix
,下面与我完美配合,并且有多个静态文件夹:
package main
import (
"embed"
"encoding/json"
"fmt"
"log"
"net/http"
)
//go:embed static
var staticFiles embed.FS
func main() {
go func() {
http.HandleFunc("/favicon.ico", func(rw http.ResponseWriter, r *http.Request) {})
// 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, to be embedded in the binary
http.Handle("/static/", fs)
// Serve public files, to be beside binary
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("./files"))))
http.HandleFunc("/getSkills", getSkills)
log.Println("Listening on :3000...")
err := http.ListenAndServe(":3000", nil)
if err != nil {
log.Fatal(err)
}
}