Go 使用路由器提供静态文件和内容
我试图提供静态文件,其中包括javascript、css、html文件 但它无法加载Go 使用路由器提供静态文件和内容,go,Go,我试图提供静态文件,其中包括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
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)
第一行将静态文件处理程序注册到。第二行运行服务器,根处理程序设置为router
。默认mux及其注册的静态文件处理程序将被忽略
有两种方法可以解决此问题:
- 配置
以使用处理静态文件路由器
- 使用默认mux注册
,并使用默认mux作为根处理程序。另外,在“/static”后面添加一个“/”以服务于整个树和文件服务器路由器
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) http.Handle("/", router) http.ListenAndServe(":8000", nil)
这些建议假设您正在使用诸如“/static/js/example.js”之类的URI为静态资源提供服务。如果您使用的URI类似于“/js/example.js”,那么您需要在static中分别注册每个目录。问题在于以下几行:
http.Handle("/static", http.FileServer(http.Dir("static")))
http.ListenAndServe(":8000", router)
第一行将静态文件处理程序注册到。第二行运行服务器,根处理程序设置为router
。默认mux及其注册的静态文件处理程序将被忽略
有两种方法可以解决此问题:
- 配置
以使用处理静态文件路由器
- 使用默认mux注册
,并使用默认mux作为根处理程序。另外,在“/static”后面添加一个“/”以服务于整个树和文件服务器路由器
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) http.Handle("/", router) http.ListenAndServe(":8000", nil)
这些建议假设您正在使用诸如“/static/js/example.js”之类的URI为静态资源提供服务。如果您使用的URI类似于“/js/example.js”,那么您需要在static中分别注册每个目录。对于一个静态文件,您试图
获取什么url?(即)应该http.Handle(“/static”,http.FileServer(http.Dir(“static”))
berouter.Handler(“GET”),http.FileServer(http.Dir(“static”))
?对于静态文件,您试图获取
的url是什么?(即)应该http.Handle(“/static”),http.FileServer(http.Dir(“static”))
berouter.Handler(“GET”,“/static”,http.FileServer(http.Dir(“static”))
?我刚刚添加了文件结构。ThanksI刚刚添加了文件结构。谢谢