当执行模板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
更新::
的第一个问题就解决了模板文件夹中。
但我仍然解决不了第二个问题
模板文件夹只需要靠近您在构建到二进制文件时所制作的二进制文件。源文件只需要src文件夹。因为模板是在运行时加载的*而不是编译时它不需要在src文件夹中。 – gabeio
所以你的意思是,当我去生产我将使用bin文件夹而不是src文件夹?所以我很抱歉问,但生产中使用的src是什么?我的意思是如果有人使用我的代码,他将如何使用我的代码?从包? –
所以你的意思是我从'src'出来文件夹并将其放在'project'文件夹下,然后将'parseGlob'从'templates/*。html'改为'src/templates/*。html'? –