3 回答

TA貢獻1877條經驗 獲得超1個贊
一種選擇是使用http.Dir實現http.FileSystem。這種方法的優點是它利用了 http.FileServer 中精心編寫的代碼。
它看起來像這樣:
type HTMLDir struct {
? ? d http.Dir
}
func main() {
? fs := http.FileServer(HTMLDir{http.Dir("public/")})
? http.Handle("/", http.StripPrefix("/", fs))
? http.ListenAndServe(":8000", nil)
}
Open方法的實現取決于應用程序的需求。
如果您總是想附加 .html 擴展名,請使用以下代碼:
func (d HTMLDir) Open(name string) (http.File, error) {
? ? return d.d.Open(name + ".html")
}
如果您想回退到 .html 擴展名,請使用以下代碼:
func (d HTMLDir) Open(name string) (http.File, error) {
? ? // Try name as supplied
? ? f, err := d.d.Open(name)
? ? if os.IsNotExist(err) {
? ? ? ? // Not found, try with .html
? ? ? ? if f, err := d.d.Open(name + ".html"); err == nil {
? ? ? ? ? ? return f, nil
? ? ? ? }
? ? }
? ? return f, err
}
將前一個翻轉過來,以 .html 擴展名開始,然后回退到所提供的名稱:
func (d HTMLDir) Open(name string) (http.File, error) {
? ? // Try name with added extension
? ? f, err := d.d.Open(name + ".html")
? ? if os.IsNotExist(err) {
? ? ? ? // Not found, try again with name as supplied.
? ? ? ? if f, err := d.d.Open(name); err == nil {
? ? ? ? ? ? return f, nil
? ? ? ? }
? ? }
? ? return f, err
}

TA貢獻1824條經驗 獲得超5個贊
因此,基本上您需要該http.FileServer功能,但不希望客戶端必須輸入尾隨.html擴展名。
另一個簡單的解決方案是在服務器端自行添加??梢赃@樣做:
fs := http.FileServer(http.Dir("public"))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
r.URL.Path += ".html"
fs.ServeHTTP(w, r)
})
panic(http.ListenAndServe(":8000", nil))
就這樣。
如果您希望此文件服務器還提供其他文件(例如圖像和 CSS 文件),則僅.html在沒有擴展名的情況下附加擴展名:
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
if ext := path.Ext(r.URL.Path); ext == "" {
r.URL.Path += ".html"
}
fs.ServeHTTP(w, r)
})

TA貢獻2065條經驗 獲得超14個贊
這是可能的,但不能通過使用http.FileServer().
相反,為該/路由創建一個自定義處理程序。在處理程序內部,使用 直接提供請求的文件http.ServeFile()。
viewPath := "public/"
http.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// hack, if requested url is / then point towards /index
if r.URL.Path == "/" {
r.URL.Path = "/index"
}
requestedPath := strings.TrimLeft(filepath.Clean(r.URL.Path), "/")
filename := fmt.Sprintf("%s/%s.html", viewPath, requestedPath)
http.ServeFile(w, r, filename)
}))
http.ListenAndServe(":8000", nil)
該.html后綴被添加到每個請求路徑中,因此它將正確指向 html 文件。
path / -> ./public/index.html
path /index -> ./public/index.html
path /some/folder/about -> ./public/some/folder/about.html
...
- 3 回答
- 0 關注
- 190 瀏覽
添加回答
舉報