tôi thiết lập một tuyến đường trong server.js
trong gói main
trong thư mục gốc của dự ántải hình ảnh và css trong Golang
http.HandleFunc("/",route.IndexHandler)
Các IndexHandler
được thực hiện trong gói route
như thế này:
func IndexHandler(w http.ResponseWriter, r *http.Request) {
data:=struct{
Name string
}{
"My name",
}
util.RenderTemplate(w, "index", data)
}
Các Chức năng RenderTemplate
được triển khai trong gói util
như sau:
func RenderTemplate(w http.ResponseWriter, tmpl string, data interface{}) {
cwd, _ := os.Getwd()
t, err := template.ParseFiles(filepath.Join(cwd, "./view/" + tmpl + ".html"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = t.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
Cấu trúc thư mục trong dự án như thế này:
/
/public/css
/public/images
/public/js
/route
/view
index.html
xem nằm trong thư mục view
, router nằm trong thư mục route
Trong index.html
tôi bao gồm các nguồn lực như thế này:
<link rel="stylesheet" type="text/css" href="../public/css/style.css">
<img src="../public/images/img_landing_page_mac.png">
Khi yêu cầu đường dẫn thích hợp, index.html
vẫn được hiển thị, nhưng hình ảnh và biểu định kiểu không được tải. Làm thế nào tôi có thể làm để bao gồm chúng trong Golang html mẫu động cơ?
Nó hoàn toàn làm việc! Cảm ơn nhiều! – necroface