【发布时间】:2015-11-30 01:20:25
【问题描述】:
您好,我在让我的模板正确显示我的 CSS 文件时遇到问题。它正在正确读取我的 imgs,但我的 CSS 文件中的任何内容都无法正确显示。当我使用 Delve 运行时,它会正确获取路径,所以我不确定发生了什么。这是我的代码。
package main
import (
"bufio"
"log"
"net/http"
"os"
"strings"
"text/template"
)
func main() {
templates := populateTemplates()
http.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
requestedFile := req.URL.Path[1:]
template := templates.Lookup(requestedFile + ".html")
if template != nil {
template.Execute(w, nil)
} else {
w.WriteHeader(404)
}
})
http.HandleFunc("/img/", serveResource)
http.HandleFunc("/css/", serveResource)
http.ListenAndServe(":8080", nil)
}
func serveResource(w http.ResponseWriter, req *http.Request) {
path := "../../public" + req.URL.Path
var contentType string
if strings.HasSuffix(path, ".css") {
contentType = "text/css"
} else if strings.HasSuffix(path, ".png") {
contentType = "image/png"
} else {
contentType = "text/plain"
}
f, err := os.Open(path)
if err != nil {
w.WriteHeader(404)
} else {
defer f.Close()
w.Header().Add("Content Type", contentType)
br := bufio.NewReader(f)
br.WriteTo(w)
}
}
func populateTemplates() *template.Template {
result := template.New("templates")
basePath := "../../templates"
templateFolder, err := os.Open(basePath)
if err != nil {
log.Fatal(err)
}
defer templateFolder.Close()
templatePathsRaw, _ := templateFolder.Readdir(-1)
templatePaths := new([]string)
for _, pathInfo := range templatePathsRaw {
if !pathInfo.IsDir() {
*templatePaths = append(*templatePaths, basePath+"/"+pathInfo.Name())
}
}
result.ParseFiles(*templatePaths...)
return result
}
(也在http://pastebin.com/7Vcm5t75上)
我有一个包含 bin、pkg、src、public 和模板的主文件夹。然后在 src 中是一个包含 main.go 的主文件夹。 public 包含img、css、脚本。 Img 里面有我的图片。 CSS中有我的CSS文件。然后模板中有我的两个 html 页面。下面以树形形式展示:
├── bin
├── pkg
├── public
│ ├── css
│ ├── img
│ └── scripts
├── src
│ └── main
└── templates
非常感谢任何帮助。
【问题讨论】:
-
请使用
tree命令列出您的文件夹。 -
添加到原帖
-
作为提示:将您的
serveResource函数替换为http.ServeFile和/或查看http.FileServer的文档 - 这将满足您的需求。 -
谢谢你工作得更好!
-
这个问题解决了吗?