golang错误提供静态文件
问题描述:
当执行模板golang错误提供静态文件
panic: open templates/*.html: The system cannot find the path specified.
时我无法弄清楚去郎此错误
另一个问题是,我的公用文件夹不能从CSS提供服务,我不知道为什么。
代码:
package main
import (
"net/http"
"github.com/gorilla/mux"
"html/template"
"log"
)
var tpl *template.Template
func init() {
tpl = template.Must(template.ParseGlob("templates/*.html"))
}
func main() {
r := mux.NewRouter()
r.HandleFunc("/",home)
http.Handle("/public/", http.StripPrefix("/public/",
http.FileServer(http.Dir("/pub"))))
http.ListenAndServe(":8080", r)
}
func home(writer http.ResponseWriter, request *http.Request) {
err := tpl.ExecuteTemplate(writer, "index.html", nil)
if err != nil {
log.Println(err)
http.Error(writer, "Internal server error", http.StatusInternalServerError)
}
}
我的文件夹是这样的:
bin pkg pub css home.css js src github.com gorila/mux templates index.html
我GOROOT指向含有bin
pkg
src
文件夹project
当我做templates
文件夹外部src
它工作正常,但我认为这是不正确的ev什么东西一定在src
对不对?
的index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<link href="../public/css/home.css" type="text/css" rel="stylesheet" />
</head>
<body>
<h1>welcome! hi</h1>
</body>
</html>
在这里,我不能服务于CSS
更新::
的第一个问题就解决了模板文件夹中。
但我仍然解决不了第二个问题
答
我个人觉得标准http
库非常好,简单的此类任务。但是,如果你坚持大猩猩mux
这里是我在你的代码中发现的问题:
func main() {
...
http.Handle("/public/", http.StripPrefix("/public/", http.FileServer(http.Dir("/pub"))))
http.ListenAndServe(":8080", r)
}
一方面您使用http.Handle
为静态文件,但是,从另一方面你给r
到http.ListenAndServe
。
为了解决这个问题只是改变这一行到:
r.PathPrefix("/public/").Handler(
http.StripPrefix("/public/",
http.FileServer(http.Dir("/pub/"))))
如果可以的话,我想用flag
设置不同的路径模板目录和公共目录中,因此会很容易建议部署和运行您的服务器。
换句话说,而不是硬编码的路径,这些路径,你可以运行:
./myserver -templates=/loca/templates -public=/home/root/public
要做到这一点只需添加以下内容:
import "flag"
....
func main() {
var tpl *template.Template
var templatesPath, publicPath string
flag.StringVar(&templatesPath, "templates", "./templates", "Path to templates")
flag.StringVar(&publicPath, "public", "./public", "Path to public")
flag.Parse()
tpl = template.Must(template.ParseGlob(templatesPath+"/*.html"))
r.HandleFunc("/", handlerHomeTemplates(tpl))
r.PathPrefix("/public/").Handler(http.StripPrefix("/public/", http.FileServer(http.Dir(publicPath))))
...
}
func handlerHomeTemplates(tpl *template.Template) http.HandlerFunc {
return http.HandlerFunc(func((writer http.ResponseWriter, request *http.Request) {
err := tpl.ExecuteTemplate(writer, "index.html", nil)
if err != nil {
...
}
})
}
即使认为init
功能是一个很好的我认为这是一个很好的习惯,除非需要它才能避免它。这就是为什么我在main
函数中完成所有初始化并使用handlerHomeTemplates
返回使用templatesPath
的新http.HandleFunc
。
模板文件夹只需要靠近您在构建到二进制文件时所制作的二进制文件。源文件只需要src文件夹。因为模板是在运行时加载的*而不是编译时它不需要在src文件夹中。 – gabeio
所以你的意思是,当我去生产我将使用bin文件夹而不是src文件夹?所以我很抱歉问,但生产中使用的src是什么?我的意思是如果有人使用我的代码,他将如何使用我的代码?从包? –
所以你的意思是我从'src'出来文件夹并将其放在'project'文件夹下,然后将'parseGlob'从'templates/*。html'改为'src/templates/*。html'? –