1 回答

TA貢獻1946條經(jīng)驗 獲得超3個贊
所以我不得不編寫自己的文件服務器來手動設置標頭,例如:
contentTypeMap := map[string]string{
".html": "text/html",
".css": "text/css",
".js": "application/javascript",
}
filepath.Walk("./dist", func(path string, info os.FileInfo, err error) error {
if err != nil {
log.Fatalf(err.Error())
}
if info.IsDir() {
return err
}
dirPath := filepath.ToSlash(filepath.Dir(path))
contentType := contentTypeMap[filepath.Ext(info.Name())]
handlePath := "/" + strings.Join(strings.Split(dirPath, "/")[1:], "/")
hf := func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", contentType) // <---- key part
http.ServeFile(w, r, path)
}
if handlePath != "/" {
handlePath += "/" + info.Name()
}
mainRouter.HandleFunc(handlePath, hf)
return nil
})
(如果代碼不好,請優(yōu)化,我自己做了解決方案,我嘗試了很多東西來滿足我的需要)
現(xiàn)在,我收到了帶有正確標頭的正確文件。
而且我找不到任何解決方案來處理http.FileServer在 http 包中使用的自定義標頭。如果存在,請?zhí)峁┮粋€簡單的解決方案。
- 1 回答
- 0 關注
- 175 瀏覽
添加回答
舉報