如何FileServer在 Go 中為虛擬主機提供靜態檔案(使用 )?
如果我有自己的處理函式,任務似乎很容易解決 [ 1 ]:
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world!")
})
http.HandleFunc("qa.example.com/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, improved world!")
})
http.ListenAndServe(":8080", nil)
}
但是,如果我需要為FileServer虛擬主機提供靜態檔案(帶有 )怎么辦?
這個
r.PathPrefix("qa.example.com/").Handler(http.FileServer(http.Dir("/static/qa/")))
不起作用——它只是被忽略了。
我究竟做錯了什么?這種方法通常是錯誤的嗎?
uj5u.com熱心網友回復:
package main
import (
"embed"
"fmt"
"net/http"
"strings"
"time"
)
//go:embed *.go
var f embed.FS
func main() {
// embed.Fs defaule modtime use now or env value.
now := time.Now()
// use mapping host to http.FileSystem
vhosts := make(map[string]http.FileSystem)
vhosts["qa.example.com"] = http.FS(f) // from embed.FS
vhosts["my.example.com"] = http.Dir(".") // from http.Dir
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, world!")
})
http.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) {
// find host
fs, ok := vhosts[r.Host]
if !ok {
w.WriteHeader(404)
w.Write([]byte("404 not found vhost"))
return
}
// open file from http.FileSystem
file, err := fs.Open(strings.TrimPrefix(r.URL.Path, "/static/"))
if err != nil {
// reference go1.18.3/net/http/fs.go toHTTPError function hander file error.
w.Write([]byte("check err is 403 or 404 or 500"))
return
}
stat, _ := file.Stat()
// fix embed modtime is zero.
modtime := stat.ModTime()
if modtime.IsZero() {
modtime = now
}
// response
http.ServeContent(w, r, stat.Name(), modtime, file)
})
http.ListenAndServe(":8080", nil)
}
運行 test exec command curl -H "Host: my.example.com" 127.0.0.1:8080/static/01.go,01.go 替換您的靜態檔案名。
uj5u.com熱心網友回復:
注冊一個處理程式host/path。/path僅在呼叫檔案處理程式時剝離部分。
此注冊為qa.example.com/static/*目錄中的檔案提供服務./static/qa/。
http.HandleFunc("qa.example.com/static/", http.StripPrefix("/static", http.FileServer(http.Dir("./static/qa/")))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/493481.html
