1 回答
TA贡献1946条经验 获得超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
})
(如果代码不好,请优化,我自己做了解决方案,我尝试了很多东西来满足我的需要)
现在,我收到了带有正确标头的正确文件。
而且我找不到任何解决方案来处理http.FileServer在 http 包中使用的自定义标头。如果存在,请提供一个简单的解决方案。
- 1 回答
- 0 关注
- 138 浏览
添加回答
举报