gpt4 book ai didi

Go Serve static 文件,内容与路由器

转载 作者:IT王子 更新时间:2023-10-29 02:34:23 26 4
gpt4 key购买 nike

我正在尝试提供包括 javascript 、 css 、 html 文件在内的静态文件

但是无法加载static 目录中的所有外部文件

我做错了什么?

请帮帮我

router := httprouter.New()

handler := func(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
type Page struct {
Title string
}
tp := template.Must(template.ParseFiles("templates/main.html", "templates/base.html"))
tp.ExecuteTemplate(w, "base", &Page{Title: "AAAAA"})
}

router.Handle("GET", "/", handler)
// func (r *Router) Handle(method, path string, handle Handle)
// func (r *Router) Handler(method, path string, handler http.Handler)
// func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)

router.Handle("GET", "/aaa", aaa.aaaHandler)

router.Handle("POST", "/aaa_01_submit", aaa.aaa01Submit)
router.Handle("GET", "/aaa_01_run", aaa.aaa01Run)

http.Handle("/static", http.FileServer(http.Dir("static")))
http.ListenAndServe(":8000", router)

这是我的文件

/app
/templates
main.html
base.html
/static
/js
files to read...
/lib
/css
main.go

最佳答案

问题出在这几行:

http.Handle("/static", http.FileServer(http.Dir("static")))
http.ListenAndServe(":8000", router)

第一行使用 default mux 注册静态文件处理程序.第二行运行服务器,根处理程序设置为 router。默认的 mux 和向其注册的静态文件处理程序将被忽略。

有两种方法可以解决这个问题:

  • 配置router使用ServeFiles处理静态文件.

    router.ServeFiles("/static/*filepath", http.Dir("static"))
  • 使用默认 mux 注册 router 并使用默认 mux 作为根处理程序。此外,将尾随“/”添加到“/static”以服务于整个树和 strip the "/static/" prefix用于文件服务器。

    http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
    http.Handle("/", router)
    http.ListenAndServe(":8000", nil)

这些建议假定您使用“/static/js/example.js”等 URI 为静态资源提供服务。如果您使用像“/js/example.js”这样的 URI,那么您需要分别在静态中注册每个目录。

关于Go Serve static 文件,内容与路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26162048/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com