如何解决文件服务器返回 404
我真正想做的是提供两个目录作为文件服务器,/assets
和 /web/public
。作为参考,这是我的项目结构:
/root
/assets
/web
/public
/src
/templates
main.go
然而,当我运行服务器时,/public
路由返回 404,而资产很好。我梳理了参考资料和一堆教程,我所做的一切都应该在板子之上。
package main
import (
"fmt"
"html/template"
"log"
"net/http"
"os"
"path/filepath"
"github.com/gorilla/mux"
)
func main() {
r := mux.NewRouter()
// here is where i set up the file servers
publicHandler := http.FileServer(http.Dir(filepath.Join("web","public")))
r.PathPrefix("/pubic/").Handler(http.StripPrefix("/pubic/",publicHandler))
assetHandler := http.FileServer(http.Dir("assets"))
r.PathPrefix("/assets/").Handler(http.StripPrefix("/assets/",assetHandler))
r.HandleFunc("/",s.HandleHome())
port := fmt.Sprintf(":%d",5123)
http.ListenAndServe(port,r)
}
func (s *Server) HandleHome() http.HandlerFunc {
tpl,err := template.New("").ParseFiles("web/templates/index.tpl")
if err != nil {
panic(err)
}
return func(w http.ResponseWriter,r *http.Request) {
err = tpl.ExecuteTemplate(w,"index",nil)
if err != nil {
http.Error(w,"oops",http.StatusInternalServerError)
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。